id
stringlengths
11
116
type
stringclasses
1 value
granularity
stringclasses
4 values
content
stringlengths
16
477k
metadata
dict
file_router_162475945752523302
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/shift4.rs // Contains: 1 structs, 0 enums use std::str::FromStr; use masking::Secret; use router::types::{self, domain, storage::enums}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct Shift4Test; impl ConnectorActions for Shift4Test {} impl utils::Connector for Shift4Test { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Shift4; utils::construct_connector_data_old( Box::new(Shift4::new()), types::Connector::Shift4, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .shift4 .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "shift4".to_string() } } static CONNECTOR: Shift4Test = Shift4Test {}; // 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(None, None).await.unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR.make_payment(None, None).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let connector = CONNECTOR; let response = connector .authorize_and_capture_payment(None, None, None) .await; assert_eq!(response.unwrap().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 connector = CONNECTOR; let response = connector .authorize_and_capture_payment( None, Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), None, ) .await; assert_eq!(response.unwrap().status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let connector = CONNECTOR; let authorize_response = connector.authorize_payment(None, None).await.unwrap(); 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() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { // Authorize let authorize_response = CONNECTOR.make_payment(None, None).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(), ), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let connector = CONNECTOR; let response = connector .authorize_and_void_payment( None, Some(types::PaymentsCancelData { connector_transaction_id: "".to_string(), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), None, ) .await; assert_eq!(response.unwrap().status, enums::AttemptStatus::Pending); //shift4 doesn't allow voiding a payment } // Cards Negative scenarios // Creates a payment with incorrect card number. #[actix_web::test] async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4024007134364842").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "The card's security code failed verification.".to_string(), ); } // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_succeed_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("asdasd".to_string()), //shift4 accept invalid CVV as it doesn't accept CVV ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged); } // 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 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "The 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 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "The card has expired.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { // Authorize let authorize_response = CONNECTOR.make_payment(None, None).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"); // Void let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, None) .await .unwrap(); assert_eq!(void_response.status, enums::AttemptStatus::Pending); //shift4 doesn't allow voiding a payment } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { // Capture let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, None) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("Charge '123456789' does not exist") ); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let connector = CONNECTOR; let response = connector .make_payment_and_refund(None, None, None) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let connector = CONNECTOR; let response = connector .auth_capture_and_refund(None, None, None) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let connector = CONNECTOR; let refund_response = connector .make_payment_and_refund( None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( refund_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 connector = CONNECTOR; let response = connector .auth_capture_and_refund( None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { let connector = CONNECTOR; connector .make_payment_and_multiple_refund( None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await; } // 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 connector = CONNECTOR; let response = connector .make_payment_and_refund( None, Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Invalid Refund data", ); } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let connector = CONNECTOR; let refund_response = connector .make_payment_and_refund(None, None, None) .await .unwrap(); let response = connector .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, None, ) .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 connector = CONNECTOR; let refund_response = connector .auth_capture_and_refund(None, None, None) .await .unwrap(); let response = connector .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); }
{ "crate": "router", "file": "crates/router/tests/connectors/shift4.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-3580526842883627467
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/tsys.rs // Contains: 1 structs, 0 enums use std::{str::FromStr, time::Duration}; use cards::CardNumber; use masking::Secret; use router::types::{self, domain, storage::enums}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct TsysTest; impl ConnectorActions for TsysTest {} impl utils::Connector for TsysTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Tsys; utils::construct_connector_data_old( Box::new(Tsys::new()), types::Connector::Tsys, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .tsys .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "tsys".to_string() } } static CONNECTOR: TsysTest = TsysTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details(amount: i64) -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { amount, payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: CardNumber::from_str("4111111111111111").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }) } // 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(101), 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(100), 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(130), 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(140), 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(150), 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(160), Some(types::PaymentsCaptureData { amount_to_capture: 160, ..utils::PaymentCaptureType::default().0 }), Some(types::RefundsData { refund_amount: 160, ..utils::PaymentRefundType::default().0 }), 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(170), Some(types::PaymentsCaptureData { amount_to_capture: 170, ..utils::PaymentCaptureType::default().0 }), 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(180), Some(types::PaymentsCaptureData { amount_to_capture: 180, ..utils::PaymentCaptureType::default().0 }), Some(types::RefundsData { refund_amount: 180, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); tokio::time::sleep(Duration::from_secs(10)).await; 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(200), 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(210), 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(220), Some(types::RefundsData { refund_amount: 220, ..utils::PaymentRefundType::default().0 }), 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(230), 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(250), 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(100), None, get_default_payment_info(), ) .await .unwrap(); tokio::time::sleep(Duration::from_secs(10)).await; 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("".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "The value of element cvv2 is not valid.".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, "The value of element 'expirationDate' is not valid., ".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("abcd".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "The value of element 'expirationDate' is not valid., ".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector Refunds the payment on Void call for Auto Captured Payment"] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(500), 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("Record(s) Not Found.") ); } // 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(100), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Return Not Allowed.", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
{ "crate": "router", "file": "crates/router/tests/connectors/tsys.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-586572510864124749
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/hyperwallet.rs // Contains: 1 structs, 0 enums use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct HyperwalletTest; impl ConnectorActions for HyperwalletTest {} impl utils::Connector for HyperwalletTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Hyperwallet; utils::construct_connector_data_old( Box::new(Hyperwallet::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .hyperwallet .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "hyperwallet".to_string() } } static CONNECTOR: HyperwalletTest = HyperwalletTest {}; 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: PaymentMethodData::Card(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: PaymentMethodData::Card(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: PaymentMethodData::Card(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
{ "crate": "router", "file": "crates/router/tests/connectors/hyperwallet.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-4603182313914938021
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/cryptopay.rs // Contains: 1 structs, 0 enums use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails}; use masking::Secret; use router::types::{self, api, domain, storage::enums, PaymentAddress}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct CryptopayTest; impl ConnectorActions for CryptopayTest {} impl utils::Connector for CryptopayTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Cryptopay; utils::construct_connector_data_old( Box::new(Cryptopay::new()), types::Connector::Cryptopay, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .cryptopay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "cryptopay".to_string() } } static CONNECTOR: CryptopayTest = CryptopayTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::IN), ..Default::default() }), phone: Some(PhoneDetails { number: Some(Secret::new("9123456789".to_string())), country_code: Some("+91".to_string()), }), email: None, }), None, None, )), ..Default::default() }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { amount: 1, currency: enums::Currency::USD, payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData { pay_currency: Some("XRP".to_string()), network: None, }), confirm: true, statement_descriptor_suffix: None, statement_descriptor: None, setup_future_usage: None, mandate_id: None, off_session: None, setup_mandate_details: None, browser_info: None, order_details: None, order_category: None, email: None, customer_name: None, payment_experience: None, payment_method_type: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None, router_return_url: Some(String::from("https://google.com/")), webhook_url: None, complete_authorize_url: None, capture_method: None, customer_id: None, surcharge_details: None, request_incremental_authorization: false, metadata: None, authentication_data: None, customer_acceptance: None, ..utils::PaymentAuthorizeType::default().0 }) } // Creates a payment using the manual capture flow #[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::AuthenticationPending); let resp = response.response.ok().unwrap(); let endpoint = match resp { types::PaymentsResponseData::TransactionResponse { redirection_data, .. } => Some(redirection_data), _ => None, }; assert!(endpoint.is_some()) } // Synchronizes a successful transaction. #[actix_web::test] async fn should_sync_authorized_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "ea684036-2b54-44fa-bffe-8256650dce7c".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a unresolved(underpaid) transaction. #[actix_web::test] async fn should_sync_unresolved_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "7993d4c2-efbc-4360-b8ce-d1e957e6f827".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Unresolved); }
{ "crate": "router", "file": "crates/router/tests/connectors/cryptopay.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-5130657526155462824
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/checkout.rs // Contains: 1 structs, 0 enums use masking::Secret; use router::types::{self, domain, storage::enums}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct CheckoutTest; impl ConnectorActions for CheckoutTest {} impl utils::Connector for CheckoutTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Checkout; utils::construct_connector_data_old( Box::new(Checkout::new()), types::Connector::Checkout, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .checkout .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "checkout".to_string() } } static CONNECTOR: CheckoutTest = CheckoutTest {}; 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). #[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); } // Captures a payment using the manual capture flow (Non 3DS). #[serial_test::serial] #[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). #[serial_test::serial] #[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). #[serial_test::serial] #[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). #[serial_test::serial] #[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). #[serial_test::serial] #[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). #[serial_test::serial] #[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] #[ignore = "Connector Error, needs to be looked into and fixed"] 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). #[serial_test::serial] #[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). #[serial_test::serial] #[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). #[serial_test::serial] #[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). #[serial_test::serial] #[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). #[serial_test::serial] #[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] #[ignore = "Connector Error, needs to be looked into and fixed"] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); tokio::time::sleep(std::time::Duration::from_secs(5)).await; 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. #[serial_test::serial] #[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, "cvv_invalid".to_string(), ); } // Creates a payment with incorrect expiry month. #[serial_test::serial] #[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, "card_expiry_month_invalid".to_string(), ); } // Creates a payment with incorrect expiry year. #[serial_test::serial] #[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, "card_expired".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[serial_test::serial] #[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().status_code, 403); } // Captures a payment using invalid connector payment id. #[serial_test::serial] #[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().status_code, 404); } // Refunds a payment with refund amount higher than payment amount. #[serial_test::serial] #[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_exceeds_balance", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
{ "crate": "router", "file": "crates/router/tests/connectors/checkout.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_103298505797616744
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/billwerk.rs // Contains: 1 structs, 0 enums use masking::Secret; use router::types::{self, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct BillwerkTest; impl ConnectorActions for BillwerkTest {} impl utils::Connector for BillwerkTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Billwerk; utils::construct_connector_data_old( Box::new(Billwerk::new()), // Added as Dummy connector as template code is added for future usage types::Connector::DummyConnector1, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .billwerk .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "billwerk".to_string() } } static CONNECTOR: BillwerkTest = BillwerkTest {}; 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
{ "crate": "router", "file": "crates/router/tests/connectors/billwerk.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-3007731470535182105
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/ebanx.rs // Contains: 1 structs, 0 enums use masking::Secret; use router::types::{self, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct EbanxTest; impl ConnectorActions for EbanxTest {} impl utils::Connector for EbanxTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Ebanx; utils::construct_connector_data_old( Box::new(Ebanx::new()), types::Connector::Ebanx, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .ebanx .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "ebanx".to_string() } } static CONNECTOR: EbanxTest = EbanxTest {}; 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: types::domain::PaymentMethodData::Card(types::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: types::domain::PaymentMethodData::Card(types::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: types::domain::PaymentMethodData::Card(types::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
{ "crate": "router", "file": "crates/router/tests/connectors/ebanx.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_4379201635580989956
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/aci.rs // Contains: 1 structs, 0 enums use std::str::FromStr; use hyperswitch_domain_models::{ address::{Address, AddressDetails, PhoneDetails}, payment_method_data::{Card, PaymentMethodData}, router_request_types::AuthenticationData, }; use masking::Secret; use router::types::{self, storage::enums, PaymentAddress}; use crate::{ connector_auth, utils::{self, ConnectorActions, PaymentInfo}, }; #[derive(Clone, Copy)] struct AciTest; impl ConnectorActions for AciTest {} impl utils::Connector for AciTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Aci; utils::construct_connector_data_old( Box::new(Aci::new()), types::Connector::Aci, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .aci .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "aci".to_string() } } static CONNECTOR: AciTest = AciTest {}; fn get_default_payment_info() -> Option<PaymentInfo> { Some(PaymentInfo { address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("John".to_string())), last_name: Some(Secret::new("Doe".to_string())), line1: Some(Secret::new("123 Main St".to_string())), city: Some("New York".to_string()), state: Some(Secret::new("NY".to_string())), zip: Some(Secret::new("10001".to_string())), country: Some(enums::CountryAlpha2::US), ..Default::default() }), phone: Some(PhoneDetails { number: Some(Secret::new("+1234567890".to_string())), country_code: Some("+1".to_string()), }), email: None, }), None, None, )), ..Default::default() }) } fn get_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), card_cvc: Secret::new("999".to_string()), card_holder_name: Some(Secret::new("John Doe".to_string())), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }) } fn get_threeds_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), card_cvc: Secret::new("999".to_string()), card_holder_name: Some(Secret::new("John Doe".to_string())), ..utils::CCardType::default().0 }), enrolled_for_3ds: true, authentication_data: Some(AuthenticationData { eci: Some("05".to_string()), cavv: Secret::new("jJ81HADVRtXfCBATEp01CJUAAAA".to_string()), threeds_server_transaction_id: Some("9458d8d4-f19f-4c28-b5c7-421b1dd2e1aa".to_string()), message_version: Some(common_utils::types::SemanticVersion::new(2, 1, 0)), ds_trans_id: Some("97267598FAE648F28083B2D2AF7B1234".to_string()), created_at: common_utils::date_time::now(), challenge_code: Some("01".to_string()), challenge_cancel: None, challenge_code_reason: Some("01".to_string()), message_extension: None, acs_trans_id: None, authentication_type: None, }), ..utils::PaymentAuthorizeType::default().0 }) } #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(get_payment_authorize_data(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( get_payment_authorize_data(), None, get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( get_payment_authorize_data(), 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); } #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(get_payment_authorize_data(), 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,); } #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( get_payment_authorize_data(), 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); } #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( get_payment_authorize_data(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( get_payment_authorize_data(), 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, ); } #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( get_payment_authorize_data(), 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, ); } #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(get_payment_authorize_data(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(get_payment_authorize_data(), 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,); } #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund( get_payment_authorize_data(), None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( get_payment_authorize_data(), 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, ); } #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( get_payment_authorize_data(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund( get_payment_authorize_data(), 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, ); } #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert!( response.response.is_err(), "Payment should fail with incorrect CVC" ); } #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert!( response.response.is_err(), "Payment should fail with invalid expiry month" ); } #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert!( response.response.is_err(), "Payment should fail with incorrect expiry year" ); } #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(get_payment_authorize_data(), 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!( void_response.response.is_err(), "Void should fail for already captured payment" ); } #[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!( capture_response.response.is_err(), "Capture should fail for invalid payment ID" ); } #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( get_payment_authorize_data(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert!( response.response.is_err(), "Refund should fail when amount exceeds payment amount" ); } #[actix_web::test] #[ignore] async fn should_make_threeds_payment() { let authorize_response = CONNECTOR .make_payment( get_threeds_payment_authorize_data(), get_default_payment_info(), ) .await .unwrap(); assert!( authorize_response.status == enums::AttemptStatus::AuthenticationPending || authorize_response.status == enums::AttemptStatus::Charged, "3DS payment should result in AuthenticationPending or Charged status, got: {:?}", authorize_response.status ); if let Ok(types::PaymentsResponseData::TransactionResponse { redirection_data, .. }) = &authorize_response.response { if authorize_response.status == enums::AttemptStatus::AuthenticationPending { assert!( redirection_data.is_some(), "3DS flow should include redirection data for authentication" ); } } } #[actix_web::test] #[ignore] async fn should_authorize_threeds_payment() { let response = CONNECTOR .authorize_payment( get_threeds_payment_authorize_data(), get_default_payment_info(), ) .await .expect("Authorize 3DS payment response"); assert!( response.status == enums::AttemptStatus::AuthenticationPending || response.status == enums::AttemptStatus::Authorized, "3DS authorization should result in AuthenticationPending or Authorized status, got: {:?}", response.status ); } #[actix_web::test] #[ignore] async fn should_sync_threeds_payment() { let authorize_response = CONNECTOR .authorize_payment( get_threeds_payment_authorize_data(), get_default_payment_info(), ) .await .expect("Authorize 3DS payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::AuthenticationPending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync 3DS response"); assert!( response.status == enums::AttemptStatus::AuthenticationPending || response.status == enums::AttemptStatus::Authorized, "3DS sync should maintain AuthenticationPending or Authorized status" ); }
{ "crate": "router", "file": "crates/router/tests/connectors/aci.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-8372316464087215469
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/zen.rs // Contains: 1 structs, 0 enums use std::str::FromStr; use cards::CardNumber; use common_utils::{pii::Email, types::MinorUnit}; use hyperswitch_domain_models::types::OrderDetailsWithAmount; use masking::Secret; use router::types::{self, domain, storage::enums}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct ZenTest; impl ConnectorActions for ZenTest {} impl utils::Connector for ZenTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Zen; utils::construct_connector_data_old( Box::new(&Zen), types::Connector::Zen, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .zen .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "zen".to_string() } } static CONNECTOR: ZenTest = ZenTest {}; // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card"] #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(None, None) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card and capture is not supported"] #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(None, None, None) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card and capture is not supported"] #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( None, Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), None, ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card"] #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(None, None) .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(), ), encoded_data: None, capture_method: None, sync_type: types::SyncRequestType::SinglePaymentSync, connector_meta: None, mandate_id: None, payment_method_type: None, currency: enums::Currency::USD, payment_experience: None, amount: MinorUnit::new(100), integrity_object: None, ..Default::default() }), None, ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card and void is not supported"] #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( None, Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), None, ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card and capture is not supported"] #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund(None, None, None, None) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card and capture is not supported"] #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( None, None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card and capture is not supported"] #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund(None, None, None, None) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card"] #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR.make_payment(None, None).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card"] #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR.make_payment(None, None).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(), ), encoded_data: None, capture_method: Some(enums::CaptureMethod::Automatic), sync_type: types::SyncRequestType::SinglePaymentSync, connector_meta: None, mandate_id: None, payment_method_type: None, currency: enums::Currency::USD, payment_experience: None, amount: MinorUnit::new(100), integrity_object: None, ..Default::default() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card"] #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(None, None, None) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card"] #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .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). #[ignore = "Connector triggers 3DS payment on test card"] #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card"] #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(None, None, None) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect card number. #[actix_web::test] async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), order_details: Some(vec![OrderDetailsWithAmount { product_name: "iphone 13".to_string(), quantity: 1, amount: MinorUnit::new(1000), product_img_link: None, requires_shipping: None, product_id: None, category: None, sub_category: None, brand: None, product_type: None, product_tax_code: None, tax_rate: None, total_tax_amount: None, description: None, sku: None, upc: None, commodity_code: None, unit_of_measure: None, total_amount: None, unit_discount_amount: None, }]), email: Some(Email::from_str("test@gmail.com").unwrap()), webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( response .response .unwrap_err() .message .split_once(';') .unwrap() .0, "Request data doesn't pass validation".to_string(), ); } // 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 }), order_details: Some(vec![OrderDetailsWithAmount { product_name: "iphone 13".to_string(), quantity: 1, amount: MinorUnit::new(1000), product_img_link: None, requires_shipping: None, product_id: None, category: None, sub_category: None, brand: None, product_type: None, product_tax_code: None, tax_rate: None, total_tax_amount: None, description: None, sku: None, upc: None, commodity_code: None, unit_of_measure: None, total_amount: None, unit_discount_amount: None, }]), email: Some(Email::from_str("test@gmail.com").unwrap()), webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( response .response .unwrap_err() .message .split_once(';') .unwrap() .0, "Request data doesn't pass validation".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 }), order_details: Some(vec![OrderDetailsWithAmount { product_name: "iphone 13".to_string(), quantity: 1, amount: MinorUnit::new(1000), product_img_link: None, requires_shipping: None, product_id: None, category: None, sub_category: None, brand: None, product_type: None, product_tax_code: None, tax_rate: None, total_tax_amount: None, description: None, sku: None, upc: None, commodity_code: None, unit_of_measure: None, total_amount: None, unit_discount_amount: None, }]), email: Some(Email::from_str("test@gmail.com").unwrap()), webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( response .response .unwrap_err() .message .split_once(';') .unwrap() .0, "Request data doesn't pass validation".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 }), order_details: Some(vec![OrderDetailsWithAmount { product_name: "iphone 13".to_string(), quantity: 1, amount: MinorUnit::new(1000), product_img_link: None, requires_shipping: None, product_id: None, category: None, sub_category: None, brand: None, product_type: None, product_tax_code: None, tax_rate: None, total_tax_amount: None, description: None, sku: None, upc: None, commodity_code: None, unit_of_measure: None, total_amount: None, unit_discount_amount: None, }]), email: Some(Email::from_str("test@gmail.com").unwrap()), webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( response .response .unwrap_err() .message .split_once(';') .unwrap() .0, "Request data doesn't pass validation".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card and void is not supported"] #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR.make_payment(None, None).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, None) .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. #[ignore = "Connector triggers 3DS payment on test card and capture is not supported"] #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, None) .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. #[ignore = "Connector triggers 3DS payment on test card"] #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( None, Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), None, ) .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
{ "crate": "router", "file": "crates/router/tests/connectors/zen.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-5254855288319574163
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/elavon.rs // Contains: 1 structs, 0 enums use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct ElavonTest; impl ConnectorActions for ElavonTest {} impl utils::Connector for ElavonTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Elavon; utils::construct_connector_data_old( Box::new(Elavon::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) // api::ConnectorData { // connector: Box::new(Elavon::new()), // connector_name: types::Connector::Elavon, // get_token: types::api::GetToken::Connector, // merchant_connector_id: None, // } } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .elavon .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "elavon".to_string() } } static CONNECTOR: ElavonTest = ElavonTest {}; 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: PaymentMethodData::Card(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: PaymentMethodData::Card(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: PaymentMethodData::Card(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
{ "crate": "router", "file": "crates/router/tests/connectors/elavon.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-7455286383510016532
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/taxjar.rs // Contains: 1 structs, 0 enums 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 TaxjarTest; impl ConnectorActions for TaxjarTest {} impl utils::Connector for TaxjarTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Taxjar; utils::construct_connector_data_old( Box::new(Taxjar::new()), types::Connector::Adyen, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .taxjar .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "taxjar".to_string() } } static CONNECTOR: TaxjarTest = TaxjarTest {}; 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
{ "crate": "router", "file": "crates/router/tests/connectors/taxjar.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-8068971526038260071
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/authorizedotnet.rs // Contains: 1 structs, 0 enums use std::str::FromStr; use masking::Secret; use router::types::{self, domain, storage::enums}; use crate::{ connector_auth, utils::{self, ConnectorActions, PaymentInfo}, }; #[derive(Clone, Copy)] struct AuthorizedotnetTest; impl ConnectorActions for AuthorizedotnetTest {} impl utils::Connector for AuthorizedotnetTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Authorizedotnet; utils::construct_connector_data_old( Box::new(Authorizedotnet::new()), types::Connector::Authorizedotnet, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .authorizedotnet .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "authorizedotnet".to_string() } } static CONNECTOR: AuthorizedotnetTest = AuthorizedotnetTest {}; fn get_payment_method_data() -> domain::Card { domain::Card { card_number: cards::CardNumber::from_str("5424000000000015").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), card_cvc: Secret::new("123".to_string()), ..Default::default() } } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let authorize_response = CONNECTOR .authorize_payment( Some(types::PaymentsAuthorizeData { amount: 300, payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }), Some(PaymentInfo::with_default_billing_name()), ) .await .expect("Authorize payment response"); assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); let txn_id = utils::get_connector_transaction_id(authorize_response.response).unwrap_or_default(); let psync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id), encoded_data: None, capture_method: None, ..Default::default() }), None, ) .await .expect("PSync response"); assert_eq!(psync_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 authorize_response = CONNECTOR .authorize_payment( Some(types::PaymentsAuthorizeData { amount: 301, payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }), Some(PaymentInfo::with_default_billing_name()), ) .await .expect("Authorize payment response"); assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); let txn_id = utils::get_connector_transaction_id(authorize_response.response).unwrap_or_default(); let psync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id.clone()), encoded_data: None, capture_method: None, ..Default::default() }), None, ) .await .expect("PSync response"); assert_eq!(psync_response.status, enums::AttemptStatus::Authorized); let cap_response = CONNECTOR .capture_payment( txn_id.clone(), Some(types::PaymentsCaptureData { amount_to_capture: 301, ..utils::PaymentCaptureType::default().0 }), None, ) .await .expect("Capture payment response"); assert_eq!(cap_response.status, enums::AttemptStatus::Pending); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::CaptureInitiated, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id), encoded_data: None, capture_method: None, ..Default::default() }), None, ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment( Some(types::PaymentsAuthorizeData { amount: 302, payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }), Some(PaymentInfo::with_default_billing_name()), ) .await .expect("Authorize payment response"); assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); let txn_id = utils::get_connector_transaction_id(authorize_response.response).unwrap_or_default(); let psync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id.clone()), encoded_data: None, capture_method: None, ..Default::default() }), None, ) .await .expect("PSync response"); assert_eq!(psync_response.status, enums::AttemptStatus::Authorized); let cap_response = CONNECTOR .capture_payment( txn_id.clone(), Some(types::PaymentsCaptureData { amount_to_capture: 150, ..utils::PaymentCaptureType::default().0 }), None, ) .await .expect("Capture payment response"); assert_eq!(cap_response.status, enums::AttemptStatus::Pending); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::CaptureInitiated, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id), encoded_data: None, capture_method: None, ..Default::default() }), None, ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); } // 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( Some(types::PaymentsAuthorizeData { amount: 303, payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }), Some(PaymentInfo::with_default_billing_name()), ) .await .expect("Authorize payment response"); assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); let txn_id = utils::get_connector_transaction_id(authorize_response.response).unwrap_or_default(); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id), encoded_data: None, capture_method: None, ..Default::default() }), None, ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS).x #[actix_web::test] async fn should_void_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment( Some(types::PaymentsAuthorizeData { amount: 304, payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }), Some(PaymentInfo::with_default_billing_name()), ) .await .expect("Authorize payment response"); assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); let txn_id = utils::get_connector_transaction_id(authorize_response.response).unwrap_or_default(); let psync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id.clone()), encoded_data: None, capture_method: None, ..Default::default() }), None, ) .await .expect("PSync response"); assert_eq!(psync_response.status, enums::AttemptStatus::Authorized); let void_response = CONNECTOR .void_payment( txn_id, Some(types::PaymentsCancelData { amount: Some(304), ..utils::PaymentCancelType::default().0 }), None, ) .await .expect("Void response"); assert_eq!(void_response.status, enums::AttemptStatus::VoidInitiated) } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let cap_response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { amount: 310, payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!(cap_response.status, enums::AttemptStatus::Pending); let txn_id = utils::get_connector_transaction_id(cap_response.response).unwrap_or_default(); let psync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::CaptureInitiated, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id.clone()), encoded_data: None, capture_method: None, ..Default::default() }), None, ) .await .expect("PSync response"); assert_eq!( psync_response.status, enums::AttemptStatus::CaptureInitiated ); } // 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( Some(types::PaymentsAuthorizeData { amount: 311, payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); 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::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), encoded_data: None, capture_method: None, ..Default::default() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, "60217566768".to_string(), None, None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment with empty card number. #[actix_web::test] async fn should_fail_payment_for_empty_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); let x = response.response.unwrap_err(); assert_eq!( x.message, "The 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:cardNumber' element is invalid - The value XX is invalid according to its datatype 'String' - The actual length is less than the MinLength value.", ); } // 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 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "The 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:cardCode' element is invalid - The value XXXXXXX is invalid according to its datatype 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:cardCode' - The actual length is greater than the MaxLength value.".to_string(), ); } // todo() // 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 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Credit card expiration date 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 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "The credit card has expired.".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( Some(types::PaymentsAuthorizeData { amount: 307, payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, None) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "The 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:amount' element is invalid - The value &#39;&#39; is invalid according to its datatype 'http://www.w3.org/2001/XMLSchema:decimal' - The string &#39;&#39; is not a valid Decimal value." ); } // 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, None) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, "The transaction cannot be found." ); } #[actix_web::test] #[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."] async fn should_partially_refund_manually_captured_payment() {} #[actix_web::test] #[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."] async fn should_refund_manually_captured_payment() {} #[actix_web::test] #[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."] async fn should_sync_manually_captured_refund() {} #[actix_web::test] #[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."] async fn should_refund_auto_captured_payment() {} #[actix_web::test] #[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."] async fn should_partially_refund_succeeded_payment() {} #[actix_web::test] #[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."] async fn should_refund_succeeded_payment_multiple_times() {} #[actix_web::test] #[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."] async fn should_fail_for_refund_amount_higher_than_payment_amount() {} // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
{ "crate": "router", "file": "crates/router/tests/connectors/authorizedotnet.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-8599951992626098359
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/payeezy.rs // Contains: 1 structs, 0 enums use std::str::FromStr; use cards::CardNumber; use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::Secret; use router::{ core::errors, types::{self, storage::enums, PaymentsAuthorizeData}, }; use crate::{ connector_auth, utils::{self, ConnectorActions, PaymentInfo}, }; #[derive(Clone, Copy)] struct PayeezyTest; impl ConnectorActions for PayeezyTest {} static CONNECTOR: PayeezyTest = PayeezyTest {}; impl utils::Connector for PayeezyTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Payeezy; utils::construct_connector_data_old( Box::new(&Payeezy), // Remove `dummy_connector` feature gate from module in `main.rs` when updating this to use actual connector variant types::Connector::DummyConnector1, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .payeezy .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "payeezy".to_string() } } impl PayeezyTest { fn get_payment_data() -> Option<PaymentsAuthorizeData> { Some(PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: CardNumber::from_str("4012000033330026").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }) } fn get_payment_info() -> Option<PaymentInfo> { Some(PaymentInfo { address: Some(types::PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { ..Default::default() }), phone: None, email: None, }), None, None, )), ..Default::default() }) } fn get_request_interval(self) -> u64 { 20 } } // 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(PayeezyTest::get_payment_data(), None) .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_payment(PayeezyTest::get_payment_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); let connector_payment_id = utils::get_connector_transaction_id(response.response.clone()).unwrap_or_default(); let connector_meta = utils::get_connector_metadata(response.response); let capture_data = types::PaymentsCaptureData { connector_meta, ..utils::PaymentCaptureType::default().0 }; let capture_response = CONNECTOR .capture_payment(connector_payment_id, Some(capture_data), None) .await .unwrap(); assert_eq!(capture_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_payment(PayeezyTest::get_payment_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); let connector_payment_id = utils::get_connector_transaction_id(response.response.clone()).unwrap_or_default(); let connector_meta = utils::get_connector_metadata(response.response); let capture_data = types::PaymentsCaptureData { connector_meta, amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }; let capture_response = CONNECTOR .capture_payment(connector_payment_id, Some(capture_data), None) .await .unwrap(); assert_eq!(capture_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore] async fn should_sync_authorized_payment() {} // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_payment(PayeezyTest::get_payment_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); let connector_payment_id = utils::get_connector_transaction_id(response.response.clone()).unwrap_or_default(); let connector_meta = utils::get_connector_metadata(response.response); tokio::time::sleep(std::time::Duration::from_secs( CONNECTOR.get_request_interval(), )) .await; // to avoid 404 error let response = CONNECTOR .void_payment( connector_payment_id, Some(types::PaymentsCancelData { connector_meta, amount: Some(100), currency: Some(diesel_models::enums::Currency::USD), ..utils::PaymentCancelType::default().0 }), None, ) .await .unwrap(); 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 authorize_response = CONNECTOR .authorize_payment( PayeezyTest::get_payment_data(), PayeezyTest::get_payment_info(), ) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); let capture_connector_meta = utils::get_connector_metadata(authorize_response.response); let capture_response = CONNECTOR .capture_payment( txn_id.clone(), Some(types::PaymentsCaptureData { connector_meta: capture_connector_meta, ..utils::PaymentCaptureType::default().0 }), PayeezyTest::get_payment_info(), ) .await .expect("Capture payment response"); let capture_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let refund_connector_metadata = utils::get_connector_metadata(capture_response.response); let response = CONNECTOR .refund_payment( capture_txn_id.clone(), Some(types::RefundsData { connector_transaction_id: capture_txn_id, connector_metadata: refund_connector_metadata, ..utils::PaymentRefundType::default().0 }), PayeezyTest::get_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 authorize_response = CONNECTOR .authorize_payment( PayeezyTest::get_payment_data(), PayeezyTest::get_payment_info(), ) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); let capture_connector_meta = utils::get_connector_metadata(authorize_response.response); let capture_response = CONNECTOR .capture_payment( txn_id.clone(), Some(types::PaymentsCaptureData { connector_meta: capture_connector_meta, ..utils::PaymentCaptureType::default().0 }), PayeezyTest::get_payment_info(), ) .await .expect("Capture payment response"); let capture_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let refund_connector_metadata = utils::get_connector_metadata(capture_response.response); let response = CONNECTOR .refund_payment( capture_txn_id.clone(), Some(types::RefundsData { refund_amount: 50, connector_transaction_id: capture_txn_id, connector_metadata: refund_connector_metadata, ..utils::PaymentRefundType::default().0 }), PayeezyTest::get_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] #[ignore] async fn should_sync_manually_captured_refund() {} // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment( PayeezyTest::get_payment_data(), PayeezyTest::get_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] #[ignore] async fn should_sync_auto_captured_payment() {} // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let captured_response = CONNECTOR.make_payment(None, None).await.unwrap(); assert_eq!(captured_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(captured_response.response.clone()); let connector_meta = utils::get_connector_metadata(captured_response.response); let response = CONNECTOR .refund_payment( txn_id.clone().unwrap(), Some(types::RefundsData { refund_amount: 100, connector_transaction_id: txn_id.unwrap(), connector_metadata: connector_meta, ..utils::PaymentRefundType::default().0 }), PayeezyTest::get_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 captured_response = CONNECTOR.make_payment(None, None).await.unwrap(); assert_eq!(captured_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(captured_response.response.clone()); let connector_meta = utils::get_connector_metadata(captured_response.response); let response = CONNECTOR .refund_payment( txn_id.clone().unwrap(), Some(types::RefundsData { refund_amount: 50, connector_transaction_id: txn_id.unwrap(), connector_metadata: connector_meta, ..utils::PaymentRefundType::default().0 }), PayeezyTest::get_payment_info(), ) .await .unwrap(); assert_eq!( 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() { let captured_response = CONNECTOR.make_payment(None, None).await.unwrap(); assert_eq!(captured_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(captured_response.response.clone()); let connector_meta = utils::get_connector_metadata(captured_response.response); for _x in 0..2 { let refund_response = CONNECTOR .refund_payment( txn_id.clone().unwrap(), Some(types::RefundsData { connector_metadata: connector_meta.clone(), connector_transaction_id: txn_id.clone().unwrap(), refund_amount: 50, ..utils::PaymentRefundType::default().0 }), PayeezyTest::get_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] #[ignore] async fn should_sync_refund() {} // Cards Negative scenarios // Creates a payment with incorrect card issuer. #[actix_web::test] async fn should_throw_not_implemented_for_unsupported_issuer() { let authorize_data = Some(PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: CardNumber::from_str("630495060000000000").unwrap(), ..utils::CCardType::default().0 }), capture_method: Some(enums::CaptureMethod::Automatic), ..utils::PaymentAuthorizeType::default().0 }); let response = CONNECTOR .make_payment(authorize_data, PayeezyTest::get_payment_info()) .await; assert_eq!( *response.unwrap_err().current_context(), errors::ConnectorError::NotSupported { message: "card".to_string(), connector: "Payeezy", } ) } // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_cvc: Secret::new("12345d".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( *response.response.unwrap_err().message, "The cvv provided must be numeric".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(PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( *response.response.unwrap_err().message, "Bad Request (25) - Invalid Expiry Date".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(PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Expiry Date is invalid".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] #[ignore] async fn should_fail_void_payment_for_auto_capture() {} // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let connector_payment_id = "12345678".to_string(); let capture_response = CONNECTOR .capture_payment( connector_payment_id, Some(types::PaymentsCaptureData { connector_meta: Some( serde_json::json!({"transaction_tag" : "10069306640".to_string()}), ), amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), None, ) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("Bad Request (69) - Invalid Transaction Tag") ); } // 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 captured_response = CONNECTOR.make_payment(None, None).await.unwrap(); assert_eq!(captured_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(captured_response.response.clone()); let connector_meta = utils::get_connector_metadata(captured_response.response); let response = CONNECTOR .refund_payment( txn_id.clone().unwrap(), Some(types::RefundsData { refund_amount: 1500, connector_transaction_id: txn_id.unwrap(), connector_metadata: connector_meta, ..utils::PaymentRefundType::default().0 }), PayeezyTest::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, String::from("Bad Request (64) - Invalid Refund"), ); }
{ "crate": "router", "file": "crates/router/tests/connectors/payeezy.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-40838741975547007
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/iatapay.rs // Contains: 1 structs, 0 enums use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails}; use masking::Secret; use router::types::{self, api, storage::enums, AccessToken}; use crate::{ connector_auth, utils::{ self, get_connector_transaction_id, Connector, ConnectorActions, PaymentAuthorizeType, }, }; #[derive(Clone, Copy)] struct IatapayTest; impl ConnectorActions for IatapayTest {} impl Connector for IatapayTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Iatapay; utils::construct_connector_data_old( Box::new(Iatapay::new()), types::Connector::Iatapay, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .iatapay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "iatapay".to_string() } } fn get_access_token() -> Option<AccessToken> { let connector = IatapayTest {}; match connector.get_auth_token() { types::ConnectorAuthType::SignatureKey { api_key, key1: _, api_secret: _, } => Some(AccessToken { token: api_key, expires: 60 * 5, }), _ => None, } } static CONNECTOR: IatapayTest = IatapayTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(types::PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::NL), ..Default::default() }), phone: Some(PhoneDetails { number: Some(Secret::new("9123456789".to_string())), country_code: Some("+91".to_string()), }), email: None, }), None, None, )), access_token: get_access_token(), ..Default::default() }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { router_return_url: Some("https://hyperswitch.io".to_string()), webhook_url: Some("https://hyperswitch.io".to_string()), currency: enums::Currency::EUR, ..PaymentAuthorizeType::default().0 }) } // Cards Positive Tests // Creates a payment checking if its status is "requires_customer_action" for redirectinal flow #[actix_web::test] async fn should_only_create_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending); } //refund on an unsuccessed payments #[actix_web::test] async fn should_fail_for_refund_on_unsuccessed_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let refund_response = CONNECTOR .refund_payment( get_connector_transaction_id(response.response).unwrap(), Some(types::RefundsData { refund_amount: response.request.amount, webhook_url: Some("https://hyperswitch.io".to_string()), ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap_err().code, "BAD_REQUEST".to_string(), ); } // 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 .refund_payment( "PWGKCZ91M4JJ0".to_string(), Some(types::RefundsData { refund_amount: 150, webhook_url: Some("https://hyperswitch.io".to_string()), ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "The amount to be refunded (100) is greater than the unrefunded amount (10.00): the amount of the payment is 10.00 and the refunded amount is 0.00", ); } #[actix_web::test] async fn should_sync_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "PE9OTYNP639XW".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } #[actix_web::test] async fn should_sync_refund() { let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, "R5DNXUW4EY6PQ".to_string(), None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); }
{ "crate": "router", "file": "crates/router/tests/connectors/iatapay.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_2957750886082958981
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/fiservemea.rs // Contains: 1 structs, 0 enums use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct FiservemeaTest; impl ConnectorActions for FiservemeaTest {} impl utils::Connector for FiservemeaTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Fiservemea; utils::construct_connector_data_old( Box::new(Fiservemea::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .fiservemea .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "fiservemea".to_string() } } static CONNECTOR: FiservemeaTest = FiservemeaTest {}; 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: PaymentMethodData::Card(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: PaymentMethodData::Card(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: PaymentMethodData::Card(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
{ "crate": "router", "file": "crates/router/tests/connectors/fiservemea.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_1908680678158137310
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/payload.rs // Contains: 1 structs, 0 enums 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 PayloadTest; impl ConnectorActions for PayloadTest {} impl utils::Connector for PayloadTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Payload; utils::construct_connector_data_old( Box::new(Payload::new()), types::Connector::DummyConnector1, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .payload .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "payload".to_string() } } static CONNECTOR: PayloadTest = PayloadTest {}; 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
{ "crate": "router", "file": "crates/router/tests/connectors/payload.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-9211788164263839964
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/mpgs.rs // Contains: 1 structs, 0 enums use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct MpgsTest; impl ConnectorActions for MpgsTest {} impl utils::Connector for MpgsTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Mpgs; utils::construct_connector_data_old( Box::new(Mpgs::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .mpgs .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "mpgs".to_string() } } static CONNECTOR: MpgsTest = MpgsTest {}; 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: PaymentMethodData::Card(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: PaymentMethodData::Card(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: PaymentMethodData::Card(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
{ "crate": "router", "file": "crates/router/tests/connectors/mpgs.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_2465212643734639780
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/trustpay.rs // Contains: 1 structs, 0 enums use std::str::FromStr; use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::Secret; use router::types::{self, api, domain, storage::enums, BrowserInformation}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct TrustpayTest; impl ConnectorActions for TrustpayTest {} impl utils::Connector for TrustpayTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Trustpay; utils::construct_connector_data_old( Box::new(Trustpay::new()), types::Connector::Trustpay, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .trustpay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "trustpay".to_string() } } fn get_default_browser_info() -> BrowserInformation { BrowserInformation { color_depth: Some(24), java_enabled: Some(false), java_script_enabled: Some(true), language: Some("en-US".to_string()), screen_height: Some(1080), screen_width: Some(1920), time_zone: Some(3600), accept_header: Some("*".to_string()), user_agent: Some("none".to_string()), ip_address: None, os_type: None, os_version: None, device_model: None, accept_language: Some("en".to_string()), referer: None, } } fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_year: Secret::new("25".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: Some(get_default_browser_info()), router_return_url: Some(String::from("http://localhost:8080")), ..utils::PaymentAuthorizeType::default().0 }) } fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(types::PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::IN), ..Default::default() }), phone: None, email: None, }), None, None, )), ..Default::default() }) } static CONNECTOR: TrustpayTest = TrustpayTest {}; // Cards Positive Tests // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment( get_default_payment_authorize_data(), 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( get_default_payment_authorize_data(), 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(), ), ..Default::default() }), None, ) .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( get_default_payment_authorize_data(), None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // 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( get_default_payment_authorize_data(), 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, None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect card number. #[actix_web::test] async fn should_fail_payment_for_incorrect_card_number() { let payment_authorize_data = types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("1234567891011").unwrap(), card_exp_year: Secret::new("25".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: Some(get_default_browser_info()), ..utils::PaymentAuthorizeType::default().0 }; let response = CONNECTOR .make_payment(Some(payment_authorize_data), get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Errors { code: 61, description: \"invalid payment data (country or brand)\" }".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let payment_authorize_data = Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_year: Secret::new("22".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: Some(get_default_browser_info()), ..utils::PaymentAuthorizeType::default().0 }); let response = CONNECTOR .make_payment(payment_authorize_data, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Errors { code: 15, description: \"the provided expiration year is not valid\" }" .to_string(), ); }
{ "crate": "router", "file": "crates/router/tests/connectors/trustpay.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_5168800779433973690
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/placetopay.rs // Contains: 1 structs, 0 enums use masking::Secret; use router::types::{self, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct PlacetopayTest; impl ConnectorActions for PlacetopayTest {} impl utils::Connector for PlacetopayTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Placetopay; utils::construct_connector_data_old( Box::new(Placetopay::new()), types::Connector::Placetopay, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .placetopay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "placetopay".to_string() } } static CONNECTOR: PlacetopayTest = PlacetopayTest {}; 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
{ "crate": "router", "file": "crates/router/tests/connectors/placetopay.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-5993535072900598883
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/utils.rs // Contains: 1 structs, 0 enums use std::{fmt::Debug, marker::PhantomData, str::FromStr, sync::Arc, time::Duration}; use async_trait::async_trait; use common_utils::{id_type::GenerateId, pii::Email}; use error_stack::Report; use hyperswitch_domain_models::router_data_v2::flow_common_types::PaymentFlowData; use masking::Secret; use router::{ configs::settings::Settings, core::{errors::ConnectorError, payments}, db::StorageImpl, routes, services::{ self, connector_integration_interface::{BoxedConnectorIntegrationInterface, ConnectorEnum}, }, types::{self, storage::enums, AccessToken, MinorUnit, PaymentAddress, RouterData}, }; use test_utils::connector_auth::ConnectorAuthType; use tokio::sync::oneshot; use wiremock::{Mock, MockServer}; pub trait Connector { fn get_data(&self) -> types::api::ConnectorData; fn get_auth_token(&self) -> types::ConnectorAuthType; fn get_name(&self) -> String; fn get_connector_meta(&self) -> Option<serde_json::Value> { None } /// interval in seconds to be followed when making the subsequent request whenever needed fn get_request_interval(&self) -> u64 { 5 } #[cfg(feature = "payouts")] fn get_payout_data(&self) -> Option<types::api::ConnectorData> { None } } pub fn construct_connector_data_old( connector: types::api::BoxedConnector, connector_name: types::Connector, get_token: types::api::GetToken, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, ) -> types::api::ConnectorData { types::api::ConnectorData { connector: ConnectorEnum::Old(connector), connector_name, get_token, merchant_connector_id, } } #[derive(Debug, Default, Clone)] pub struct PaymentInfo { pub address: Option<PaymentAddress>, pub auth_type: Option<enums::AuthenticationType>, pub access_token: Option<AccessToken>, pub connector_meta_data: Option<serde_json::Value>, pub connector_customer: Option<String>, pub payment_method_token: Option<String>, #[cfg(feature = "payouts")] pub payout_method_data: Option<types::api::PayoutMethodData>, #[cfg(feature = "payouts")] pub currency: Option<enums::Currency>, } impl PaymentInfo { pub fn with_default_billing_name() -> Self { Self { address: Some(PaymentAddress::new( None, None, Some(hyperswitch_domain_models::address::Address { address: Some(hyperswitch_domain_models::address::AddressDetails { first_name: Some(Secret::new("John".to_string())), last_name: Some(Secret::new("Doe".to_string())), ..Default::default() }), phone: None, email: None, }), None, )), ..Default::default() } } } #[async_trait] pub trait ConnectorActions: Connector { /// 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 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, ); Box::pin(call_connector(request, integration)).await } async fn create_connector_customer( &self, payment_data: Option<types::ConnectorCustomerData>, payment_info: Option<PaymentInfo>, ) -> Result<types::ConnectorCustomerRouterData, Report<ConnectorError>> { let integration: BoxedConnectorIntegrationInterface<_, PaymentFlowData, _, _> = self.get_data().connector.get_connector_integration(); let request = self.generate_data( types::ConnectorCustomerData { ..(payment_data.unwrap_or(CustomerType::default().0)) }, payment_info, ); Box::pin(call_connector(request, integration)).await } async fn create_connector_pm_token( &self, payment_data: Option<types::PaymentMethodTokenizationData>, payment_info: Option<PaymentInfo>, ) -> Result<types::TokenizationRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( types::PaymentMethodTokenizationData { ..(payment_data.unwrap_or(TokenType::default().0)) }, payment_info, ); Box::pin(call_connector(request, integration)).await } /// For initiating payments when `CaptureMethod` is set to `Automatic` /// This does complete the transaction without user intervention to Capture the payment async fn make_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 request = self.generate_data( types::PaymentsAuthorizeData { confirm: true, capture_method: Some(diesel_models::enums::CaptureMethod::Automatic), ..(payment_data.unwrap_or(PaymentAuthorizeType::default().0)) }, payment_info, ); Box::pin(call_connector(request, integration)).await } async fn sync_payment( &self, payment_data: Option<types::PaymentsSyncData>, payment_info: Option<PaymentInfo>, ) -> Result<types::PaymentsSyncRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( payment_data.unwrap_or_else(|| PaymentSyncType::default().0), payment_info, ); Box::pin(call_connector(request, integration)).await } /// will retry the psync till the given status matches or retry max 3 times async fn psync_retry_till_status_matches( &self, status: enums::AttemptStatus, payment_data: Option<types::PaymentsSyncData>, payment_info: Option<PaymentInfo>, ) -> Result<types::PaymentsSyncRouterData, Report<ConnectorError>> { let max_tries = 3; for curr_try in 0..max_tries { let sync_res = self .sync_payment(payment_data.clone(), payment_info.clone()) .await .unwrap(); if (sync_res.status == status) || (curr_try == max_tries - 1) { return Ok(sync_res); } tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; } Err(ConnectorError::ProcessingStepFailed(None).into()) } async fn capture_payment( &self, transaction_id: String, payment_data: Option<types::PaymentsCaptureData>, payment_info: Option<PaymentInfo>, ) -> Result<types::PaymentsCaptureRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( types::PaymentsCaptureData { connector_transaction_id: transaction_id, ..payment_data.unwrap_or(PaymentCaptureType::default().0) }, payment_info, ); Box::pin(call_connector(request, integration)).await } async fn authorize_and_capture_payment( &self, authorize_data: Option<types::PaymentsAuthorizeData>, capture_data: Option<types::PaymentsCaptureData>, payment_info: Option<PaymentInfo>, ) -> Result<types::PaymentsCaptureRouterData, Report<ConnectorError>> { let authorize_response = self .authorize_payment(authorize_data, payment_info.clone()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); let txn_id = get_connector_transaction_id(authorize_response.response); let response = self .capture_payment(txn_id.unwrap(), capture_data, payment_info) .await .unwrap(); return Ok(response); } async fn void_payment( &self, transaction_id: String, payment_data: Option<types::PaymentsCancelData>, payment_info: Option<PaymentInfo>, ) -> Result<types::PaymentsCancelRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( types::PaymentsCancelData { connector_transaction_id: transaction_id, ..payment_data.unwrap_or(PaymentCancelType::default().0) }, payment_info, ); Box::pin(call_connector(request, integration)).await } async fn authorize_and_void_payment( &self, authorize_data: Option<types::PaymentsAuthorizeData>, void_data: Option<types::PaymentsCancelData>, payment_info: Option<PaymentInfo>, ) -> Result<types::PaymentsCancelRouterData, Report<ConnectorError>> { let authorize_response = self .authorize_payment(authorize_data, payment_info.clone()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); let txn_id = get_connector_transaction_id(authorize_response.response); tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; // to avoid 404 error let response = self .void_payment(txn_id.unwrap(), void_data, payment_info) .await .unwrap(); return Ok(response); } async fn refund_payment( &self, transaction_id: String, refund_data: Option<types::RefundsData>, payment_info: Option<PaymentInfo>, ) -> Result<types::RefundExecuteRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( types::RefundsData { connector_transaction_id: transaction_id, ..refund_data.unwrap_or(PaymentRefundType::default().0) }, payment_info, ); Box::pin(call_connector(request, integration)).await } async fn capture_payment_and_refund( &self, authorize_data: Option<types::PaymentsAuthorizeData>, capture_data: Option<types::PaymentsCaptureData>, refund_data: Option<types::RefundsData>, payment_info: Option<PaymentInfo>, ) -> Result<types::RefundExecuteRouterData, Report<ConnectorError>> { //make a successful payment let response = self .authorize_and_capture_payment(authorize_data, capture_data, payment_info.clone()) .await .unwrap(); let txn_id = self.get_connector_transaction_id_from_capture_data(response); //try refund for previous payment tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; // to avoid 404 error Ok(self .refund_payment(txn_id.unwrap(), refund_data, payment_info) .await .unwrap()) } async fn make_payment_and_refund( &self, authorize_data: Option<types::PaymentsAuthorizeData>, refund_data: Option<types::RefundsData>, payment_info: Option<PaymentInfo>, ) -> Result<types::RefundExecuteRouterData, Report<ConnectorError>> { //make a successful payment let response = self .make_payment(authorize_data, payment_info.clone()) .await .unwrap(); //try refund for previous payment let transaction_id = get_connector_transaction_id(response.response).unwrap(); tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; // to avoid 404 error Ok(self .refund_payment(transaction_id, refund_data, payment_info) .await .unwrap()) } async fn auth_capture_and_refund( &self, authorize_data: Option<types::PaymentsAuthorizeData>, refund_data: Option<types::RefundsData>, payment_info: Option<PaymentInfo>, ) -> Result<types::RefundExecuteRouterData, Report<ConnectorError>> { //make a successful payment let response = self .authorize_and_capture_payment(authorize_data, None, payment_info.clone()) .await .unwrap(); //try refund for previous payment let transaction_id = get_connector_transaction_id(response.response).unwrap(); tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; // to avoid 404 error Ok(self .refund_payment(transaction_id, refund_data, payment_info) .await .unwrap()) } async fn make_payment_and_multiple_refund( &self, authorize_data: Option<types::PaymentsAuthorizeData>, refund_data: Option<types::RefundsData>, payment_info: Option<PaymentInfo>, ) { //make a successful payment let response = self .make_payment(authorize_data, payment_info.clone()) .await .unwrap(); //try refund for previous payment let transaction_id = get_connector_transaction_id(response.response).unwrap(); for _x in 0..2 { tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; // to avoid 404 error let refund_response = self .refund_payment( transaction_id.clone(), refund_data.clone(), payment_info.clone(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } } async fn sync_refund( &self, refund_id: String, payment_data: Option<types::RefundsData>, payment_info: Option<PaymentInfo>, ) -> Result<types::RefundSyncRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( payment_data.unwrap_or_else(|| types::RefundsData { payment_amount: 1000, minor_payment_amount: MinorUnit::new(1000), currency: enums::Currency::USD, refund_id: uuid::Uuid::new_v4().to_string(), connector_transaction_id: "".to_string(), webhook_url: None, refund_amount: 100, minor_refund_amount: MinorUnit::new(100), connector_metadata: None, refund_connector_metadata: None, reason: None, connector_refund_id: Some(refund_id), browser_info: None, split_refunds: None, integrity_object: None, refund_status: enums::RefundStatus::Pending, merchant_account_id: None, merchant_config_currency: None, capture_method: None, additional_payment_method_data: None, }), payment_info, ); Box::pin(call_connector(request, integration)).await } /// will retry the rsync till the given status matches or retry max 3 times async fn rsync_retry_till_status_matches( &self, status: enums::RefundStatus, refund_id: String, payment_data: Option<types::RefundsData>, payment_info: Option<PaymentInfo>, ) -> Result<types::RefundSyncRouterData, Report<ConnectorError>> { let max_tries = 3; for curr_try in 0..max_tries { let sync_res = self .sync_refund( refund_id.clone(), payment_data.clone(), payment_info.clone(), ) .await .unwrap(); if (sync_res.clone().response.unwrap().refund_status == status) || (curr_try == max_tries - 1) { return Ok(sync_res); } tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; } Err(ConnectorError::ProcessingStepFailed(None).into()) } #[cfg(feature = "payouts")] fn get_payout_request<Flow, Res>( &self, connector_payout_id: Option<String>, payout_type: enums::PayoutType, payment_info: Option<PaymentInfo>, ) -> RouterData<Flow, types::PayoutsData, Res> { self.generate_data( types::PayoutsData { payout_id: common_utils::id_type::PayoutId::generate(), amount: 1, minor_amount: MinorUnit::new(1), connector_payout_id, destination_currency: payment_info.to_owned().map_or(enums::Currency::EUR, |pi| { pi.currency.map_or(enums::Currency::EUR, |c| c) }), source_currency: payment_info.to_owned().map_or(enums::Currency::EUR, |pi| { pi.currency.map_or(enums::Currency::EUR, |c| c) }), entity_type: enums::PayoutEntityType::Individual, payout_type: Some(payout_type), customer_details: Some(payments::CustomerDetails { customer_id: Some(common_utils::generate_customer_id_of_default_length()), name: Some(Secret::new("John Doe".to_string())), email: Email::from_str("john.doe@example").ok(), phone: Some(Secret::new("620874518".to_string())), phone_country_code: Some("+31".to_string()), tax_registration_id: Some("1232343243".to_string().into()), }), vendor_details: None, priority: None, connector_transfer_method_id: None, webhook_url: None, browser_info: None, payout_connector_metadata: None, }, payment_info, ) } fn generate_data<Flow, Req: From<Req>, Res>( &self, req: Req, info: Option<PaymentInfo>, ) -> RouterData<Flow, Req, Res> { let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from(self.get_name())) .unwrap(); RouterData { flow: PhantomData, merchant_id, customer_id: Some(common_utils::generate_customer_id_of_default_length()), connector: self.get_name(), tenant_id: common_utils::id_type::TenantId::try_from_string("public".to_string()) .unwrap(), payment_id: uuid::Uuid::new_v4().to_string(), attempt_id: uuid::Uuid::new_v4().to_string(), status: enums::AttemptStatus::default(), auth_type: info .clone() .map_or(enums::AuthenticationType::NoThreeDs, |a| { a.auth_type .map_or(enums::AuthenticationType::NoThreeDs, |a| a) }), payment_method: enums::PaymentMethod::Card, payment_method_type: None, connector_auth_type: self.get_auth_token(), description: Some("This is a test".to_string()), payment_method_status: None, request: req, response: Err(types::ErrorResponse::default()), address: info .clone() .and_then(|a| a.address) .or_else(|| Some(PaymentAddress::default())) .unwrap(), connector_meta_data: info .clone() .and_then(|a| a.connector_meta_data.map(Secret::new)), connector_wallets_details: None, amount_captured: None, minor_amount_captured: None, access_token: info.clone().and_then(|a| a.access_token), session_token: None, reference_id: None, payment_method_token: info.clone().and_then(|a| { a.payment_method_token .map(|token| types::PaymentMethodToken::Token(Secret::new(token))) }), connector_customer: info.clone().and_then(|a| a.connector_customer), recurring_mandate_payment_data: None, preprocessing_id: None, connector_request_reference_id: uuid::Uuid::new_v4().to_string(), #[cfg(feature = "payouts")] payout_method_data: info.and_then(|p| p.payout_method_data), #[cfg(feature = "payouts")] quote_id: None, test_mode: None, payment_method_balance: None, connector_api_version: None, connector_http_status_code: None, apple_pay_flow: None, external_latency: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, psd2_sca_exemption_type: None, authentication_id: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, } } fn get_connector_transaction_id_from_capture_data( &self, response: types::PaymentsCaptureRouterData, ) -> Option<String> { match response.response { Ok(types::PaymentsResponseData::TransactionResponse { resource_id, .. }) => { resource_id.get_connector_transaction_id().ok() } Ok(types::PaymentsResponseData::SessionResponse { .. }) => None, Ok(types::PaymentsResponseData::SessionTokenResponse { .. }) => None, Ok(types::PaymentsResponseData::TokenizationResponse { .. }) => None, Ok(types::PaymentsResponseData::TransactionUnresolvedResponse { .. }) => None, Ok(types::PaymentsResponseData::ConnectorCustomerResponse(..)) => None, Ok(types::PaymentsResponseData::PreProcessingResponse { .. }) => None, Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. }) => None, Ok(types::PaymentsResponseData::MultipleCaptureResponse { .. }) => None, Ok(types::PaymentsResponseData::IncrementalAuthorizationResponse { .. }) => None, Ok(types::PaymentsResponseData::PostProcessingResponse { .. }) => None, Ok(types::PaymentsResponseData::PaymentResourceUpdateResponse { .. }) => None, Ok(types::PaymentsResponseData::PaymentsCreateOrderResponse { .. }) => None, Err(_) => None, } } #[cfg(feature = "payouts")] async fn verify_payout_eligibility( &self, payout_type: enums::PayoutType, payment_info: Option<PaymentInfo>, ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> { let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< types::api::PoEligibility, types::PayoutsData, types::PayoutsResponseData, > = self .get_payout_data() .ok_or(ConnectorError::FailedToObtainPreferredConnector)? .connector .get_connector_integration(); let request = self.get_payout_request(None, payout_type, payment_info); let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( Settings::new().unwrap(), StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); let res = services::api::execute_connector_processing_step( &state, connector_integration, &request, payments::CallConnectorAction::Trigger, None, None, ) .await?; Ok(res.response.unwrap()) } #[cfg(feature = "payouts")] async fn fulfill_payout( &self, connector_payout_id: Option<String>, payout_type: enums::PayoutType, payment_info: Option<PaymentInfo>, ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> { let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< types::api::PoFulfill, types::PayoutsData, types::PayoutsResponseData, > = self .get_payout_data() .ok_or(ConnectorError::FailedToObtainPreferredConnector)? .connector .get_connector_integration(); let request = self.get_payout_request(connector_payout_id, payout_type, payment_info); let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( Settings::new().unwrap(), StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); let res = services::api::execute_connector_processing_step( &state, connector_integration, &request, payments::CallConnectorAction::Trigger, None, None, ) .await?; Ok(res.response.unwrap()) } #[cfg(feature = "payouts")] async fn create_payout( &self, connector_customer: Option<String>, payout_type: enums::PayoutType, payment_info: Option<PaymentInfo>, ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> { let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< types::api::PoCreate, types::PayoutsData, types::PayoutsResponseData, > = self .get_payout_data() .ok_or(ConnectorError::FailedToObtainPreferredConnector)? .connector .get_connector_integration(); let mut request = self.get_payout_request(None, payout_type, payment_info); request.connector_customer = connector_customer; let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( Settings::new().unwrap(), StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); let res = services::api::execute_connector_processing_step( &state, connector_integration, &request, payments::CallConnectorAction::Trigger, None, None, ) .await?; Ok(res.response.unwrap()) } #[cfg(feature = "payouts")] async fn cancel_payout( &self, connector_payout_id: String, payout_type: enums::PayoutType, payment_info: Option<PaymentInfo>, ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> { let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< types::api::PoCancel, types::PayoutsData, types::PayoutsResponseData, > = self .get_payout_data() .ok_or(ConnectorError::FailedToObtainPreferredConnector)? .connector .get_connector_integration(); let request = self.get_payout_request(Some(connector_payout_id), payout_type, payment_info); let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( Settings::new().unwrap(), StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); let res = services::api::execute_connector_processing_step( &state, connector_integration, &request, payments::CallConnectorAction::Trigger, None, None, ) .await?; Ok(res.response.unwrap()) } #[cfg(feature = "payouts")] async fn create_and_fulfill_payout( &self, connector_customer: Option<String>, payout_type: enums::PayoutType, payment_info: Option<PaymentInfo>, ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> { let create_res = self .create_payout(connector_customer, payout_type, payment_info.to_owned()) .await?; assert_eq!( create_res.status.unwrap(), enums::PayoutStatus::RequiresFulfillment ); let fulfill_res = self .fulfill_payout( create_res.connector_payout_id, payout_type, payment_info.to_owned(), ) .await?; Ok(fulfill_res) } #[cfg(feature = "payouts")] async fn create_and_cancel_payout( &self, connector_customer: Option<String>, payout_type: enums::PayoutType, payment_info: Option<PaymentInfo>, ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> { let create_res = self .create_payout(connector_customer, payout_type, payment_info.to_owned()) .await?; assert_eq!( create_res.status.unwrap(), enums::PayoutStatus::RequiresFulfillment ); let cancel_res = self .cancel_payout( create_res .connector_payout_id .ok_or(ConnectorError::MissingRequiredField { field_name: "connector_payout_id", })?, payout_type, payment_info.to_owned(), ) .await?; Ok(cancel_res) } #[cfg(feature = "payouts")] async fn create_payout_recipient( &self, payout_type: enums::PayoutType, payment_info: Option<PaymentInfo>, ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> { let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< types::api::PoRecipient, types::PayoutsData, types::PayoutsResponseData, > = self .get_payout_data() .ok_or(ConnectorError::FailedToObtainPreferredConnector)? .connector .get_connector_integration(); let request = self.get_payout_request(None, payout_type, payment_info); let tx = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( Settings::new().unwrap(), StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); let res = services::api::execute_connector_processing_step( &state, connector_integration, &request, payments::CallConnectorAction::Trigger, None, None, ) .await?; Ok(res.response.unwrap()) } } async fn call_connector< T: Debug + Clone + 'static, ResourceCommonData: Debug + Clone + services::connector_integration_interface::RouterDataConversion<T, Req, Resp> + 'static, Req: Debug + Clone + 'static, Resp: Debug + Clone + 'static, >( request: RouterData<T, Req, Resp>, integration: BoxedConnectorIntegrationInterface<T, ResourceCommonData, Req, Resp>, ) -> Result<RouterData<T, Req, Resp>, Report<ConnectorError>> { let conf = Settings::new().unwrap(); let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); services::api::execute_connector_processing_step( &state, integration, &request, payments::CallConnectorAction::Trigger, None, None, ) .await } pub struct MockConfig { pub address: Option<String>, pub mocks: Vec<Mock>, } #[async_trait] pub trait LocalMock { async fn start_server(&self, config: MockConfig) -> MockServer { let address = config .address .unwrap_or_else(|| "127.0.0.1:9090".to_string()); let listener = std::net::TcpListener::bind(address).unwrap(); let expected_server_address = listener .local_addr() .expect("Failed to get server address."); let mock_server = MockServer::builder().listener(listener).start().await; assert_eq!(&expected_server_address, mock_server.address()); for mock in config.mocks { mock_server.register(mock).await; } mock_server } } pub struct PaymentAuthorizeType(pub types::PaymentsAuthorizeData); pub struct PaymentCaptureType(pub types::PaymentsCaptureData); pub struct PaymentCancelType(pub types::PaymentsCancelData); pub struct PaymentSyncType(pub types::PaymentsSyncData); pub struct PaymentRefundType(pub types::RefundsData); pub struct CCardType(pub types::domain::Card); pub struct BrowserInfoType(pub types::BrowserInformation); pub struct CustomerType(pub types::ConnectorCustomerData); pub struct TokenType(pub types::PaymentMethodTokenizationData); impl Default for CCardType { fn default() -> Self { Self(types::domain::Card { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), card_cvc: Secret::new("999".to_string()), card_issuer: None, card_network: None, card_type: None, card_issuing_country: None, 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, }) } } impl Default for PaymentAuthorizeType { fn default() -> Self { let data = types::PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(CCardType::default().0), amount: 100, minor_amount: MinorUnit::new(100), order_tax_amount: Some(MinorUnit::zero()), currency: enums::Currency::USD, confirm: true, statement_descriptor_suffix: None, statement_descriptor: None, capture_method: None, setup_future_usage: None, mandate_id: None, off_session: None, setup_mandate_details: None, browser_info: Some(BrowserInfoType::default().0), order_details: None, order_category: None, email: None, customer_name: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None, payment_experience: None, payment_method_type: None, router_return_url: None, complete_authorize_url: None, webhook_url: None, customer_id: None, surcharge_details: None, request_incremental_authorization: false, request_extended_authorization: None, metadata: None, authentication_data: None, customer_acceptance: None, split_payments: None, integrity_object: None, merchant_order_reference_id: None, additional_payment_method_data: None, shipping_cost: None, merchant_account_id: None, merchant_config_currency: None, connector_testing_data: None, order_id: None, locale: None, payment_channel: None, enable_partial_authorization: None, enable_overcapture: None, is_stored_credential: None, mit_category: None, }; Self(data) } } impl Default for PaymentCaptureType { fn default() -> Self { Self(types::PaymentsCaptureData { amount_to_capture: 100, currency: enums::Currency::USD, connector_transaction_id: "".to_string(), payment_amount: 100, ..Default::default() }) } } impl Default for PaymentCancelType { fn default() -> Self { Self(types::PaymentsCancelData { cancellation_reason: Some("requested_by_customer".to_string()), connector_transaction_id: "".to_string(), ..Default::default() }) } } impl Default for BrowserInfoType { fn default() -> Self { let data = types::BrowserInformation { user_agent: Some("".to_string()), accept_header: Some("".to_string()), language: Some("nl-NL".to_string()), color_depth: Some(24), screen_height: Some(723), screen_width: Some(1536), time_zone: Some(0), java_enabled: Some(true), java_script_enabled: Some(true), ip_address: Some("127.0.0.1".parse().unwrap()), device_model: Some("Apple IPHONE 7".to_string()), os_type: Some("IOS or ANDROID".to_string()), os_version: Some("IOS 14.5".to_string()), accept_language: Some("en".to_string()), referer: None, }; Self(data) } } impl Default for PaymentSyncType { fn default() -> Self { let data = types::PaymentsSyncData { mandate_id: None, connector_transaction_id: types::ResponseId::ConnectorTransactionId( "12345".to_string(), ), encoded_data: None, capture_method: None, sync_type: types::SyncRequestType::SinglePaymentSync, connector_meta: None, payment_method_type: None, currency: enums::Currency::USD, payment_experience: None, amount: MinorUnit::new(100), integrity_object: None, ..Default::default() }; Self(data) } } impl Default for PaymentRefundType { fn default() -> Self { let data = types::RefundsData { payment_amount: 100, minor_payment_amount: MinorUnit::new(100), currency: enums::Currency::USD, refund_id: uuid::Uuid::new_v4().to_string(), connector_transaction_id: String::new(), refund_amount: 100, minor_refund_amount: MinorUnit::new(100), webhook_url: None, connector_metadata: None, refund_connector_metadata: None, reason: Some("Customer returned product".to_string()), connector_refund_id: None, browser_info: None, split_refunds: None, integrity_object: None, refund_status: enums::RefundStatus::Pending, merchant_account_id: None, merchant_config_currency: None, capture_method: None, additional_payment_method_data: None, }; Self(data) } } impl Default for CustomerType { fn default() -> Self { let data = types::ConnectorCustomerData { payment_method_data: Some(types::domain::PaymentMethodData::Card( CCardType::default().0, )), description: None, email: Email::from_str("test@juspay.in").ok(), phone: None, name: None, preprocessing_id: None, split_payments: None, customer_acceptance: None, setup_future_usage: None, customer_id: None, billing_address: None, }; Self(data) } } impl Default for TokenType { fn default() -> Self { let data = types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(CCardType::default().0), browser_info: None, amount: Some(100), currency: enums::Currency::USD, split_payments: None, mandate_id: None, setup_future_usage: None, customer_acceptance: None, setup_mandate_details: None, }; Self(data) } } pub fn get_connector_transaction_id( response: Result<types::PaymentsResponseData, types::ErrorResponse>, ) -> Option<String> { match response { Ok(types::PaymentsResponseData::TransactionResponse { resource_id, .. }) => { resource_id.get_connector_transaction_id().ok() } Ok(types::PaymentsResponseData::SessionResponse { .. }) => None, Ok(types::PaymentsResponseData::SessionTokenResponse { .. }) => None, Ok(types::PaymentsResponseData::TokenizationResponse { .. }) => None, Ok(types::PaymentsResponseData::TransactionUnresolvedResponse { .. }) => None, Ok(types::PaymentsResponseData::PreProcessingResponse { .. }) => None, Ok(types::PaymentsResponseData::ConnectorCustomerResponse(..)) => None, Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. }) => None, Ok(types::PaymentsResponseData::MultipleCaptureResponse { .. }) => None, Ok(types::PaymentsResponseData::IncrementalAuthorizationResponse { .. }) => None, Ok(types::PaymentsResponseData::PostProcessingResponse { .. }) => None, Ok(types::PaymentsResponseData::PaymentResourceUpdateResponse { .. }) => None, Ok(types::PaymentsResponseData::PaymentsCreateOrderResponse { .. }) => None, Err(_) => None, } } pub fn get_connector_metadata( response: Result<types::PaymentsResponseData, types::ErrorResponse>, ) -> Option<serde_json::Value> { match response { Ok(types::PaymentsResponseData::TransactionResponse { resource_id: _, redirection_data: _, mandate_reference: _, connector_metadata, network_txn_id: _, connector_response_reference_id: _, incremental_authorization_allowed: _, charges: _, }) => connector_metadata, _ => None, } } pub fn to_connector_auth_type(auth_type: ConnectorAuthType) -> types::ConnectorAuthType { match auth_type { ConnectorAuthType::HeaderKey { api_key } => types::ConnectorAuthType::HeaderKey { api_key }, ConnectorAuthType::BodyKey { api_key, key1 } => { types::ConnectorAuthType::BodyKey { api_key, key1 } } ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => types::ConnectorAuthType::SignatureKey { api_key, key1, api_secret, }, ConnectorAuthType::MultiAuthKey { api_key, key1, api_secret, key2, } => types::ConnectorAuthType::MultiAuthKey { api_key, key1, api_secret, key2, }, _ => types::ConnectorAuthType::NoKey, } }
{ "crate": "router", "file": "crates/router/tests/connectors/utils.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-7360648879559392619
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/checkbook.rs // Contains: 1 structs, 0 enums use std::str::FromStr; use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::Secret; use router::types::{self, api, storage::enums, Email}; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct CheckbookTest; impl ConnectorActions for CheckbookTest {} impl utils::Connector for CheckbookTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Checkbook; utils::construct_connector_data_old( Box::new(Checkbook::new()), types::Connector::Checkbook, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { types::ConnectorAuthType::BodyKey { key1: Secret::new("dummy_publishable_key".to_string()), api_key: Secret::new("dummy_secret_key".to_string()), } } fn get_name(&self) -> String { "checkbook".to_string() } } static CONNECTOR: CheckbookTest = CheckbookTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(types::PaymentAddress::new( None, None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("John".to_string())), last_name: Some(Secret::new("Doe".to_string())), ..Default::default() }), phone: None, email: Some(Email::from_str("abc@gmail.com").unwrap()), }), None, )), ..Default::default() }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Creates a payment. #[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::AuthenticationPending); } // Synchronizes a payment. #[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::AuthenticationPending, 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::AuthenticationPending); } // Voids a payment. #[actix_web::test] async fn should_void_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 .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); }
{ "crate": "router", "file": "crates/router/tests/connectors/checkbook.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_5139650620740915983
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/santander.rs // Contains: 1 structs, 0 enums 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 SantanderTest; impl ConnectorActions for SantanderTest {} impl utils::Connector for SantanderTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Santander; utils::construct_connector_data_old( Box::new(Santander::new()), types::Connector::DummyConnector1, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .santander .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "santander".to_string() } } static CONNECTOR: SantanderTest = SantanderTest {}; 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
{ "crate": "router", "file": "crates/router/tests/connectors/santander.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-1761472020977779735
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/tokenio.rs // Contains: 1 structs, 0 enums use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct TokenioTest; impl ConnectorActions for TokenioTest {} impl utils::Connector for TokenioTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Tokenio; utils::construct_connector_data_old( Box::new(Tokenio::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .tokenio .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "tokenio".to_string() } } static CONNECTOR: TokenioTest = TokenioTest {}; 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: PaymentMethodData::Card(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: PaymentMethodData::Card(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: PaymentMethodData::Card(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
{ "crate": "router", "file": "crates/router/tests/connectors/tokenio.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_1990515546418583169
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/vgs.rs // Contains: 1 structs, 0 enums use masking::Secret; use router::types::{self, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct VgsTest; impl ConnectorActions for VgsTest {} impl utils::Connector for VgsTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Vgs; utils::construct_connector_data_old( Box::new(&Vgs), types::Connector::Vgs, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .vgs .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "vgs".to_string() } } static CONNECTOR: VgsTest = VgsTest {}; 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
{ "crate": "router", "file": "crates/router/tests/connectors/vgs.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-367866553213283377
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/bamboraapac.rs // Contains: 1 structs, 0 enums 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 BamboraapacTest; impl ConnectorActions for BamboraapacTest {} impl utils::Connector for BamboraapacTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Adyen; utils::construct_connector_data_old( Box::new(Adyen::new()), types::Connector::Adyen, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .bamboraapac .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "bamboraapac".to_string() } } static CONNECTOR: BamboraapacTest = BamboraapacTest {}; 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
{ "crate": "router", "file": "crates/router/tests/connectors/bamboraapac.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_1636769682133226467
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/gpayments.rs // Contains: 1 structs, 0 enums use router::types; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] #[allow(dead_code)] struct GpaymentsTest; impl ConnectorActions for GpaymentsTest {} impl utils::Connector for GpaymentsTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Gpayments; utils::construct_connector_data_old( Box::new(Gpayments::new()), types::Connector::Threedsecureio, // Added as Dummy connector as template code is added for future usage types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .gpayments .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "gpayments".to_string() } }
{ "crate": "router", "file": "crates/router/tests/connectors/gpayments.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_8881848396102626206
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/moneris.rs // Contains: 1 structs, 0 enums use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct MonerisTest; impl ConnectorActions for MonerisTest {} impl utils::Connector for MonerisTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Moneris; utils::construct_connector_data_old( Box::new(Moneris::new()), types::Connector::Moneris, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .moneris .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "moneris".to_string() } } static CONNECTOR: MonerisTest = MonerisTest {}; 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: PaymentMethodData::Card(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: PaymentMethodData::Card(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: PaymentMethodData::Card(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
{ "crate": "router", "file": "crates/router/tests/connectors/moneris.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-1421720614197724281
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/tests/connectors/nexixpay.rs // Contains: 1 structs, 0 enums use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct NexixpayTest; impl ConnectorActions for NexixpayTest {} impl utils::Connector for NexixpayTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Nexixpay; utils::construct_connector_data_old( Box::new(Nexixpay::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .nexixpay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "nexixpay".to_string() } } static CONNECTOR: NexixpayTest = NexixpayTest {}; 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: PaymentMethodData::Card(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: PaymentMethodData::Card(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: PaymentMethodData::Card(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
{ "crate": "router", "file": "crates/router/tests/connectors/nexixpay.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_6309432663834079066
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types.rs // Contains: 7 structs, 5 enums // FIXME: Why were these data types grouped this way? // // Folder `types` is strange for Rust ecosystem, nevertheless it might be okay. // But folder `enum` is even more strange I unlikely okay. Why should not we introduce folders `type`, `structs` and `traits`? :) // Is it better to split data types according to business logic instead. // For example, customers/address/dispute/mandate is "models". // Separation of concerns instead of separation of forms. pub mod api; pub mod authentication; pub mod connector_transformers; pub mod domain; #[cfg(feature = "frm")] pub mod fraud_check; pub mod payment_methods; pub mod pm_auth; use masking::Secret; pub mod storage; pub mod transformers; use std::marker::PhantomData; pub use api_models::{enums::Connector, mandates}; #[cfg(feature = "payouts")] pub use api_models::{enums::PayoutConnectors, payouts as payout_types}; #[cfg(feature = "v2")] use common_utils::errors::CustomResult; pub use common_utils::{pii, pii::Email, request::RequestContent, types::MinorUnit}; #[cfg(feature = "v2")] use error_stack::ResultExt; #[cfg(feature = "frm")] pub use hyperswitch_domain_models::router_data_v2::FrmFlowData; use hyperswitch_domain_models::router_flow_types::{ self, access_token_auth::AccessTokenAuth, dispute::{Accept, Defend, Dsync, Evidence, Fetch}, files::{Retrieve, Upload}, mandate_revoke::MandateRevoke, payments::{ Approve, Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, ExtendAuthorization, ExternalVaultProxy, IncrementalAuthorization, InitPayment, PSync, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, refunds::{Execute, RSync}, webhooks::VerifyWebhookSource, }; pub use hyperswitch_domain_models::{ payment_address::PaymentAddress, router_data::{ AccessToken, AccessTokenAuthenticationResponse, AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, ErrorResponse, GooglePayPaymentMethodDetails, GooglePayPredecryptDataInternal, L2L3Data, PaymentMethodBalance, PaymentMethodToken, RecurringMandatePaymentData, RouterData, }, router_data_v2::{ AccessTokenFlowData, AuthenticationTokenFlowData, DisputesFlowData, ExternalAuthenticationFlowData, FilesFlowData, MandateRevokeFlowData, PaymentFlowData, RefundFlowData, RouterDataV2, UasFlowData, WebhookSourceVerifyData, }, router_request_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, InvoiceRecordBackRequest, }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, BrowserInformation, ChargeRefunds, ChargeRefundsOptions, CompleteAuthorizeData, CompleteAuthorizeRedirectResponse, ConnectorCustomerData, CreateOrderRequestData, DefendDisputeRequestData, DestinationChargeRefund, DirectChargeRefund, DisputeSyncData, ExternalVaultProxyPaymentsData, FetchDisputesRequestData, MandateRevokeRequestData, MultipleCaptureRequestData, PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, ResponseId, RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, SplitRefundsRequest, SubmitEvidenceRequestData, SyncRequestType, UploadFileRequestData, VaultRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, InvoiceRecordBackResponse, }, AcceptDisputeResponse, CaptureSyncResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, MandateReference, MandateRevokeResponseData, PaymentsResponseData, PreprocessingResponseId, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, TaxCalculationResponseData, UploadFileResponse, VaultResponseData, VerifyWebhookSourceResponseData, VerifyWebhookStatus, }, }; #[cfg(feature = "payouts")] pub use hyperswitch_domain_models::{ router_data_v2::PayoutFlowData, router_request_types::PayoutsData, router_response_types::PayoutsResponseData, }; #[cfg(feature = "payouts")] pub use hyperswitch_interfaces::types::{ PayoutCancelType, PayoutCreateType, PayoutEligibilityType, PayoutFulfillType, PayoutQuoteType, PayoutRecipientAccountType, PayoutRecipientType, PayoutSyncType, }; pub use hyperswitch_interfaces::{ disputes::DisputePayload, types::{ AcceptDisputeType, ConnectorCustomerType, DefendDisputeType, FetchDisputesType, IncrementalAuthorizationType, MandateRevokeType, PaymentsAuthorizeType, PaymentsBalanceType, PaymentsCaptureType, PaymentsCompleteAuthorizeType, PaymentsInitType, PaymentsPostCaptureVoidType, PaymentsPostProcessingType, PaymentsPostSessionTokensType, PaymentsPreAuthorizeType, PaymentsPreProcessingType, PaymentsSessionType, PaymentsSyncType, PaymentsUpdateMetadataType, PaymentsVoidType, RefreshTokenType, RefundExecuteType, RefundSyncType, Response, RetrieveFileType, SdkSessionUpdateType, SetupMandateType, SubmitEvidenceType, TokenizationType, UploadFileType, VerifyWebhookSourceType, }, }; #[cfg(feature = "v2")] use crate::core::errors; pub use crate::core::payments::CustomerDetails; use crate::{ consts, core::payments::{OperationSessionGetters, PaymentData}, services, types::transformers::{ForeignFrom, ForeignTryFrom}, }; pub type PaymentsAuthorizeRouterData = RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>; pub type ExternalVaultProxyPaymentsRouterData = RouterData<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData>; pub type PaymentsPreProcessingRouterData = RouterData<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>; pub type PaymentsPostProcessingRouterData = RouterData<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>; pub type PaymentsAuthorizeSessionTokenRouterData = RouterData<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>; pub type PaymentsCompleteAuthorizeRouterData = RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>; pub type PaymentsInitRouterData = RouterData<InitPayment, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsBalanceRouterData = RouterData<Balance, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsSyncRouterData = RouterData<PSync, PaymentsSyncData, PaymentsResponseData>; pub type PaymentsCaptureRouterData = RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>; pub type PaymentsIncrementalAuthorizationRouterData = RouterData< IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData, >; pub type PaymentsExtendAuthorizationRouterData = RouterData<ExtendAuthorization, PaymentsExtendAuthorizationData, PaymentsResponseData>; pub type PaymentsTaxCalculationRouterData = RouterData<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>; pub type CreateOrderRouterData = RouterData<CreateOrder, CreateOrderRequestData, PaymentsResponseData>; pub type SdkSessionUpdateRouterData = RouterData<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>; pub type PaymentsPostSessionTokensRouterData = RouterData<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>; pub type PaymentsUpdateMetadataRouterData = RouterData<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData>; pub type PaymentsCancelRouterData = RouterData<Void, PaymentsCancelData, PaymentsResponseData>; pub type PaymentsCancelPostCaptureRouterData = RouterData<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData>; pub type PaymentsRejectRouterData = RouterData<Reject, PaymentsRejectData, PaymentsResponseData>; pub type PaymentsApproveRouterData = RouterData<Approve, PaymentsApproveData, PaymentsResponseData>; pub type PaymentsSessionRouterData = RouterData<Session, PaymentsSessionData, PaymentsResponseData>; pub type RefundsRouterData<F> = RouterData<F, RefundsData, RefundsResponseData>; pub type RefundExecuteRouterData = RouterData<Execute, RefundsData, RefundsResponseData>; pub type RefundSyncRouterData = RouterData<RSync, RefundsData, RefundsResponseData>; pub type TokenizationRouterData = RouterData< router_flow_types::PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData, >; pub type ConnectorCustomerRouterData = RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>; pub type RefreshTokenRouterData = RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>; pub type PaymentsResponseRouterData<R> = ResponseRouterData<Authorize, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsCancelResponseRouterData<R> = ResponseRouterData<Void, R, PaymentsCancelData, PaymentsResponseData>; pub type PaymentsCancelPostCaptureResponseRouterData<R> = ResponseRouterData<PostCaptureVoid, R, PaymentsCancelPostCaptureData, PaymentsResponseData>; pub type PaymentsExtendAuthorizationResponseRouterData<R> = ResponseRouterData< ExtendAuthorization, R, PaymentsExtendAuthorizationData, PaymentsResponseData, >; pub type PaymentsBalanceResponseRouterData<R> = ResponseRouterData<Balance, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsSyncResponseRouterData<R> = ResponseRouterData<PSync, R, PaymentsSyncData, PaymentsResponseData>; pub type PaymentsSessionResponseRouterData<R> = ResponseRouterData<Session, R, PaymentsSessionData, PaymentsResponseData>; pub type PaymentsInitResponseRouterData<R> = ResponseRouterData<InitPayment, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type SdkSessionUpdateResponseRouterData<R> = ResponseRouterData<SdkSessionUpdate, R, SdkPaymentsSessionUpdateData, PaymentsResponseData>; pub type PaymentsCaptureResponseRouterData<R> = ResponseRouterData<Capture, R, PaymentsCaptureData, PaymentsResponseData>; pub type PaymentsPreprocessingResponseRouterData<R> = ResponseRouterData<PreProcessing, R, PaymentsPreProcessingData, PaymentsResponseData>; pub type TokenizationResponseRouterData<R> = ResponseRouterData<PaymentMethodToken, R, PaymentMethodTokenizationData, PaymentsResponseData>; pub type ConnectorCustomerResponseRouterData<R> = ResponseRouterData<CreateConnectorCustomer, R, ConnectorCustomerData, PaymentsResponseData>; pub type RefundsResponseRouterData<F, R> = ResponseRouterData<F, R, RefundsData, RefundsResponseData>; pub type SetupMandateRouterData = RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>; pub type AcceptDisputeRouterData = RouterData<Accept, AcceptDisputeRequestData, AcceptDisputeResponse>; pub type VerifyWebhookSourceRouterData = RouterData< VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, >; pub type SubmitEvidenceRouterData = RouterData<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>; pub type UploadFileRouterData = RouterData<Upload, UploadFileRequestData, UploadFileResponse>; pub type RetrieveFileRouterData = RouterData<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>; pub type DefendDisputeRouterData = RouterData<Defend, DefendDisputeRequestData, DefendDisputeResponse>; pub type FetchDisputesRouterData = RouterData<Fetch, FetchDisputesRequestData, FetchDisputesResponse>; pub type DisputeSyncRouterData = RouterData<Dsync, DisputeSyncData, DisputeSyncResponse>; pub type MandateRevokeRouterData = RouterData<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>; #[cfg(feature = "payouts")] pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>; #[cfg(feature = "payouts")] pub type PayoutsResponseRouterData<F, R> = ResponseRouterData<F, R, PayoutsData, PayoutsResponseData>; #[cfg(feature = "payouts")] pub type PayoutActionData = Vec<( storage::Payouts, storage::PayoutAttempt, Option<domain::Customer>, Option<api_models::payments::Address>, )>; #[cfg(feature = "payouts")] pub trait PayoutIndividualDetailsExt { type Error; fn get_external_account_account_holder_type(&self) -> Result<String, Self::Error>; } pub trait Capturable { fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, _payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { None } fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, _get_amount_capturable: Option<i64>, _attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { None } } #[cfg(feature = "v1")] impl Capturable for PaymentsAuthorizeData { fn get_captured_amount<F>( &self, amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { amount_captured.or(Some( payment_data .payment_attempt .get_total_amount() .get_amount_as_i64(), )) } fn get_amount_capturable<F>( &self, payment_data: &PaymentData<F>, amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let amount_capturable_from_intent_status = match payment_data.get_capture_method().unwrap_or_default() { common_enums::CaptureMethod::Automatic | common_enums::CaptureMethod::SequentialAutomatic => { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::Processing => None, } }, common_enums::CaptureMethod::Manual => Some(payment_data.payment_attempt.get_total_amount().get_amount_as_i64()), // In case of manual multiple, amount capturable must be inferred from all captures. common_enums::CaptureMethod::ManualMultiple | // Scheduled capture is not supported as of now common_enums::CaptureMethod::Scheduled => None, }; amount_capturable .or(amount_capturable_from_intent_status) .or(Some( payment_data .payment_attempt .get_total_amount() .get_amount_as_i64(), )) } } #[cfg(feature = "v1")] impl Capturable for PaymentsCaptureData { fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, _payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { Some(self.amount_to_capture) } fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, _amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Processing | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Failed | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => None, } } } #[cfg(feature = "v1")] impl Capturable for CompleteAuthorizeData { fn get_captured_amount<F>( &self, amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { amount_captured.or(Some( payment_data .payment_attempt .get_total_amount() .get_amount_as_i64(), )) } fn get_amount_capturable<F>( &self, payment_data: &PaymentData<F>, amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let amount_capturable_from_intent_status = match payment_data .get_capture_method() .unwrap_or_default() { common_enums::CaptureMethod::Automatic | common_enums::CaptureMethod::SequentialAutomatic => { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::Processing => None, } }, common_enums::CaptureMethod::Manual => Some(payment_data.payment_attempt.get_total_amount().get_amount_as_i64()), // In case of manual multiple, amount capturable must be inferred from all captures. common_enums::CaptureMethod::ManualMultiple | // Scheduled capture is not supported as of now common_enums::CaptureMethod::Scheduled => None, }; amount_capturable .or(amount_capturable_from_intent_status) .or(Some( payment_data .payment_attempt .get_total_amount() .get_amount_as_i64(), )) } } impl Capturable for SetupMandateRequestData {} impl Capturable for PaymentsTaxCalculationData {} impl Capturable for SdkPaymentsSessionUpdateData {} impl Capturable for PaymentsPostSessionTokensData {} impl Capturable for PaymentsUpdateMetadataData {} impl Capturable for PaymentsCancelData { fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { // return previously captured amount payment_data .payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()) } fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, _amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Processing | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, } } } impl Capturable for PaymentsCancelPostCaptureData { fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { // return previously captured amount payment_data .payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()) } fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, _amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::Processing | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => None, } } } impl Capturable for PaymentsApproveData {} impl Capturable for PaymentsRejectData {} impl Capturable for PaymentsSessionData {} impl Capturable for PaymentsIncrementalAuthorizationData { fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, amount_capturable: Option<i64>, _attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { amount_capturable.or(Some(self.total_amount)) } } impl Capturable for PaymentsSyncData { #[cfg(feature = "v1")] fn get_captured_amount<F>( &self, amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { payment_data .payment_attempt .amount_to_capture .or(payment_data.payment_intent.amount_captured) .or(amount_captured.map(MinorUnit::new)) .or_else(|| Some(payment_data.payment_attempt.get_total_amount())) .map(|amt| amt.get_amount_as_i64()) } #[cfg(feature = "v2")] fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { // TODO: add a getter for this payment_data .payment_attempt .amount_details .get_amount_to_capture() .or_else(|| Some(payment_data.payment_attempt.get_total_amount())) .map(|amt| amt.get_amount_as_i64()) } #[cfg(feature = "v1")] fn get_amount_capturable<F>( &self, payment_data: &PaymentData<F>, amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { if attempt_status.is_terminal_status() { Some(0) } else { amount_capturable.or(Some(MinorUnit::get_amount_as_i64( payment_data.payment_attempt.amount_capturable, ))) } } #[cfg(feature = "v2")] fn get_amount_capturable<F>( &self, payment_data: &PaymentData<F>, amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { if attempt_status.is_terminal_status() { Some(0) } else { None } } } impl Capturable for PaymentsExtendAuthorizationData { fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { // return previously captured amount payment_data .payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()) } fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, _amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Expired | common_enums::IntentStatus::Succeeded => Some(0), common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::Processing | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => None, } } } pub struct AddAccessTokenResult { pub access_token_result: Result<Option<AccessToken>, ErrorResponse>, pub connector_supports_access_token: bool, } pub struct PaymentMethodTokenResult { pub payment_method_token_result: Result<Option<String>, ErrorResponse>, pub is_payment_method_tokenization_performed: bool, pub connector_response: Option<ConnectorResponseData>, } #[derive(Clone)] pub struct CreateOrderResult { pub create_order_result: Result<String, ErrorResponse>, } pub struct PspTokenResult { pub token: Result<String, ErrorResponse>, } #[derive(Debug, Clone, Copy)] pub enum Redirection { Redirect, NoRedirect, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PollConfig { pub delay_in_secs: i8, pub frequency: i8, } impl PollConfig { pub fn get_poll_config_key(connector: String) -> String { format!("poll_config_external_three_ds_{connector}") } } impl Default for PollConfig { fn default() -> Self { Self { delay_in_secs: consts::DEFAULT_POLL_DELAY_IN_SECS, frequency: consts::DEFAULT_POLL_FREQUENCY, } } } #[cfg(feature = "v1")] #[derive(Clone, Debug)] pub struct RedirectPaymentFlowResponse { pub payments_response: api_models::payments::PaymentsResponse, pub business_profile: domain::Profile, } #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub struct RedirectPaymentFlowResponse<D> { pub payment_data: D, pub profile: domain::Profile, } #[cfg(feature = "v1")] #[derive(Clone, Debug)] pub struct AuthenticatePaymentFlowResponse { pub payments_response: api_models::payments::PaymentsResponse, pub poll_config: PollConfig, pub business_profile: domain::Profile, } #[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize)] pub struct ConnectorResponse { pub merchant_id: common_utils::id_type::MerchantId, pub connector: String, pub payment_id: common_utils::id_type::PaymentId, pub amount: i64, pub connector_transaction_id: String, pub return_url: Option<String>, pub three_ds_form: Option<services::RedirectForm>, } pub struct ResponseRouterData<Flow, R, Request, Response> { pub response: R, pub data: RouterData<Flow, Request, Response>, pub http_code: u16, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub enum RecipientIdType { ConnectorId(Secret<String>), LockerId(Secret<String>), } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum MerchantAccountData { Iban { iban: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, Bacs { account_number: Secret<String>, sort_code: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, FasterPayments { account_number: Secret<String>, sort_code: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, Sepa { iban: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, SepaInstant { iban: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, Elixir { account_number: Secret<String>, iban: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, Bankgiro { number: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, Plusgiro { number: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, } impl ForeignFrom<MerchantAccountData> for api_models::admin::MerchantAccountData { fn foreign_from(from: MerchantAccountData) -> Self { match from { MerchantAccountData::Iban { iban, name, connector_recipient_id, } => Self::Iban { iban, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::Bacs { account_number, sort_code, name, connector_recipient_id, } => Self::Bacs { account_number, sort_code, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::FasterPayments { account_number, sort_code, name, connector_recipient_id, } => Self::FasterPayments { account_number, sort_code, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::Sepa { iban, name, connector_recipient_id, } => Self::Sepa { iban, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::SepaInstant { iban, name, connector_recipient_id, } => Self::SepaInstant { iban, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::Elixir { account_number, iban, name, connector_recipient_id, } => Self::Elixir { account_number, iban, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::Bankgiro { number, name, connector_recipient_id, } => Self::Bankgiro { number, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::Plusgiro { number, name, connector_recipient_id, } => Self::Plusgiro { number, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, } } } impl From<api_models::admin::MerchantAccountData> for MerchantAccountData { fn from(from: api_models::admin::MerchantAccountData) -> Self { match from { api_models::admin::MerchantAccountData::Iban { iban, name, connector_recipient_id, } => Self::Iban { iban, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::Bacs { account_number, sort_code, name, connector_recipient_id, } => Self::Bacs { account_number, sort_code, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::FasterPayments { account_number, sort_code, name, connector_recipient_id, } => Self::FasterPayments { account_number, sort_code, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::Sepa { iban, name, connector_recipient_id, } => Self::Sepa { iban, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::SepaInstant { iban, name, connector_recipient_id, } => Self::SepaInstant { iban, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::Elixir { account_number, iban, name, connector_recipient_id, } => Self::Elixir { account_number, iban, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::Bankgiro { number, name, connector_recipient_id, } => Self::Bankgiro { number, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::Plusgiro { number, name, connector_recipient_id, } => Self::Plusgiro { number, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, } } } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum MerchantRecipientData { ConnectorRecipientId(Secret<String>), WalletId(Secret<String>), AccountData(MerchantAccountData), } impl ForeignFrom<MerchantRecipientData> for api_models::admin::MerchantRecipientData { fn foreign_from(value: MerchantRecipientData) -> Self { match value { MerchantRecipientData::ConnectorRecipientId(id) => Self::ConnectorRecipientId(id), MerchantRecipientData::WalletId(id) => Self::WalletId(id), MerchantRecipientData::AccountData(data) => { Self::AccountData(api_models::admin::MerchantAccountData::foreign_from(data)) } } } } impl From<api_models::admin::MerchantRecipientData> for MerchantRecipientData { fn from(value: api_models::admin::MerchantRecipientData) -> Self { match value { api_models::admin::MerchantRecipientData::ConnectorRecipientId(id) => { Self::ConnectorRecipientId(id) } api_models::admin::MerchantRecipientData::WalletId(id) => Self::WalletId(id), api_models::admin::MerchantRecipientData::AccountData(data) => { Self::AccountData(data.into()) } } } } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AdditionalMerchantData { OpenBankingRecipientData(MerchantRecipientData), } impl ForeignFrom<api_models::admin::AdditionalMerchantData> for AdditionalMerchantData { fn foreign_from(value: api_models::admin::AdditionalMerchantData) -> Self { match value { api_models::admin::AdditionalMerchantData::OpenBankingRecipientData(data) => { Self::OpenBankingRecipientData(MerchantRecipientData::from(data)) } } } } impl ForeignFrom<AdditionalMerchantData> for api_models::admin::AdditionalMerchantData { fn foreign_from(value: AdditionalMerchantData) -> Self { match value { AdditionalMerchantData::OpenBankingRecipientData(data) => { Self::OpenBankingRecipientData( api_models::admin::MerchantRecipientData::foreign_from(data), ) } } } } impl ForeignFrom<api_models::admin::ConnectorAuthType> for ConnectorAuthType { fn foreign_from(value: api_models::admin::ConnectorAuthType) -> Self { match value { api_models::admin::ConnectorAuthType::TemporaryAuth => Self::TemporaryAuth, api_models::admin::ConnectorAuthType::HeaderKey { api_key } => { Self::HeaderKey { api_key } } api_models::admin::ConnectorAuthType::BodyKey { api_key, key1 } => { Self::BodyKey { api_key, key1 } } api_models::admin::ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Self::SignatureKey { api_key, key1, api_secret, }, api_models::admin::ConnectorAuthType::MultiAuthKey { api_key, key1, api_secret, key2, } => Self::MultiAuthKey { api_key, key1, api_secret, key2, }, api_models::admin::ConnectorAuthType::CurrencyAuthKey { auth_key_map } => { Self::CurrencyAuthKey { auth_key_map } } api_models::admin::ConnectorAuthType::NoKey => Self::NoKey, api_models::admin::ConnectorAuthType::CertificateAuth { certificate, private_key, } => Self::CertificateAuth { certificate, private_key, }, } } } impl ForeignFrom<ConnectorAuthType> for api_models::admin::ConnectorAuthType { fn foreign_from(from: ConnectorAuthType) -> Self { match from { ConnectorAuthType::TemporaryAuth => Self::TemporaryAuth, ConnectorAuthType::HeaderKey { api_key } => Self::HeaderKey { api_key }, ConnectorAuthType::BodyKey { api_key, key1 } => Self::BodyKey { api_key, key1 }, ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Self::SignatureKey { api_key, key1, api_secret, }, ConnectorAuthType::MultiAuthKey { api_key, key1, api_secret, key2, } => Self::MultiAuthKey { api_key, key1, api_secret, key2, }, ConnectorAuthType::CurrencyAuthKey { auth_key_map } => { Self::CurrencyAuthKey { auth_key_map } } ConnectorAuthType::NoKey => Self::NoKey, ConnectorAuthType::CertificateAuth { certificate, private_key, } => Self::CertificateAuth { certificate, private_key, }, } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ConnectorsList { pub connectors: Vec<String>, } impl ForeignFrom<&PaymentsAuthorizeRouterData> for AuthorizeSessionTokenData { fn foreign_from(data: &PaymentsAuthorizeRouterData) -> Self { Self { amount_to_capture: data.amount_captured, currency: data.request.currency, connector_transaction_id: data.payment_id.clone(), amount: Some(data.request.amount), } } } impl ForeignFrom<&ExternalVaultProxyPaymentsRouterData> for AuthorizeSessionTokenData { fn foreign_from(data: &ExternalVaultProxyPaymentsRouterData) -> Self { Self { amount_to_capture: data.amount_captured, currency: data.request.currency, connector_transaction_id: data.payment_id.clone(), amount: Some(data.request.amount), } } } impl<'a> ForeignFrom<&'a SetupMandateRouterData> for AuthorizeSessionTokenData { fn foreign_from(data: &'a SetupMandateRouterData) -> Self { Self { amount_to_capture: data.request.amount, currency: data.request.currency, connector_transaction_id: data.payment_id.clone(), amount: data.request.amount, } } } pub trait Tokenizable { fn set_session_token(&mut self, token: Option<String>); } impl Tokenizable for SetupMandateRequestData { fn set_session_token(&mut self, _token: Option<String>) {} } impl Tokenizable for PaymentsAuthorizeData { fn set_session_token(&mut self, token: Option<String>) { self.session_token = token; } } impl Tokenizable for CompleteAuthorizeData { fn set_session_token(&mut self, _token: Option<String>) {} } impl Tokenizable for ExternalVaultProxyPaymentsData { fn set_session_token(&mut self, token: Option<String>) { self.session_token = token; } } impl ForeignFrom<&SetupMandateRouterData> for PaymentsAuthorizeData { fn foreign_from(data: &SetupMandateRouterData) -> Self { Self { currency: data.request.currency, payment_method_data: data.request.payment_method_data.clone(), confirm: data.request.confirm, statement_descriptor_suffix: data.request.statement_descriptor_suffix.clone(), mandate_id: data.request.mandate_id.clone(), setup_future_usage: data.request.setup_future_usage, off_session: data.request.off_session, setup_mandate_details: data.request.setup_mandate_details.clone(), router_return_url: data.request.router_return_url.clone(), email: data.request.email.clone(), customer_name: data.request.customer_name.clone(), amount: 0, order_tax_amount: Some(MinorUnit::zero()), minor_amount: MinorUnit::new(0), statement_descriptor: None, capture_method: None, webhook_url: None, complete_authorize_url: None, browser_info: data.request.browser_info.clone(), order_details: None, order_category: None, session_token: None, enrolled_for_3ds: true, related_transaction_id: None, payment_experience: None, payment_method_type: None, customer_id: None, surcharge_details: None, request_incremental_authorization: data.request.request_incremental_authorization, metadata: None, request_extended_authorization: None, authentication_data: None, customer_acceptance: data.request.customer_acceptance.clone(), split_payments: None, // TODO: allow charges on mandates? merchant_order_reference_id: None, integrity_object: None, additional_payment_method_data: None, shipping_cost: data.request.shipping_cost, merchant_account_id: None, merchant_config_currency: None, connector_testing_data: data.request.connector_testing_data.clone(), order_id: None, locale: None, payment_channel: None, enable_partial_authorization: data.request.enable_partial_authorization, enable_overcapture: None, is_stored_credential: data.request.is_stored_credential, mit_category: None, } } } impl<F1, F2, T1, T2> ForeignFrom<(&RouterData<F1, T1, PaymentsResponseData>, T2)> for RouterData<F2, T2, PaymentsResponseData> { fn foreign_from(item: (&RouterData<F1, T1, PaymentsResponseData>, T2)) -> Self { let data = item.0; let request = item.1; Self { flow: PhantomData, request, merchant_id: data.merchant_id.clone(), connector: data.connector.clone(), attempt_id: data.attempt_id.clone(), tenant_id: data.tenant_id.clone(), status: data.status, payment_method: data.payment_method, payment_method_type: data.payment_method_type, connector_auth_type: data.connector_auth_type.clone(), description: data.description.clone(), address: data.address.clone(), auth_type: data.auth_type, connector_meta_data: data.connector_meta_data.clone(), connector_wallets_details: data.connector_wallets_details.clone(), amount_captured: data.amount_captured, minor_amount_captured: data.minor_amount_captured, access_token: data.access_token.clone(), response: data.response.clone(), payment_id: data.payment_id.clone(), session_token: data.session_token.clone(), reference_id: data.reference_id.clone(), customer_id: data.customer_id.clone(), payment_method_token: None, preprocessing_id: None, connector_customer: data.connector_customer.clone(), recurring_mandate_payment_data: data.recurring_mandate_payment_data.clone(), connector_request_reference_id: data.connector_request_reference_id.clone(), #[cfg(feature = "payouts")] payout_method_data: data.payout_method_data.clone(), #[cfg(feature = "payouts")] quote_id: data.quote_id.clone(), test_mode: data.test_mode, payment_method_status: None, payment_method_balance: data.payment_method_balance.clone(), connector_api_version: data.connector_api_version.clone(), connector_http_status_code: data.connector_http_status_code, external_latency: data.external_latency, apple_pay_flow: data.apple_pay_flow.clone(), frm_metadata: data.frm_metadata.clone(), dispute_id: data.dispute_id.clone(), refund_id: data.refund_id.clone(), connector_response: data.connector_response.clone(), integrity_check: Ok(()), additional_merchant_data: data.additional_merchant_data.clone(), header_payload: data.header_payload.clone(), 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, raw_connector_response: data.raw_connector_response.clone(), is_payment_id_from_merchant: data.is_payment_id_from_merchant, l2_l3_data: data.l2_l3_data.clone(), minor_amount_capturable: data.minor_amount_capturable, authorized_amount: data.authorized_amount, } } } #[cfg(feature = "payouts")] impl<F1, F2> ForeignFrom<( &RouterData<F1, PayoutsData, PayoutsResponseData>, PayoutsData, )> for RouterData<F2, PayoutsData, PayoutsResponseData> { fn foreign_from( item: ( &RouterData<F1, PayoutsData, PayoutsResponseData>, PayoutsData, ), ) -> Self { let data = item.0; let request = item.1; Self { flow: PhantomData, request, merchant_id: data.merchant_id.clone(), connector: data.connector.clone(), attempt_id: data.attempt_id.clone(), tenant_id: data.tenant_id.clone(), status: data.status, payment_method: data.payment_method, payment_method_type: data.payment_method_type, connector_auth_type: data.connector_auth_type.clone(), description: data.description.clone(), address: data.address.clone(), auth_type: data.auth_type, connector_meta_data: data.connector_meta_data.clone(), connector_wallets_details: data.connector_wallets_details.clone(), amount_captured: data.amount_captured, minor_amount_captured: data.minor_amount_captured, access_token: data.access_token.clone(), response: data.response.clone(), payment_id: data.payment_id.clone(), session_token: data.session_token.clone(), reference_id: data.reference_id.clone(), customer_id: data.customer_id.clone(), payment_method_token: None, recurring_mandate_payment_data: None, preprocessing_id: None, connector_customer: data.connector_customer.clone(), connector_request_reference_id: data.connector_request_reference_id.clone(), payout_method_data: data.payout_method_data.clone(), quote_id: data.quote_id.clone(), test_mode: data.test_mode, payment_method_balance: None, payment_method_status: None, connector_api_version: None, connector_http_status_code: data.connector_http_status_code, external_latency: data.external_latency, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: data.connector_response.clone(), integrity_check: Ok(()), header_payload: data.header_payload.clone(), authentication_id: None, psd2_sca_exemption_type: None, additional_merchant_data: data.additional_merchant_data.clone(), connector_mandate_request_reference_id: None, raw_connector_response: None, is_payment_id_from_merchant: data.is_payment_id_from_merchant, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, } } } #[cfg(feature = "v2")] impl ForeignFrom<&domain::MerchantConnectorAccountFeatureMetadata> for api_models::admin::MerchantConnectorAccountFeatureMetadata { fn foreign_from(item: &domain::MerchantConnectorAccountFeatureMetadata) -> Self { let revenue_recovery = item .revenue_recovery .as_ref() .map( |revenue_recovery_metadata| api_models::admin::RevenueRecoveryMetadata { max_retry_count: revenue_recovery_metadata.max_retry_count, billing_connector_retry_threshold: revenue_recovery_metadata .billing_connector_retry_threshold, billing_account_reference: revenue_recovery_metadata .mca_reference .recovery_to_billing .clone(), }, ); Self { revenue_recovery } } } #[cfg(feature = "v2")] impl ForeignTryFrom<&api_models::admin::MerchantConnectorAccountFeatureMetadata> for domain::MerchantConnectorAccountFeatureMetadata { type Error = errors::ApiErrorResponse; fn foreign_try_from( feature_metadata: &api_models::admin::MerchantConnectorAccountFeatureMetadata, ) -> Result<Self, Self::Error> { let revenue_recovery = feature_metadata .revenue_recovery .as_ref() .map(|revenue_recovery_metadata| { domain::AccountReferenceMap::new( revenue_recovery_metadata.billing_account_reference.clone(), ) .map(|mca_reference| domain::RevenueRecoveryMetadata { max_retry_count: revenue_recovery_metadata.max_retry_count, billing_connector_retry_threshold: revenue_recovery_metadata .billing_connector_retry_threshold, mca_reference, }) }) .transpose()?; Ok(Self { revenue_recovery }) } }
{ "crate": "router", "file": "crates/router/src/types.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 5, "num_structs": 7, "num_tables": null, "score": null, "total_crates": null }
file_router_8680078133308722572
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/middleware.rs // Contains: 1 structs, 0 enums use common_utils::consts::TENANT_HEADER; use futures::StreamExt; use router_env::{ logger, tracing::{field::Empty, Instrument}, }; use crate::{headers, routes::metrics}; /// Middleware to include request ID in response header. pub struct RequestId; impl<S, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for RequestId where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, >, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Transform = RequestIdMiddleware<S>; type InitError = (); type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { std::future::ready(Ok(RequestIdMiddleware { service })) } } pub struct RequestIdMiddleware<S> { service: S, } impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest> for RequestIdMiddleware<S> where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, >, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_web::dev::forward_ready!(service); fn call(&self, req: actix_web::dev::ServiceRequest) -> Self::Future { let old_x_request_id = req.headers().get("x-request-id").cloned(); let mut req = req; let request_id_fut = req.extract::<router_env::tracing_actix_web::RequestId>(); let response_fut = self.service.call(req); Box::pin( async move { let request_id = request_id_fut.await?; let request_id = request_id.as_hyphenated().to_string(); if let Some(upstream_request_id) = old_x_request_id { router_env::logger::info!(?upstream_request_id); } let mut response = response_fut.await?; response.headers_mut().append( http::header::HeaderName::from_static("x-request-id"), http::HeaderValue::from_str(&request_id)?, ); Ok(response) } .in_current_span(), ) } } /// Middleware for attaching default response headers. Headers with the same key already set in a /// response will not be overwritten. pub fn default_response_headers() -> actix_web::middleware::DefaultHeaders { use actix_web::http::header; let default_headers_middleware = actix_web::middleware::DefaultHeaders::new(); #[cfg(feature = "vergen")] let default_headers_middleware = default_headers_middleware.add(("x-hyperswitch-version", router_env::git_tag!())); default_headers_middleware // Max age of 1 year in seconds, equal to `60 * 60 * 24 * 365` seconds. .add((header::STRICT_TRANSPORT_SECURITY, "max-age=31536000")) .add((header::VIA, "HyperSwitch")) } /// Middleware to build a TOP level domain span for each request. pub struct LogSpanInitializer; impl<S, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for LogSpanInitializer where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, >, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Transform = LogSpanInitializerMiddleware<S>; type InitError = (); type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { std::future::ready(Ok(LogSpanInitializerMiddleware { service })) } } pub struct LogSpanInitializerMiddleware<S> { service: S, } impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest> for LogSpanInitializerMiddleware<S> where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, >, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_web::dev::forward_ready!(service); // TODO: have a common source of truth for the list of top level fields // /crates/router_env/src/logger/storage.rs also has a list of fields called PERSISTENT_KEYS fn call(&self, req: actix_web::dev::ServiceRequest) -> Self::Future { let tenant_id = req .headers() .get(TENANT_HEADER) .and_then(|i| i.to_str().ok()) .map(|s| s.to_owned()); let response_fut = self.service.call(req); let tenant_id_clone = tenant_id.clone(); Box::pin( async move { if let Some(tenant) = tenant_id_clone { router_env::tracing::Span::current().record("tenant_id", tenant); } let response = response_fut.await; router_env::tracing::Span::current().record("golden_log_line", true); response } .instrument( router_env::tracing::info_span!( "ROOT_SPAN", payment_id = Empty, merchant_id = Empty, connector_name = Empty, payment_method = Empty, status_code = Empty, flow = "UNKNOWN", golden_log_line = Empty, tenant_id = &tenant_id ) .or_current(), ), ) } } fn get_request_details_from_value(json_value: &serde_json::Value, parent_key: &str) -> String { match json_value { serde_json::Value::Null => format!("{parent_key}: null"), serde_json::Value::Bool(b) => format!("{parent_key}: {b}"), serde_json::Value::Number(num) => format!("{}: {}", parent_key, num.to_string().len()), serde_json::Value::String(s) => format!("{}: {}", parent_key, s.len()), serde_json::Value::Array(arr) => { let mut result = String::new(); for (index, value) in arr.iter().enumerate() { let child_key = format!("{parent_key}[{index}]"); result.push_str(&get_request_details_from_value(value, &child_key)); if index < arr.len() - 1 { result.push_str(", "); } } result } serde_json::Value::Object(obj) => { let mut result = String::new(); for (index, (key, value)) in obj.iter().enumerate() { let child_key = format!("{parent_key}[{key}]"); result.push_str(&get_request_details_from_value(value, &child_key)); if index < obj.len() - 1 { result.push_str(", "); } } result } } } /// Middleware for Logging request_details of HTTP 400 Bad Requests pub struct Http400RequestDetailsLogger; impl<S: 'static, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for Http400RequestDetailsLogger where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, >, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Transform = Http400RequestDetailsLoggerMiddleware<S>; type InitError = (); type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { std::future::ready(Ok(Http400RequestDetailsLoggerMiddleware { service: std::rc::Rc::new(service), })) } } pub struct Http400RequestDetailsLoggerMiddleware<S> { service: std::rc::Rc<S>, } impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest> for Http400RequestDetailsLoggerMiddleware<S> where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, > + 'static, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_web::dev::forward_ready!(service); fn call(&self, mut req: actix_web::dev::ServiceRequest) -> Self::Future { let svc = self.service.clone(); let request_id_fut = req.extract::<router_env::tracing_actix_web::RequestId>(); Box::pin(async move { let (http_req, payload) = req.into_parts(); let result_payload: Vec<Result<bytes::Bytes, actix_web::error::PayloadError>> = payload.collect().await; let payload = result_payload .into_iter() .collect::<Result<Vec<bytes::Bytes>, actix_web::error::PayloadError>>()?; let bytes = payload.clone().concat().to_vec(); let bytes_length = bytes.len(); // we are creating h1 payload manually from bytes, currently there's no way to create http2 payload with actix let (_, mut new_payload) = actix_http::h1::Payload::create(true); new_payload.unread_data(bytes.to_vec().clone().into()); let new_req = actix_web::dev::ServiceRequest::from_parts(http_req, new_payload.into()); let content_length_header = new_req .headers() .get(headers::CONTENT_LENGTH) .map(ToOwned::to_owned); let response_fut = svc.call(new_req); let response = response_fut.await?; // Log the request_details when we receive 400 status from the application if response.status() == 400 { let request_id = request_id_fut.await?.as_hyphenated().to_string(); let content_length_header_string = content_length_header .map(|content_length_header| { content_length_header.to_str().map(ToOwned::to_owned) }) .transpose() .inspect_err(|error| { logger::warn!("Could not convert content length to string {error:?}"); }) .ok() .flatten(); logger::info!("Content length from header: {content_length_header_string:?}, Bytes length: {bytes_length}"); if !bytes.is_empty() { let value_result: Result<serde_json::Value, serde_json::Error> = serde_json::from_slice(&bytes); match value_result { Ok(value) => { logger::info!( "request_id: {request_id}, request_details: {}", get_request_details_from_value(&value, "") ); } Err(err) => { logger::warn!("error while parsing the request in json value: {err}"); } } } else { logger::info!("request_id: {request_id}, request_details: Empty Body"); } } Ok(response) }) } } /// Middleware for Adding Accept-Language header based on query params pub struct AddAcceptLanguageHeader; impl<S: 'static, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for AddAcceptLanguageHeader where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, >, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Transform = AddAcceptLanguageHeaderMiddleware<S>; type InitError = (); type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { std::future::ready(Ok(AddAcceptLanguageHeaderMiddleware { service: std::rc::Rc::new(service), })) } } pub struct AddAcceptLanguageHeaderMiddleware<S> { service: std::rc::Rc<S>, } impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest> for AddAcceptLanguageHeaderMiddleware<S> where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, > + 'static, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_web::dev::forward_ready!(service); fn call(&self, mut req: actix_web::dev::ServiceRequest) -> Self::Future { let svc = self.service.clone(); Box::pin(async move { #[derive(serde::Deserialize)] struct LocaleQueryParam { locale: Option<String>, } let query_params = req.query_string(); let locale_param = serde_qs::from_str::<LocaleQueryParam>(query_params).map_err(|error| { actix_web::error::ErrorBadRequest(format!( "Could not convert query params to locale query parmas: {error:?}", )) })?; let accept_language_header = req.headers().get(http::header::ACCEPT_LANGUAGE); if let Some(locale) = locale_param.locale { req.headers_mut().insert( http::header::ACCEPT_LANGUAGE, http::HeaderValue::from_str(&locale)?, ); } else if accept_language_header.is_none() { req.headers_mut().insert( http::header::ACCEPT_LANGUAGE, http::HeaderValue::from_static("en"), ); } let response_fut = svc.call(req); let response = response_fut.await?; Ok(response) }) } } /// Middleware for recording request-response metrics pub struct RequestResponseMetrics; impl<S: 'static, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for RequestResponseMetrics where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, >, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Transform = RequestResponseMetricsMiddleware<S>; type InitError = (); type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { std::future::ready(Ok(RequestResponseMetricsMiddleware { service: std::rc::Rc::new(service), })) } } pub struct RequestResponseMetricsMiddleware<S> { service: std::rc::Rc<S>, } impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest> for RequestResponseMetricsMiddleware<S> where S: actix_web::dev::Service< actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse<B>, Error = actix_web::Error, > + 'static, S::Future: 'static, B: 'static, { type Response = actix_web::dev::ServiceResponse<B>; type Error = actix_web::Error; type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_web::dev::forward_ready!(service); fn call(&self, req: actix_web::dev::ServiceRequest) -> Self::Future { use std::borrow::Cow; let svc = self.service.clone(); let request_path = req .match_pattern() .map(Cow::<'static, str>::from) .unwrap_or_else(|| "UNKNOWN".into()); let request_method = Cow::<'static, str>::from(req.method().as_str().to_owned()); Box::pin(async move { let mut attributes = router_env::metric_attributes!(("path", request_path), ("method", request_method)) .to_vec(); let response_fut = svc.call(req); metrics::REQUESTS_RECEIVED.add(1, &attributes); let (response_result, request_duration) = common_utils::metrics::utils::time_future(response_fut).await; let response = response_result?; attributes.extend_from_slice(router_env::metric_attributes!(( "status_code", i64::from(response.status().as_u16()) ))); metrics::REQUEST_TIME.record(request_duration.as_secs_f64(), &attributes); Ok(response) }) } }
{ "crate": "router", "file": "crates/router/src/middleware.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-7495256651845769483
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/utils.rs // Contains: 1 structs, 0 enums pub mod chat; #[cfg(feature = "olap")] pub mod connector_onboarding; pub mod currency; pub mod db_utils; pub mod ext_traits; #[cfg(feature = "kv_store")] pub mod storage_partitioning; #[cfg(feature = "olap")] pub mod user; #[cfg(feature = "olap")] pub mod user_role; #[cfg(feature = "olap")] pub mod verify_connector; use std::fmt::Debug; use api_models::{ enums, payments::{self}, webhooks, }; use common_utils::types::keymanager::KeyManagerState; pub use common_utils::{ crypto::{self, Encryptable}, ext_traits::{ByteSliceExt, BytesExt, Encode, StringExt, ValueExt}, fp_utils::when, id_type, pii, validation::validate_email, }; #[cfg(feature = "v1")] use common_utils::{ type_name, types::keymanager::{Identifier, ToEncryptable}, }; use error_stack::ResultExt; pub use hyperswitch_connectors::utils::QrImage; use hyperswitch_domain_models::payments::PaymentIntent; #[cfg(feature = "v1")] use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation}; use masking::{ExposeInterface, SwitchStrategy}; use nanoid::nanoid; use serde::de::DeserializeOwned; use serde_json::Value; #[cfg(feature = "v1")] use subscriptions::subscription_handler::SubscriptionHandler; use tracing_futures::Instrument; pub use self::ext_traits::{OptionExt, ValidateCall}; use crate::{ consts, core::{ authentication::types::ExternalThreeDSConnectorMetadata, errors::{self, CustomResult, RouterResult, StorageErrorExt}, payments as payments_core, }, headers::ACCEPT_LANGUAGE, logger, routes::{metrics, SessionState}, services::{self, authentication::get_header_value_by_key}, types::{self, domain, transformers::ForeignInto}, }; #[cfg(feature = "v1")] use crate::{core::webhooks as webhooks_core, types::storage}; pub mod error_parser { use std::fmt::Display; use actix_web::{ error::{Error, JsonPayloadError}, http::StatusCode, HttpRequest, ResponseError, }; #[derive(Debug)] struct CustomJsonError { err: JsonPayloadError, } // Display is a requirement defined by the actix crate for implementing ResponseError trait impl Display for CustomJsonError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str( serde_json::to_string(&serde_json::json!({ "error": { "error_type": "invalid_request", "message": self.err.to_string(), "code": "IR_06", } })) .as_deref() .unwrap_or("Invalid Json Error"), ) } } impl ResponseError for CustomJsonError { fn status_code(&self) -> StatusCode { StatusCode::BAD_REQUEST } fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> { use actix_web::http::header; actix_web::HttpResponseBuilder::new(self.status_code()) .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)) .body(self.to_string()) } } pub fn custom_json_error_handler(err: JsonPayloadError, _req: &HttpRequest) -> Error { Error::from(CustomJsonError { err }) } } #[inline] pub fn generate_id(length: usize, prefix: &str) -> String { format!("{}_{}", prefix, nanoid!(length, &consts::ALPHABETS)) } pub trait ConnectorResponseExt: Sized { fn get_response(self) -> RouterResult<types::Response>; fn get_error_response(self) -> RouterResult<types::Response>; fn get_response_inner<T: DeserializeOwned>(self, type_name: &'static str) -> RouterResult<T> { self.get_response()? .response .parse_struct(type_name) .change_context(errors::ApiErrorResponse::InternalServerError) } } impl<E> ConnectorResponseExt for Result<Result<types::Response, types::Response>, error_stack::Report<E>> { fn get_error_response(self) -> RouterResult<types::Response> { self.map_err(|error| error.change_context(errors::ApiErrorResponse::InternalServerError)) .attach_printable("Error while receiving response") .and_then(|inner| match inner { Ok(res) => { logger::error!(response=?res); Err(errors::ApiErrorResponse::InternalServerError).attach_printable(format!( "Expecting error response, received response: {res:?}" )) } Err(err_res) => Ok(err_res), }) } fn get_response(self) -> RouterResult<types::Response> { self.map_err(|error| error.change_context(errors::ApiErrorResponse::InternalServerError)) .attach_printable("Error while receiving response") .and_then(|inner| match inner { Err(err_res) => { logger::error!(error_response=?err_res); Err(errors::ApiErrorResponse::InternalServerError).attach_printable(format!( "Expecting response, received error response: {err_res:?}" )) } Ok(res) => Ok(res), }) } } #[inline] pub fn get_payout_attempt_id(payout_id: &str, attempt_count: i16) -> String { format!("{payout_id}_{attempt_count}") } #[cfg(feature = "v1")] pub async fn find_payment_intent_from_payment_id_type( state: &SessionState, payment_id_type: payments::PaymentIdType, merchant_context: &domain::MerchantContext, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { let key_manager_state: KeyManagerState = state.into(); let db = &*state.store; match payment_id_type { payments::PaymentIdType::PaymentIntentId(payment_id) => db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound), payments::PaymentIdType::ConnectorTransactionId(connector_transaction_id) => { let attempt = db .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_context.get_merchant_account().get_id(), &connector_transaction_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &attempt.payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } payments::PaymentIdType::PaymentAttemptId(attempt_id) => { let attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &attempt_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &attempt.payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } payments::PaymentIdType::PreprocessingId(_) => { Err(errors::ApiErrorResponse::PaymentNotFound)? } } } #[cfg(feature = "v1")] pub async fn find_payment_intent_from_refund_id_type( state: &SessionState, refund_id_type: webhooks::RefundIdType, merchant_context: &domain::MerchantContext, connector_name: &str, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { let db = &*state.store; let refund = match refund_id_type { webhooks::RefundIdType::RefundId(id) => db .find_refund_by_merchant_id_refund_id( merchant_context.get_merchant_account().get_id(), &id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?, webhooks::RefundIdType::ConnectorRefundId(id) => db .find_refund_by_merchant_id_connector_refund_id_connector( merchant_context.get_merchant_account().get_id(), &id, connector_name, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?, }; let attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &refund.attempt_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( &state.into(), &attempt.payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } #[cfg(feature = "v1")] pub async fn find_payment_intent_from_mandate_id_type( state: &SessionState, mandate_id_type: webhooks::MandateIdType, merchant_context: &domain::MerchantContext, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { let db = &*state.store; let mandate = match mandate_id_type { webhooks::MandateIdType::MandateId(mandate_id) => db .find_mandate_by_merchant_id_mandate_id( merchant_context.get_merchant_account().get_id(), mandate_id.as_str(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?, webhooks::MandateIdType::ConnectorMandateId(connector_mandate_id) => db .find_mandate_by_merchant_id_connector_mandate_id( merchant_context.get_merchant_account().get_id(), connector_mandate_id.as_str(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?, }; db.find_payment_intent_by_payment_id_merchant_id( &state.into(), &mandate .original_payment_id .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("original_payment_id not present in mandate record")?, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } #[cfg(feature = "v1")] pub async fn find_mca_from_authentication_id_type( state: &SessionState, authentication_id_type: webhooks::AuthenticationIdType, merchant_context: &domain::MerchantContext, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; let authentication = match authentication_id_type { webhooks::AuthenticationIdType::AuthenticationId(authentication_id) => db .find_authentication_by_merchant_id_authentication_id( merchant_context.get_merchant_account().get_id(), &authentication_id, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?, webhooks::AuthenticationIdType::ConnectorAuthenticationId(connector_authentication_id) => { db.find_authentication_by_merchant_id_connector_authentication_id( merchant_context.get_merchant_account().get_id().clone(), connector_authentication_id, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)? } }; #[cfg(feature = "v1")] { // raise error if merchant_connector_id is not present since it should we be present in the current flow let mca_id = authentication .merchant_connector_id .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("merchant_connector_id not present in authentication record")?; db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( &state.into(), merchant_context.get_merchant_account().get_id(), &mca_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: mca_id.get_string_repr().to_string(), }, ) } #[cfg(feature = "v2")] //get mca using id { let _ = key_store; let _ = authentication; todo!() } } #[cfg(feature = "v1")] pub async fn get_mca_from_payment_intent( state: &SessionState, merchant_context: &domain::MerchantContext, payment_intent: PaymentIntent, connector_name: &str, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; let key_manager_state: &KeyManagerState = &state.into(); #[cfg(feature = "v1")] let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &payment_intent.active_attempt.get_id(), merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; #[cfg(feature = "v2")] let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( key_manager_state, key_store, &payment_intent.active_attempt.get_id(), merchant_account.get_id(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; match payment_attempt.merchant_connector_id { Some(merchant_connector_id) => { #[cfg(feature = "v1")] { db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_context.get_merchant_account().get_id(), &merchant_connector_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, ) } #[cfg(feature = "v2")] { //get mca using id let _id = merchant_connector_id; let _ = key_store; let _ = key_manager_state; let _ = connector_name; todo!() } } None => { let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")? .clone(); #[cfg(feature = "v1")] { db.find_merchant_connector_account_by_profile_id_connector_name( key_manager_state, &profile_id, connector_name, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: format!( "profile_id {} and connector_name {connector_name}", profile_id.get_string_repr() ), }, ) } #[cfg(feature = "v2")] { //get mca using id let _ = profile_id; todo!() } } } } #[cfg(feature = "payouts")] pub async fn get_mca_from_payout_attempt( state: &SessionState, merchant_context: &domain::MerchantContext, payout_id_type: webhooks::PayoutIdType, connector_name: &str, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; let payout = match payout_id_type { webhooks::PayoutIdType::PayoutAttemptId(payout_attempt_id) => db .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_context.get_merchant_account().get_id(), &payout_attempt_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?, webhooks::PayoutIdType::ConnectorPayoutId(connector_payout_id) => db .find_payout_attempt_by_merchant_id_connector_payout_id( merchant_context.get_merchant_account().get_id(), &connector_payout_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?, }; let key_manager_state: &KeyManagerState = &state.into(); match payout.merchant_connector_id { Some(merchant_connector_id) => { #[cfg(feature = "v1")] { db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_context.get_merchant_account().get_id(), &merchant_connector_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, ) } #[cfg(feature = "v2")] { //get mca using id let _id = merchant_connector_id; let _ = merchant_context.get_merchant_key_store(); let _ = connector_name; let _ = key_manager_state; todo!() } } None => { #[cfg(feature = "v1")] { db.find_merchant_connector_account_by_profile_id_connector_name( key_manager_state, &payout.profile_id, connector_name, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: format!( "profile_id {} and connector_name {}", payout.profile_id.get_string_repr(), connector_name ), }, ) } #[cfg(feature = "v2")] { todo!() } } } } #[cfg(feature = "v1")] pub async fn get_mca_from_object_reference_id( state: &SessionState, object_reference_id: webhooks::ObjectReferenceId, merchant_context: &domain::MerchantContext, connector_name: &str, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; #[cfg(feature = "v1")] let default_profile_id = merchant_context .get_merchant_account() .default_profile .as_ref(); #[cfg(feature = "v2")] let default_profile_id = Option::<&String>::None; match default_profile_id { Some(profile_id) => { #[cfg(feature = "v1")] { db.find_merchant_connector_account_by_profile_id_connector_name( &state.into(), profile_id, connector_name, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: format!( "profile_id {} and connector_name {connector_name}", profile_id.get_string_repr() ), }, ) } #[cfg(feature = "v2")] { let _db = db; let _profile_id = profile_id; todo!() } } _ => match object_reference_id { webhooks::ObjectReferenceId::PaymentId(payment_id_type) => { get_mca_from_payment_intent( state, merchant_context, find_payment_intent_from_payment_id_type( state, payment_id_type, merchant_context, ) .await?, connector_name, ) .await } webhooks::ObjectReferenceId::RefundId(refund_id_type) => { get_mca_from_payment_intent( state, merchant_context, find_payment_intent_from_refund_id_type( state, refund_id_type, merchant_context, connector_name, ) .await?, connector_name, ) .await } webhooks::ObjectReferenceId::MandateId(mandate_id_type) => { get_mca_from_payment_intent( state, merchant_context, find_payment_intent_from_mandate_id_type( state, mandate_id_type, merchant_context, ) .await?, connector_name, ) .await } webhooks::ObjectReferenceId::ExternalAuthenticationID(authentication_id_type) => { find_mca_from_authentication_id_type( state, authentication_id_type, merchant_context, ) .await } webhooks::ObjectReferenceId::SubscriptionId(subscription_id_type) => { #[cfg(feature = "v1")] { let subscription_state = state.clone().into(); let subscription_handler = SubscriptionHandler::new(&subscription_state, merchant_context); let mut subscription_with_handler = subscription_handler .find_subscription(subscription_id_type) .await?; subscription_with_handler.get_mca(connector_name).await } #[cfg(feature = "v2")] { let _db = db; todo!() } } #[cfg(feature = "payouts")] webhooks::ObjectReferenceId::PayoutId(payout_id_type) => { get_mca_from_payout_attempt(state, merchant_context, payout_id_type, connector_name) .await } }, } } // validate json format for the error pub fn handle_json_response_deserialization_failure( res: types::Response, connector: &'static str, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { metrics::RESPONSE_DESERIALIZATION_FAILURE .add(1, router_env::metric_attributes!(("connector", connector))); let response_data = String::from_utf8(res.response.to_vec()) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; // check for whether the response is in json format match serde_json::from_str::<Value>(&response_data) { // in case of unexpected response but in json format Ok(_) => Err(errors::ConnectorError::ResponseDeserializationFailed)?, // in case of unexpected response but in html or string format Err(error_msg) => { logger::error!(deserialization_error=?error_msg); logger::error!("UNEXPECTED RESPONSE FROM CONNECTOR: {}", response_data); Ok(types::ErrorResponse { status_code: res.status_code, code: consts::NO_ERROR_CODE.to_string(), message: consts::UNSUPPORTED_ERROR_MESSAGE.to_string(), reason: Some(response_data), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } } pub fn get_http_status_code_type( status_code: u16, ) -> CustomResult<String, errors::ApiErrorResponse> { let status_code_type = match status_code { 100..=199 => "1xx", 200..=299 => "2xx", 300..=399 => "3xx", 400..=499 => "4xx", 500..=599 => "5xx", _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid http status code")?, }; Ok(status_code_type.to_string()) } pub fn add_connector_http_status_code_metrics(option_status_code: Option<u16>) { if let Some(status_code) = option_status_code { let status_code_type = get_http_status_code_type(status_code).ok(); match status_code_type.as_deref() { Some("1xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_1XX_COUNT.add(1, &[]), Some("2xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_2XX_COUNT.add(1, &[]), Some("3xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_3XX_COUNT.add(1, &[]), Some("4xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_4XX_COUNT.add(1, &[]), Some("5xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_5XX_COUNT.add(1, &[]), _ => logger::info!("Skip metrics as invalid http status code received from connector"), }; } else { logger::info!("Skip metrics as no http status code received from connector") } } #[cfg(feature = "v1")] #[async_trait::async_trait] pub trait CustomerAddress { async fn get_address_update( &self, state: &SessionState, address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, merchant_id: id_type::MerchantId, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError>; async fn get_domain_address( &self, state: &SessionState, address_details: payments::AddressDetails, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError>; } #[cfg(feature = "v1")] #[async_trait::async_trait] impl CustomerAddress for api_models::customers::CustomerRequest { async fn get_address_update( &self, state: &SessionState, address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, merchant_id: id_type::MerchantId, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError> { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address_details.line1.clone(), line2: address_details.line2.clone(), line3: address_details.line3.clone(), state: address_details.state.clone(), first_name: address_details.first_name.clone(), last_name: address_details.last_name.clone(), zip: address_details.zip.clone(), phone_number: self.phone.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), origin_zip: address_details.origin_zip.clone(), }, )), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; Ok(storage::AddressUpdate::Update { city: address_details.city, country: address_details.country, line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, zip: encryptable_address.zip, state: encryptable_address.state, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: self.phone_country_code.clone(), updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), origin_zip: encryptable_address.origin_zip, }) } async fn get_domain_address( &self, state: &SessionState, address_details: payments::AddressDetails, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError> { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address_details.line1.clone(), line2: address_details.line2.clone(), line3: address_details.line3.clone(), state: address_details.state.clone(), first_name: address_details.first_name.clone(), last_name: address_details.last_name.clone(), zip: address_details.zip.clone(), phone_number: self.phone.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), origin_zip: address_details.origin_zip.clone(), }, )), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; let address = domain::Address { city: address_details.city, country: address_details.country, line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, zip: encryptable_address.zip, state: encryptable_address.state, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: self.phone_country_code.clone(), merchant_id: merchant_id.to_owned(), address_id: generate_id(consts::ID_LENGTH, "add"), created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), origin_zip: encryptable_address.origin_zip, }; Ok(domain::CustomerAddress { address, customer_id: customer_id.to_owned(), }) } } #[cfg(feature = "v1")] #[async_trait::async_trait] impl CustomerAddress for api_models::customers::CustomerUpdateRequest { async fn get_address_update( &self, state: &SessionState, address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, merchant_id: id_type::MerchantId, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError> { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address_details.line1.clone(), line2: address_details.line2.clone(), line3: address_details.line3.clone(), state: address_details.state.clone(), first_name: address_details.first_name.clone(), last_name: address_details.last_name.clone(), zip: address_details.zip.clone(), phone_number: self.phone.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), origin_zip: address_details.origin_zip.clone(), }, )), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; Ok(storage::AddressUpdate::Update { city: address_details.city, country: address_details.country, line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, zip: encryptable_address.zip, state: encryptable_address.state, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: self.phone_country_code.clone(), updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), origin_zip: encryptable_address.origin_zip, }) } async fn get_domain_address( &self, state: &SessionState, address_details: payments::AddressDetails, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError> { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address_details.line1.clone(), line2: address_details.line2.clone(), line3: address_details.line3.clone(), state: address_details.state.clone(), first_name: address_details.first_name.clone(), last_name: address_details.last_name.clone(), zip: address_details.zip.clone(), phone_number: self.phone.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), origin_zip: address_details.origin_zip.clone(), }, )), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; let address = domain::Address { city: address_details.city, country: address_details.country, line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, zip: encryptable_address.zip, state: encryptable_address.state, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: self.phone_country_code.clone(), merchant_id: merchant_id.to_owned(), address_id: generate_id(consts::ID_LENGTH, "add"), created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), origin_zip: encryptable_address.origin_zip, }; Ok(domain::CustomerAddress { address, customer_id: customer_id.to_owned(), }) } } pub fn add_apple_pay_flow_metrics( apple_pay_flow: &Option<domain::ApplePayFlow>, connector: Option<String>, merchant_id: id_type::MerchantId, ) { if let Some(flow) = apple_pay_flow { match flow { domain::ApplePayFlow::Simplified(_) => metrics::APPLE_PAY_SIMPLIFIED_FLOW.add( 1, router_env::metric_attributes!( ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_id.clone()), ), ), domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW.add( 1, router_env::metric_attributes!( ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_id.clone()), ), ), } } } pub fn add_apple_pay_payment_status_metrics( payment_attempt_status: enums::AttemptStatus, apple_pay_flow: Option<domain::ApplePayFlow>, connector: Option<String>, merchant_id: id_type::MerchantId, ) { if payment_attempt_status == enums::AttemptStatus::Charged { if let Some(flow) = apple_pay_flow { match flow { domain::ApplePayFlow::Simplified(_) => { metrics::APPLE_PAY_SIMPLIFIED_FLOW_SUCCESSFUL_PAYMENT.add( 1, router_env::metric_attributes!( ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_id.clone()), ), ) } domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_SUCCESSFUL_PAYMENT .add( 1, router_env::metric_attributes!( ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_id.clone()), ), ), } } } else if payment_attempt_status == enums::AttemptStatus::Failure { if let Some(flow) = apple_pay_flow { match flow { domain::ApplePayFlow::Simplified(_) => { metrics::APPLE_PAY_SIMPLIFIED_FLOW_FAILED_PAYMENT.add( 1, router_env::metric_attributes!( ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_id.clone()), ), ) } domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT.add( 1, router_env::metric_attributes!( ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_id.clone()), ), ), } } } } pub fn check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata( metadata: Option<Value>, ) -> bool { let external_three_ds_connector_metadata: Option<ExternalThreeDSConnectorMetadata> = metadata .parse_value("ExternalThreeDSConnectorMetadata") .map_err(|err| logger::warn!(parsing_error=?err,"Error while parsing ExternalThreeDSConnectorMetadata")) .ok(); external_three_ds_connector_metadata .and_then(|metadata| metadata.pull_mechanism_for_external_3ds_enabled) .unwrap_or(true) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn trigger_payments_webhook<F, Op, D>( merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: &domain::MerchantKeyStore, payment_data: D, customer: Option<domain::Customer>, state: &SessionState, operation: Op, ) -> RouterResult<()> where F: Send + Clone + Sync, Op: Debug, D: payments_core::OperationSessionGetters<F>, { todo!() } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn trigger_payments_webhook<F, Op, D>( merchant_context: domain::MerchantContext, business_profile: domain::Profile, payment_data: D, customer: Option<domain::Customer>, state: &SessionState, operation: Op, ) -> RouterResult<()> where F: Send + Clone + Sync, Op: Debug, D: payments_core::OperationSessionGetters<F>, { let status = payment_data.get_payment_intent().status; 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, customer, services::AuthFlow::Merchant, &state.base_url, &operation, &state.conf.connector_request_reference_id_config, None, None, None, )?; let event_type = status.into(); if let services::ApplicationResponse::JsonWithHeaders((payments_response_json, _)) = payments_response { let cloned_state = state.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. if let Some(event_type) = event_type { tokio::spawn( async move { let primary_object_created_at = payments_response_json.created; Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook( cloned_state, merchant_context.clone(), business_profile, event_type, diesel_models::enums::EventClass::Payments, payment_id.get_string_repr().to_owned(), diesel_models::enums::EventObjectType::PaymentDetails, webhooks::OutgoingWebhookContent::PaymentDetails(Box::new( payments_response_json, )), primary_object_created_at, )) .await } .in_current_span(), ); } else { logger::warn!( "Outgoing webhook not sent because of missing event type status mapping" ); } } } Ok(()) } type Handle<T> = tokio::task::JoinHandle<RouterResult<T>>; pub async fn flatten_join_error<T>(handle: Handle<T>) -> RouterResult<T> { match handle.await { Ok(Ok(t)) => Ok(t), Ok(Err(err)) => Err(err), Err(err) => Err(err) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Join Error"), } } #[cfg(feature = "v1")] pub async fn trigger_refund_outgoing_webhook( state: &SessionState, merchant_context: &domain::MerchantContext, refund: &diesel_models::Refund, profile_id: id_type::ProfileId, ) -> RouterResult<()> { let refund_status = refund.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 refund_id = refund_response.refund_id.clone(); let cloned_state = state.clone(); let cloned_merchant_context = merchant_context.clone(); let primary_object_created_at = refund_response.created_at; if let Some(outgoing_event_type) = event_type { tokio::spawn( async move { Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook( cloned_state, cloned_merchant_context, business_profile, outgoing_event_type, diesel_models::enums::EventClass::Refunds, refund_id.to_string(), diesel_models::enums::EventObjectType::RefundDetails, webhooks::OutgoingWebhookContent::RefundDetails(Box::new(refund_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(feature = "v2")] pub async fn trigger_refund_outgoing_webhook( state: &SessionState, merchant_account: &domain::MerchantAccount, refund: &diesel_models::Refund, profile_id: id_type::ProfileId, key_store: &domain::MerchantKeyStore, ) -> RouterResult<()> { todo!() } pub fn get_locale_from_header(headers: &actix_web::http::header::HeaderMap) -> String { get_header_value_by_key(ACCEPT_LANGUAGE.into(), headers) .ok() .flatten() .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.get_string_repr().to_owned(), 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!() }
{ "crate": "router", "file": "crates/router/src/utils.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-2264682229645094307
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/compatibility/stripe/webhooks.rs // Contains: 4 structs, 4 enums #[cfg(feature = "payouts")] use api_models::payouts as payout_models; use api_models::{ enums::{Currency, DisputeStatus, MandateStatus}, webhooks::{self as api}, }; use common_utils::{crypto::SignMessage, date_time, ext_traits::Encode}; #[cfg(feature = "payouts")] use common_utils::{ id_type, pii::{self, Email}, }; use error_stack::ResultExt; use router_env::logger; use serde::Serialize; use super::{ payment_intents::types::StripePaymentIntentResponse, refunds::types::StripeRefundResponse, }; use crate::{ core::{ errors, webhooks::types::{OutgoingWebhookPayloadWithSignature, OutgoingWebhookType}, }, headers, services::request::Maskable, }; #[derive(Serialize, Debug)] pub struct StripeOutgoingWebhook { id: String, #[serde(rename = "type")] stype: &'static str, object: &'static str, data: StripeWebhookObject, created: u64, // api_version: "2019-11-05", // not used } impl OutgoingWebhookType for StripeOutgoingWebhook { fn get_outgoing_webhooks_signature( &self, payment_response_hash_key: Option<impl AsRef<[u8]>>, ) -> errors::CustomResult<OutgoingWebhookPayloadWithSignature, errors::WebhooksFlowError> { let timestamp = self.created; let payment_response_hash_key = payment_response_hash_key .ok_or(errors::WebhooksFlowError::MerchantConfigNotFound) .attach_printable("For stripe compatibility payment_response_hash_key is mandatory")?; let webhook_signature_payload = self .encode_to_string_of_json() .change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed) .attach_printable("failed encoding outgoing webhook payload")?; let new_signature_payload = format!("{timestamp}.{webhook_signature_payload}"); let v1 = hex::encode( common_utils::crypto::HmacSha256::sign_message( &common_utils::crypto::HmacSha256, payment_response_hash_key.as_ref(), new_signature_payload.as_bytes(), ) .change_context(errors::WebhooksFlowError::OutgoingWebhookSigningFailed) .attach_printable("Failed to sign the message")?, ); let t = timestamp; let signature = Some(format!("t={t},v1={v1}")); Ok(OutgoingWebhookPayloadWithSignature { payload: webhook_signature_payload.into(), signature, }) } fn add_webhook_header(header: &mut Vec<(String, Maskable<String>)>, signature: String) { header.push(( headers::STRIPE_COMPATIBLE_WEBHOOK_SIGNATURE.to_string(), signature.into(), )) } } #[derive(Serialize, Debug)] #[serde(tag = "type", content = "object", rename_all = "snake_case")] pub enum StripeWebhookObject { PaymentIntent(Box<StripePaymentIntentResponse>), Refund(StripeRefundResponse), Dispute(StripeDisputeResponse), Mandate(StripeMandateResponse), #[cfg(feature = "payouts")] Payout(StripePayoutResponse), } #[derive(Serialize, Debug)] pub struct StripeDisputeResponse { pub id: String, pub amount: String, pub currency: Currency, pub payment_intent: id_type::PaymentId, pub reason: Option<String>, pub status: StripeDisputeStatus, } #[derive(Serialize, Debug)] pub struct StripeMandateResponse { pub mandate_id: String, pub status: StripeMandateStatus, pub payment_method_id: String, pub payment_method: String, } #[cfg(feature = "payouts")] #[derive(Clone, Serialize, Debug)] pub struct StripePayoutResponse { pub id: id_type::PayoutId, pub amount: i64, pub currency: String, pub payout_type: Option<common_enums::PayoutType>, pub status: StripePayoutStatus, pub name: Option<masking::Secret<String>>, pub email: Option<Email>, pub phone: Option<masking::Secret<String>>, pub phone_country_code: Option<String>, pub created: Option<i64>, pub metadata: Option<pii::SecretSerdeValue>, pub entity_type: common_enums::PayoutEntityType, pub recurring: bool, pub error_message: Option<String>, pub error_code: Option<String>, } #[cfg(feature = "payouts")] #[derive(Clone, Serialize, Debug)] #[serde(rename_all = "snake_case")] pub enum StripePayoutStatus { PayoutSuccess, PayoutFailure, PayoutProcessing, PayoutCancelled, PayoutInitiated, PayoutExpired, PayoutReversed, } #[cfg(feature = "payouts")] impl From<common_enums::PayoutStatus> for StripePayoutStatus { fn from(status: common_enums::PayoutStatus) -> Self { match status { common_enums::PayoutStatus::Success => Self::PayoutSuccess, common_enums::PayoutStatus::Failed => Self::PayoutFailure, common_enums::PayoutStatus::Cancelled => Self::PayoutCancelled, common_enums::PayoutStatus::Initiated => Self::PayoutInitiated, common_enums::PayoutStatus::Expired => Self::PayoutExpired, common_enums::PayoutStatus::Reversed => Self::PayoutReversed, common_enums::PayoutStatus::Pending | common_enums::PayoutStatus::Ineligible | common_enums::PayoutStatus::RequiresCreation | common_enums::PayoutStatus::RequiresFulfillment | common_enums::PayoutStatus::RequiresPayoutMethodData | common_enums::PayoutStatus::RequiresVendorAccountCreation | common_enums::PayoutStatus::RequiresConfirmation => Self::PayoutProcessing, } } } #[cfg(feature = "payouts")] impl From<payout_models::PayoutCreateResponse> for StripePayoutResponse { fn from(res: payout_models::PayoutCreateResponse) -> Self { let (name, email, phone, phone_country_code) = match res.customer { Some(customer) => ( customer.name, customer.email, customer.phone, customer.phone_country_code, ), None => (None, None, None, None), }; Self { id: res.payout_id, amount: res.amount.get_amount_as_i64(), currency: res.currency.to_string(), payout_type: res.payout_type, status: StripePayoutStatus::from(res.status), name, email, phone, phone_country_code, created: res.created.map(|t| t.assume_utc().unix_timestamp()), metadata: res.metadata, entity_type: res.entity_type, recurring: res.recurring, error_message: res.error_message, error_code: res.error_code, } } } #[derive(Serialize, Debug)] #[serde(rename_all = "snake_case")] pub enum StripeMandateStatus { Active, Inactive, Pending, } #[derive(Serialize, Debug)] #[serde(rename_all = "snake_case")] pub enum StripeDisputeStatus { WarningNeedsResponse, WarningUnderReview, WarningClosed, NeedsResponse, UnderReview, ChargeRefunded, Won, Lost, } impl From<api_models::disputes::DisputeResponse> for StripeDisputeResponse { fn from(res: api_models::disputes::DisputeResponse) -> Self { Self { id: res.dispute_id, amount: res.amount.to_string(), currency: res.currency, payment_intent: res.payment_id, reason: res.connector_reason, status: StripeDisputeStatus::from(res.dispute_status), } } } impl From<api_models::mandates::MandateResponse> for StripeMandateResponse { fn from(res: api_models::mandates::MandateResponse) -> Self { Self { mandate_id: res.mandate_id, payment_method: res.payment_method, payment_method_id: res.payment_method_id, status: StripeMandateStatus::from(res.status), } } } impl From<MandateStatus> for StripeMandateStatus { fn from(status: MandateStatus) -> Self { match status { MandateStatus::Active => Self::Active, MandateStatus::Inactive | MandateStatus::Revoked => Self::Inactive, MandateStatus::Pending => Self::Pending, } } } impl From<DisputeStatus> for StripeDisputeStatus { fn from(status: DisputeStatus) -> Self { match status { DisputeStatus::DisputeOpened => Self::WarningNeedsResponse, DisputeStatus::DisputeExpired => Self::Lost, DisputeStatus::DisputeAccepted => Self::Lost, DisputeStatus::DisputeCancelled => Self::WarningClosed, DisputeStatus::DisputeChallenged => Self::WarningUnderReview, DisputeStatus::DisputeWon => Self::Won, DisputeStatus::DisputeLost => Self::Lost, } } } fn get_stripe_event_type(event_type: api_models::enums::EventType) -> &'static str { match event_type { api_models::enums::EventType::PaymentSucceeded => "payment_intent.succeeded", api_models::enums::EventType::PaymentFailed => "payment_intent.payment_failed", api_models::enums::EventType::PaymentProcessing | api_models::enums::EventType::PaymentPartiallyAuthorized => "payment_intent.processing", api_models::enums::EventType::PaymentCancelled | api_models::enums::EventType::PaymentCancelledPostCapture | api_models::enums::EventType::PaymentExpired => "payment_intent.canceled", // the below are not really stripe compatible because stripe doesn't provide this api_models::enums::EventType::ActionRequired => "action.required", api_models::enums::EventType::RefundSucceeded => "refund.succeeded", api_models::enums::EventType::RefundFailed => "refund.failed", api_models::enums::EventType::DisputeOpened => "dispute.failed", api_models::enums::EventType::DisputeExpired => "dispute.expired", api_models::enums::EventType::DisputeAccepted => "dispute.accepted", api_models::enums::EventType::DisputeCancelled => "dispute.cancelled", api_models::enums::EventType::DisputeChallenged => "dispute.challenged", api_models::enums::EventType::DisputeWon => "dispute.won", api_models::enums::EventType::DisputeLost => "dispute.lost", api_models::enums::EventType::MandateActive => "mandate.active", api_models::enums::EventType::MandateRevoked => "mandate.revoked", // as per this doc https://stripe.com/docs/api/events/types#event_types-payment_intent.amount_capturable_updated api_models::enums::EventType::PaymentAuthorized => { "payment_intent.amount_capturable_updated" } // stripe treats partially captured payments as succeeded. api_models::enums::EventType::PaymentCaptured => "payment_intent.succeeded", api_models::enums::EventType::PayoutSuccess => "payout.paid", api_models::enums::EventType::PayoutFailed => "payout.failed", api_models::enums::EventType::PayoutInitiated => "payout.created", api_models::enums::EventType::PayoutCancelled => "payout.canceled", api_models::enums::EventType::PayoutProcessing => "payout.created", api_models::enums::EventType::PayoutExpired => "payout.failed", api_models::enums::EventType::PayoutReversed => "payout.reconciliation_completed", } } impl From<api::OutgoingWebhook> for StripeOutgoingWebhook { fn from(value: api::OutgoingWebhook) -> Self { Self { id: value.event_id, stype: get_stripe_event_type(value.event_type), data: StripeWebhookObject::from(value.content), object: "event", // put this conversion it into a function created: u64::try_from(value.timestamp.assume_utc().unix_timestamp()).unwrap_or_else( |error| { logger::error!( %error, "incorrect value for `webhook.timestamp` provided {}", value.timestamp ); // Current timestamp converted to Unix timestamp should have a positive value // for many years to come u64::try_from(date_time::now().assume_utc().unix_timestamp()) .unwrap_or_default() }, ), } } } impl From<api::OutgoingWebhookContent> for StripeWebhookObject { fn from(value: api::OutgoingWebhookContent) -> Self { match value { api::OutgoingWebhookContent::PaymentDetails(payment) => { Self::PaymentIntent(Box::new((*payment).into())) } api::OutgoingWebhookContent::RefundDetails(refund) => Self::Refund((*refund).into()), api::OutgoingWebhookContent::DisputeDetails(dispute) => { Self::Dispute((*dispute).into()) } api::OutgoingWebhookContent::MandateDetails(mandate) => { Self::Mandate((*mandate).into()) } #[cfg(feature = "payouts")] api::OutgoingWebhookContent::PayoutDetails(payout) => Self::Payout((*payout).into()), } } }
{ "crate": "router", "file": "crates/router/src/compatibility/stripe/webhooks.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 4, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_router_7394797703811344986
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/compatibility/stripe/customers/types.rs // Contains: 9 structs, 0 enums use std::{convert::From, default::Default}; #[cfg(feature = "v1")] use api_models::payment_methods as api_types; use api_models::payments; #[cfg(feature = "v1")] use common_utils::{crypto::Encryptable, date_time}; use common_utils::{ id_type, pii::{self, Email}, types::Description, }; use serde::{Deserialize, Serialize}; #[cfg(feature = "v1")] use crate::logger; use crate::types::{api, api::enums as api_enums}; #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct Shipping { pub address: StripeAddressDetails, pub name: Option<masking::Secret<String>>, pub carrier: Option<String>, pub phone: Option<masking::Secret<String>>, pub tracking_number: Option<masking::Secret<String>>, } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct StripeAddressDetails { pub city: Option<String>, pub country: Option<api_enums::CountryAlpha2>, pub line1: Option<masking::Secret<String>>, pub line2: Option<masking::Secret<String>>, pub postal_code: Option<masking::Secret<String>>, pub state: Option<masking::Secret<String>>, } #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct CreateCustomerRequest { pub email: Option<Email>, pub invoice_prefix: Option<String>, pub name: Option<masking::Secret<String>>, pub phone: Option<masking::Secret<String>>, pub address: Option<StripeAddressDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub description: Option<Description>, pub shipping: Option<Shipping>, pub payment_method: Option<String>, // not used pub balance: Option<i64>, // not used pub cash_balance: Option<pii::SecretSerdeValue>, // not used pub coupon: Option<String>, // not used pub invoice_settings: Option<pii::SecretSerdeValue>, // not used pub next_invoice_sequence: Option<String>, // not used pub preferred_locales: Option<String>, // not used pub promotion_code: Option<String>, // not used pub source: Option<String>, // not used pub tax: Option<pii::SecretSerdeValue>, // not used pub tax_exempt: Option<String>, // not used pub tax_id_data: Option<String>, // not used pub test_clock: Option<String>, // not used } #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct CustomerUpdateRequest { pub description: Option<Description>, pub email: Option<Email>, pub phone: Option<masking::Secret<String, masking::WithType>>, pub name: Option<masking::Secret<String>>, pub address: Option<StripeAddressDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub shipping: Option<Shipping>, pub payment_method: Option<String>, // not used pub balance: Option<i64>, // not used pub cash_balance: Option<pii::SecretSerdeValue>, // not used pub coupon: Option<String>, // not used pub default_source: Option<String>, // not used pub invoice_settings: Option<pii::SecretSerdeValue>, // not used pub next_invoice_sequence: Option<String>, // not used pub preferred_locales: Option<String>, // not used pub promotion_code: Option<String>, // not used pub source: Option<String>, // not used pub tax: Option<pii::SecretSerdeValue>, // not used pub tax_exempt: Option<String>, // not used } #[derive(Serialize, PartialEq, Eq)] pub struct CreateCustomerResponse { pub id: id_type::CustomerId, pub object: String, pub created: u64, pub description: Option<Description>, pub email: Option<Email>, pub metadata: Option<pii::SecretSerdeValue>, pub name: Option<masking::Secret<String>>, pub phone: Option<masking::Secret<String, masking::WithType>>, } pub type CustomerRetrieveResponse = CreateCustomerResponse; pub type CustomerUpdateResponse = CreateCustomerResponse; #[derive(Serialize, PartialEq, Eq)] pub struct CustomerDeleteResponse { pub id: id_type::CustomerId, pub deleted: bool, } impl From<StripeAddressDetails> for payments::AddressDetails { fn from(address: StripeAddressDetails) -> Self { Self { city: address.city, country: address.country, line1: address.line1, line2: address.line2, zip: address.postal_code, state: address.state, first_name: None, line3: None, last_name: None, origin_zip: None, } } } #[cfg(feature = "v1")] impl From<CreateCustomerRequest> for api::CustomerRequest { fn from(req: CreateCustomerRequest) -> Self { Self { customer_id: Some(common_utils::generate_customer_id_of_default_length()), name: req.name, phone: req.phone, email: req.email, description: req.description, metadata: req.metadata, address: req.address.map(|s| s.into()), ..Default::default() } } } #[cfg(feature = "v1")] impl From<CustomerUpdateRequest> for api::CustomerUpdateRequest { fn from(req: CustomerUpdateRequest) -> Self { Self { name: req.name, phone: req.phone, email: req.email, description: req.description, metadata: req.metadata, address: req.address.map(|s| s.into()), ..Default::default() } } } #[cfg(feature = "v1")] impl From<api::CustomerResponse> for CreateCustomerResponse { fn from(cust: api::CustomerResponse) -> Self { let cust = cust.into_inner(); Self { id: cust.customer_id, object: "customer".to_owned(), created: u64::try_from(cust.created_at.assume_utc().unix_timestamp()).unwrap_or_else( |error| { logger::error!( %error, "incorrect value for `customer.created_at` provided {}", cust.created_at ); // Current timestamp converted to Unix timestamp should have a positive value // for many years to come u64::try_from(date_time::now().assume_utc().unix_timestamp()) .unwrap_or_default() }, ), description: cust.description, email: cust.email.map(|inner| inner.into()), metadata: cust.metadata, name: cust.name.map(Encryptable::into_inner), phone: cust.phone.map(Encryptable::into_inner), } } } #[cfg(feature = "v1")] impl From<api::CustomerDeleteResponse> for CustomerDeleteResponse { fn from(cust: api::CustomerDeleteResponse) -> Self { Self { id: cust.customer_id, deleted: cust.customer_deleted, } } } #[derive(Default, Serialize, PartialEq, Eq)] pub struct CustomerPaymentMethodListResponse { pub object: &'static str, pub data: Vec<PaymentMethodData>, } #[derive(Default, Serialize, PartialEq, Eq)] pub struct PaymentMethodData { pub id: Option<String>, pub object: &'static str, pub card: Option<CardDetails>, pub created: Option<time::PrimitiveDateTime>, } #[derive(Default, Serialize, PartialEq, Eq)] pub struct CardDetails { pub country: Option<String>, pub last4: Option<String>, pub exp_month: Option<masking::Secret<String>>, pub exp_year: Option<masking::Secret<String>>, pub fingerprint: Option<masking::Secret<String>>, } #[cfg(feature = "v1")] impl From<api::CustomerPaymentMethodsListResponse> for CustomerPaymentMethodListResponse { fn from(item: api::CustomerPaymentMethodsListResponse) -> Self { let customer_payment_methods = item.customer_payment_methods; let data = customer_payment_methods .into_iter() .map(From::from) .collect(); Self { object: "list", data, } } } #[cfg(feature = "v1")] impl From<api_types::CustomerPaymentMethod> for PaymentMethodData { fn from(item: api_types::CustomerPaymentMethod) -> Self { let card = item.card.map(From::from); Self { id: Some(item.payment_token), object: "payment_method", card, created: item.created, } } } #[cfg(feature = "v1")] impl From<api_types::CardDetailFromLocker> for CardDetails { fn from(item: api_types::CardDetailFromLocker) -> Self { Self { country: item.issuer_country, last4: item.last4_digits, exp_month: item.expiry_month, exp_year: item.expiry_year, fingerprint: item.card_fingerprint, } } }
{ "crate": "router", "file": "crates/router/src/compatibility/stripe/customers/types.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 9, "num_tables": null, "score": null, "total_crates": null }
file_router_7592355824429817966
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/compatibility/stripe/payment_intents/types.rs // Contains: 20 structs, 10 enums use std::str::FromStr; use api_models::payments; use common_types::payments as common_payments_types; use common_utils::{ crypto::Encryptable, date_time, ext_traits::StringExt, id_type, pii::{IpAddress, SecretSerdeValue, UpiVpaMaskingStrategy}, types::MinorUnit, }; use error_stack::ResultExt; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{ compatibility::stripe::refunds::types as stripe_refunds, connector::utils::AddressData, consts, core::errors, pii::{Email, PeekInterface}, types::{ api::{admin, enums as api_enums}, transformers::{ForeignFrom, ForeignTryFrom}, }, }; #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct StripeBillingDetails { pub address: Option<AddressDetails>, pub email: Option<Email>, pub name: Option<String>, pub phone: Option<masking::Secret<String>>, } impl From<StripeBillingDetails> for payments::Address { fn from(details: StripeBillingDetails) -> Self { Self { phone: Some(payments::PhoneDetails { number: details.phone, country_code: details.address.as_ref().and_then(|address| { address.country.as_ref().map(|country| country.to_string()) }), }), email: details.email, address: details.address.map(|address| payments::AddressDetails { city: address.city, country: address.country, line1: address.line1, line2: address.line2, zip: address.postal_code, state: address.state, first_name: None, line3: None, last_name: None, origin_zip: None, }), } } } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct StripeCard { pub number: cards::CardNumber, pub exp_month: masking::Secret<String>, pub exp_year: masking::Secret<String>, pub cvc: masking::Secret<String>, pub holder_name: Option<masking::Secret<String>>, } // ApplePay wallet param is not available in stripe Docs #[derive(Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] #[serde(rename_all = "snake_case")] pub enum StripeWallet { ApplePay(payments::ApplePayWalletData), } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct StripeUpi { pub vpa_id: masking::Secret<String, UpiVpaMaskingStrategy>, } #[derive(Debug, Default, Serialize, PartialEq, Eq, Deserialize, Clone)] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodType { #[default] Card, Wallet, Upi, BankRedirect, RealTimePayment, } impl From<StripePaymentMethodType> for api_enums::PaymentMethod { fn from(item: StripePaymentMethodType) -> Self { match item { StripePaymentMethodType::Card => Self::Card, StripePaymentMethodType::Wallet => Self::Wallet, StripePaymentMethodType::Upi => Self::Upi, StripePaymentMethodType::BankRedirect => Self::BankRedirect, StripePaymentMethodType::RealTimePayment => Self::RealTimePayment, } } } #[derive(Default, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct StripePaymentMethodData { #[serde(rename = "type")] pub stype: StripePaymentMethodType, pub billing_details: Option<StripeBillingDetails>, #[serde(flatten)] pub payment_method_details: Option<StripePaymentMethodDetails>, // enum pub metadata: Option<SecretSerdeValue>, } #[derive(PartialEq, Eq, Deserialize, Clone, Debug)] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodDetails { Card(StripeCard), Wallet(StripeWallet), Upi(StripeUpi), } impl From<StripeCard> for payments::Card { fn from(card: StripeCard) -> Self { Self { card_number: card.number, card_exp_month: card.exp_month, card_exp_year: card.exp_year, card_holder_name: card.holder_name, card_cvc: card.cvc, card_issuer: None, card_network: None, bank_code: None, card_issuing_country: None, card_type: None, nick_name: None, } } } impl From<StripeWallet> for payments::WalletData { fn from(wallet: StripeWallet) -> Self { match wallet { StripeWallet::ApplePay(data) => Self::ApplePay(data), } } } impl From<StripeUpi> for payments::UpiData { fn from(upi_data: StripeUpi) -> Self { Self::UpiCollect(payments::UpiCollectData { vpa_id: Some(upi_data.vpa_id), }) } } impl From<StripePaymentMethodDetails> for payments::PaymentMethodData { fn from(item: StripePaymentMethodDetails) -> Self { match item { StripePaymentMethodDetails::Card(card) => Self::Card(payments::Card::from(card)), StripePaymentMethodDetails::Wallet(wallet) => { Self::Wallet(payments::WalletData::from(wallet)) } StripePaymentMethodDetails::Upi(upi) => Self::Upi(payments::UpiData::from(upi)), } } } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct Shipping { pub address: AddressDetails, pub name: Option<masking::Secret<String>>, pub carrier: Option<String>, pub phone: Option<masking::Secret<String>>, pub tracking_number: Option<masking::Secret<String>>, } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct AddressDetails { pub city: Option<String>, pub country: Option<api_enums::CountryAlpha2>, pub line1: Option<masking::Secret<String>>, pub line2: Option<masking::Secret<String>>, pub postal_code: Option<masking::Secret<String>>, pub state: Option<masking::Secret<String>>, } impl From<Shipping> for payments::Address { fn from(details: Shipping) -> Self { Self { phone: Some(payments::PhoneDetails { number: details.phone, country_code: details.address.country.map(|country| country.to_string()), }), email: None, address: Some(payments::AddressDetails { city: details.address.city, country: details.address.country, line1: details.address.line1, line2: details.address.line2, zip: details.address.postal_code, state: details.address.state, first_name: details.name, line3: None, last_name: None, origin_zip: None, }), } } } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct MandateData { pub customer_acceptance: CustomerAcceptance, pub mandate_type: Option<StripeMandateType>, pub amount: Option<i64>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub start_date: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub end_date: Option<PrimitiveDateTime>, } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct CustomerAcceptance { #[serde(rename = "type")] pub acceptance_type: Option<AcceptanceType>, pub accepted_at: Option<PrimitiveDateTime>, pub online: Option<OnlineMandate>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone)] #[serde(rename_all = "lowercase")] pub enum AcceptanceType { Online, #[default] Offline, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct OnlineMandate { pub ip_address: masking::Secret<String, IpAddress>, pub user_agent: String, } #[derive(Deserialize, Clone, Debug)] pub struct StripePaymentIntentRequest { pub id: Option<id_type::PaymentId>, pub amount: Option<i64>, // amount in cents, hence passed as integer pub connector: Option<Vec<api_enums::RoutableConnectors>>, pub currency: Option<String>, #[serde(rename = "amount_to_capture")] pub amount_capturable: Option<i64>, pub confirm: Option<bool>, pub capture_method: Option<api_enums::CaptureMethod>, pub customer: Option<id_type::CustomerId>, pub description: Option<String>, pub payment_method_data: Option<StripePaymentMethodData>, pub receipt_email: Option<Email>, pub return_url: Option<url::Url>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub shipping: Option<Shipping>, pub statement_descriptor: Option<String>, pub statement_descriptor_suffix: Option<String>, pub metadata: Option<serde_json::Value>, pub client_secret: Option<masking::Secret<String>>, pub payment_method_options: Option<StripePaymentMethodOptions>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, pub mandate: Option<String>, pub off_session: Option<bool>, pub payment_method_types: Option<api_enums::PaymentMethodType>, pub receipt_ipaddress: Option<String>, pub user_agent: Option<String>, pub mandate_data: Option<MandateData>, pub automatic_payment_methods: Option<SecretSerdeValue>, // not used pub payment_method: Option<String>, // not used pub confirmation_method: Option<String>, // not used pub error_on_requires_action: Option<String>, // not used pub radar_options: Option<SecretSerdeValue>, // not used pub connector_metadata: Option<payments::ConnectorMetadata>, } impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripePaymentIntentRequest) -> errors::RouterResult<Self> { let routable_connector: Option<api_enums::RoutableConnectors> = item.connector.and_then(|v| v.into_iter().next()); let routing = routable_connector .map(|connector| { api_models::routing::StaticRoutingAlgorithm::Single(Box::new( api_models::routing::RoutableConnectorChoice { choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, connector, merchant_connector_id: None, }, )) }) .map(|r| { serde_json::to_value(r) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("converting to routing failed") }) .transpose()?; let ip_address = item .receipt_ipaddress .map(|ip| std::net::IpAddr::from_str(ip.as_str())) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "receipt_ipaddress".to_string(), expected_format: "127.0.0.1".to_string(), })?; let amount = item.amount.map(|amount| MinorUnit::new(amount).into()); let payment_method_data = item.payment_method_data.as_ref().map(|pmd| { let billing = pmd.billing_details.clone().map(payments::Address::from); let payment_method_data = match pmd.payment_method_details.as_ref() { Some(spmd) => Some(payments::PaymentMethodData::from(spmd.to_owned())), None => get_pmd_based_on_payment_method_type( item.payment_method_types, billing.clone().map(From::from), ), }; payments::PaymentMethodDataRequest { payment_method_data, billing, } }); let request = Ok(Self { payment_id: item.id.map(payments::PaymentIdType::PaymentIntentId), amount, currency: item .currency .as_ref() .map(|c| c.to_uppercase().parse_enum("currency")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "currency", })?, capture_method: item.capture_method, amount_to_capture: item.amount_capturable.map(MinorUnit::new), confirm: item.confirm, customer_id: item.customer, email: item.receipt_email, phone: item.shipping.as_ref().and_then(|s| s.phone.clone()), description: item.description, return_url: item.return_url, payment_method_data, payment_method: item .payment_method_data .as_ref() .map(|pmd| api_enums::PaymentMethod::from(pmd.stype.to_owned())), shipping: item .shipping .as_ref() .map(|s| payments::Address::from(s.to_owned())), billing: item .payment_method_data .and_then(|pmd| pmd.billing_details.map(payments::Address::from)), statement_descriptor_name: item.statement_descriptor, statement_descriptor_suffix: item.statement_descriptor_suffix, metadata: item.metadata, client_secret: item.client_secret.map(|s| s.peek().clone()), authentication_type: match item.payment_method_options { Some(pmo) => { let StripePaymentMethodOptions::Card { request_three_d_secure, }: StripePaymentMethodOptions = pmo; Some(api_enums::AuthenticationType::foreign_from( request_three_d_secure, )) } None => None, }, mandate_data: ForeignTryFrom::foreign_try_from(( item.mandate_data, item.currency.to_owned(), ))?, merchant_connector_details: item.merchant_connector_details, setup_future_usage: item.setup_future_usage, mandate_id: item.mandate, off_session: item.off_session, payment_method_type: item.payment_method_types, routing, browser_info: Some( serde_json::to_value(crate::types::BrowserInformation { ip_address, user_agent: item.user_agent, ..Default::default() }) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("convert to browser info failed")?, ), connector_metadata: item.connector_metadata, ..Self::default() }); request } } #[derive(Clone, Default, Eq, PartialEq, Serialize, Deserialize, Debug)] #[serde(rename_all = "snake_case")] pub enum StripePaymentStatus { Succeeded, Canceled, #[default] Processing, RequiresAction, RequiresPaymentMethod, RequiresConfirmation, RequiresCapture, } impl From<api_enums::IntentStatus> for StripePaymentStatus { fn from(item: api_enums::IntentStatus) -> Self { match item { api_enums::IntentStatus::Succeeded | api_enums::IntentStatus::PartiallyCaptured => { Self::Succeeded } api_enums::IntentStatus::Failed | api_enums::IntentStatus::Expired => Self::Canceled, api_enums::IntentStatus::Processing => Self::Processing, api_enums::IntentStatus::RequiresCustomerAction | api_enums::IntentStatus::RequiresMerchantAction | api_enums::IntentStatus::Conflicted => Self::RequiresAction, api_enums::IntentStatus::RequiresPaymentMethod => Self::RequiresPaymentMethod, api_enums::IntentStatus::RequiresConfirmation => Self::RequiresConfirmation, api_enums::IntentStatus::RequiresCapture | api_enums::IntentStatus::PartiallyCapturedAndCapturable | api_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => { Self::RequiresCapture } api_enums::IntentStatus::Cancelled | api_enums::IntentStatus::CancelledPostCapture => { Self::Canceled } } } } #[derive(Debug, Serialize, Deserialize, Copy, Clone, strum::Display)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CancellationReason { Duplicate, Fraudulent, RequestedByCustomer, Abandoned, } #[derive(Debug, Deserialize, Serialize, Copy, Clone)] pub struct StripePaymentCancelRequest { cancellation_reason: Option<CancellationReason>, } impl From<StripePaymentCancelRequest> for payments::PaymentsCancelRequest { fn from(item: StripePaymentCancelRequest) -> Self { Self { cancellation_reason: item.cancellation_reason.map(|c| c.to_string()), ..Self::default() } } } #[derive(Default, Eq, PartialEq, Serialize, Debug)] pub struct StripePaymentIntentResponse { pub id: id_type::PaymentId, pub object: &'static str, pub amount: i64, pub amount_received: Option<i64>, pub amount_capturable: i64, pub currency: String, pub status: StripePaymentStatus, pub client_secret: Option<masking::Secret<String>>, pub created: Option<i64>, pub customer: Option<id_type::CustomerId>, pub refunds: Option<Vec<stripe_refunds::StripeRefundResponse>>, pub mandate: Option<String>, pub metadata: Option<serde_json::Value>, pub charges: Charges, pub connector: Option<String>, pub description: Option<String>, pub mandate_data: Option<payments::MandateData>, pub setup_future_usage: Option<api_models::enums::FutureUsage>, pub off_session: Option<bool>, pub authentication_type: Option<api_models::enums::AuthenticationType>, pub next_action: Option<StripeNextAction>, pub cancellation_reason: Option<String>, pub payment_method: Option<api_models::enums::PaymentMethod>, pub payment_method_data: Option<payments::PaymentMethodDataResponse>, pub shipping: Option<payments::Address>, pub billing: Option<payments::Address>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub capture_on: Option<PrimitiveDateTime>, pub payment_token: Option<String>, pub email: Option<Email>, pub phone: Option<masking::Secret<String>>, pub statement_descriptor_suffix: Option<String>, pub statement_descriptor_name: Option<String>, pub capture_method: Option<api_models::enums::CaptureMethod>, pub name: Option<masking::Secret<String>>, pub last_payment_error: Option<LastPaymentError>, pub connector_transaction_id: Option<String>, } #[derive(Default, Eq, PartialEq, Serialize, Debug)] pub struct LastPaymentError { charge: Option<String>, code: Option<String>, decline_code: Option<String>, message: String, param: Option<String>, payment_method: StripePaymentMethod, #[serde(rename = "type")] error_type: String, } impl From<payments::PaymentsResponse> for StripePaymentIntentResponse { fn from(resp: payments::PaymentsResponse) -> Self { Self { object: "payment_intent", id: resp.payment_id, status: StripePaymentStatus::from(resp.status), amount: resp.amount.get_amount_as_i64(), amount_capturable: resp.amount_capturable.get_amount_as_i64(), amount_received: resp.amount_received.map(|amt| amt.get_amount_as_i64()), connector: resp.connector, client_secret: resp.client_secret, created: resp.created.map(|t| t.assume_utc().unix_timestamp()), currency: resp.currency.to_lowercase(), customer: resp.customer_id, description: resp.description, refunds: resp .refunds .map(|a| a.into_iter().map(Into::into).collect()), mandate: resp.mandate_id, mandate_data: resp.mandate_data, setup_future_usage: resp.setup_future_usage, off_session: resp.off_session, capture_on: resp.capture_on, capture_method: resp.capture_method, payment_method: resp.payment_method, payment_method_data: resp .payment_method_data .and_then(|pmd| pmd.payment_method_data), payment_token: resp.payment_token, shipping: resp.shipping, billing: resp.billing, email: resp.email.map(|inner| inner.into()), name: resp.name.map(Encryptable::into_inner), phone: resp.phone.map(Encryptable::into_inner), authentication_type: resp.authentication_type, statement_descriptor_name: resp.statement_descriptor_name, statement_descriptor_suffix: resp.statement_descriptor_suffix, next_action: into_stripe_next_action(resp.next_action, resp.return_url), cancellation_reason: resp.cancellation_reason, metadata: resp.metadata, charges: Charges::new(), last_payment_error: resp.error_code.map(|code| LastPaymentError { charge: None, code: Some(code.to_owned()), decline_code: None, message: resp .error_message .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), param: None, payment_method: StripePaymentMethod { payment_method_id: "place_holder_id".to_string(), object: "payment_method", card: None, created: u64::try_from(date_time::now().assume_utc().unix_timestamp()) .unwrap_or_default(), method_type: "card".to_string(), livemode: false, }, error_type: code, }), connector_transaction_id: resp.connector_transaction_id, } } } #[derive(Default, Eq, PartialEq, Serialize, Debug)] pub struct StripePaymentMethod { #[serde(rename = "id")] payment_method_id: String, object: &'static str, card: Option<StripeCard>, created: u64, #[serde(rename = "type")] method_type: String, livemode: bool, } #[derive(Default, Eq, PartialEq, Serialize, Debug)] pub struct Charges { object: &'static str, data: Vec<String>, has_more: bool, total_count: i32, url: String, } impl Charges { pub fn new() -> Self { Self { object: "list", data: vec![], has_more: false, total_count: 0, url: "http://placeholder".to_string(), } } } #[derive(Clone, Debug, serde::Deserialize)] #[serde(deny_unknown_fields)] pub struct StripePaymentListConstraints { pub customer: Option<id_type::CustomerId>, pub starting_after: Option<id_type::PaymentId>, pub ending_before: Option<id_type::PaymentId>, #[serde(default = "default_limit")] pub limit: u32, pub created: Option<i64>, #[serde(rename = "created[lt]")] pub created_lt: Option<i64>, #[serde(rename = "created[gt]")] pub created_gt: Option<i64>, #[serde(rename = "created[lte]")] pub created_lte: Option<i64>, #[serde(rename = "created[gte]")] pub created_gte: Option<i64>, } fn default_limit() -> u32 { 10 } impl TryFrom<StripePaymentListConstraints> for payments::PaymentListConstraints { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripePaymentListConstraints) -> Result<Self, Self::Error> { Ok(Self { customer_id: item.customer, starting_after: item.starting_after, ending_before: item.ending_before, limit: item.limit, created: from_timestamp_to_datetime(item.created)?, created_lt: from_timestamp_to_datetime(item.created_lt)?, created_gt: from_timestamp_to_datetime(item.created_gt)?, created_lte: from_timestamp_to_datetime(item.created_lte)?, created_gte: from_timestamp_to_datetime(item.created_gte)?, }) } } #[inline] fn from_timestamp_to_datetime( time: Option<i64>, ) -> Result<Option<PrimitiveDateTime>, errors::ApiErrorResponse> { if let Some(time) = time { let time = time::OffsetDateTime::from_unix_timestamp(time).map_err(|_| { errors::ApiErrorResponse::InvalidRequestData { message: "Error while converting timestamp".to_string(), } })?; Ok(Some(PrimitiveDateTime::new(time.date(), time.time()))) } else { Ok(None) } } #[derive(Default, Eq, PartialEq, Serialize)] pub struct StripePaymentIntentListResponse { pub object: String, pub url: String, pub has_more: bool, pub data: Vec<StripePaymentIntentResponse>, } impl From<payments::PaymentListResponse> for StripePaymentIntentListResponse { fn from(it: payments::PaymentListResponse) -> Self { Self { object: "list".to_string(), url: "/v1/payment_intents".to_string(), has_more: false, data: it.data.into_iter().map(Into::into).collect(), } } } #[derive(PartialEq, Eq, Deserialize, Clone, Debug)] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodOptions { Card { request_three_d_secure: Option<Request3DS>, }, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(rename_all = "snake_case")] pub enum StripeMandateType { SingleUse, MultiUse, } #[derive(PartialEq, Eq, Clone, Default, Deserialize, Serialize, Debug)] pub struct MandateOption { #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub accepted_at: Option<PrimitiveDateTime>, pub user_agent: Option<String>, pub ip_address: Option<masking::Secret<String, IpAddress>>, pub mandate_type: Option<StripeMandateType>, pub amount: Option<i64>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub start_date: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub end_date: Option<PrimitiveDateTime>, } impl ForeignTryFrom<(Option<MandateData>, Option<String>)> for Option<payments::MandateData> { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( (mandate_data, currency): (Option<MandateData>, Option<String>), ) -> errors::RouterResult<Self> { let currency = currency .ok_or( errors::ApiErrorResponse::MissingRequiredField { field_name: "currency", } .into(), ) .and_then(|c| { c.to_uppercase().parse_enum("currency").change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "currency", }, ) })?; let mandate_data = mandate_data.map(|mandate| payments::MandateData { mandate_type: match mandate.mandate_type { Some(item) => match item { StripeMandateType::SingleUse => Some(payments::MandateType::SingleUse( payments::MandateAmountData { amount: MinorUnit::new(mandate.amount.unwrap_or_default()), currency, start_date: mandate.start_date, end_date: mandate.end_date, metadata: None, }, )), StripeMandateType::MultiUse => Some(payments::MandateType::MultiUse(Some( payments::MandateAmountData { amount: MinorUnit::new(mandate.amount.unwrap_or_default()), currency, start_date: mandate.start_date, end_date: mandate.end_date, metadata: None, }, ))), }, None => Some(payments::MandateType::MultiUse(Some( payments::MandateAmountData { amount: MinorUnit::new(mandate.amount.unwrap_or_default()), currency, start_date: mandate.start_date, end_date: mandate.end_date, metadata: None, }, ))), }, 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| { common_payments_types::OnlineMandate { ip_address: Some(online.ip_address), user_agent: online.user_agent, } }), }), update_mandate_id: None, }); Ok(mandate_data) } } #[derive(Default, Eq, PartialEq, Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "snake_case")] pub enum Request3DS { #[default] Automatic, Any, } impl ForeignFrom<Option<Request3DS>> for api_models::enums::AuthenticationType { fn foreign_from(item: Option<Request3DS>) -> Self { match item.unwrap_or_default() { Request3DS::Automatic => Self::NoThreeDs, Request3DS::Any => Self::ThreeDs, } } } #[derive(Default, Eq, PartialEq, Serialize, Debug)] pub struct RedirectUrl { pub return_url: Option<String>, pub url: Option<String>, } #[derive(Eq, PartialEq, serde::Serialize, Debug)] #[serde(tag = "type", rename_all = "snake_case")] pub enum StripeNextAction { RedirectToUrl { redirect_to_url: RedirectUrl, }, DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: payments::BankTransferNextStepsData, }, ThirdPartySdkSessionToken { session_token: Option<payments::SessionToken>, }, QrCodeInformation { image_data_url: Option<url::Url>, display_to_timestamp: Option<i64>, qr_code_url: Option<url::Url>, border_color: Option<String>, display_text: Option<String>, }, FetchQrCodeInformation { qr_code_fetch_url: url::Url, }, DisplayVoucherInformation { voucher_details: payments::VoucherNextStepData, }, WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, poll_config: Option<payments::PollConfig>, }, InvokeSdkClient { next_action_data: payments::SdkNextActionData, }, CollectOtp { consent_data_required: payments::MobilePaymentConsent, }, InvokeHiddenIframe { iframe_data: payments::IframeData, }, SdkUpiIntentInformation { sdk_uri: url::Url, }, } pub(crate) fn into_stripe_next_action( next_action: Option<payments::NextActionData>, return_url: Option<String>, ) -> Option<StripeNextAction> { next_action.map(|next_action_data| match next_action_data { payments::NextActionData::RedirectToUrl { redirect_to_url } => { StripeNextAction::RedirectToUrl { redirect_to_url: RedirectUrl { return_url, url: Some(redirect_to_url), }, } } payments::NextActionData::RedirectInsidePopup { popup_url, .. } => { StripeNextAction::RedirectToUrl { redirect_to_url: RedirectUrl { return_url, url: Some(popup_url), }, } } payments::NextActionData::DisplayBankTransferInformation { bank_transfer_steps_and_charges_details, } => StripeNextAction::DisplayBankTransferInformation { bank_transfer_steps_and_charges_details, }, payments::NextActionData::ThirdPartySdkSessionToken { session_token } => { StripeNextAction::ThirdPartySdkSessionToken { session_token } } payments::NextActionData::QrCodeInformation { image_data_url, display_to_timestamp, qr_code_url, border_color, display_text, } => StripeNextAction::QrCodeInformation { image_data_url, display_to_timestamp, qr_code_url, border_color, display_text, }, payments::NextActionData::FetchQrCodeInformation { qr_code_fetch_url } => { StripeNextAction::FetchQrCodeInformation { qr_code_fetch_url } } payments::NextActionData::DisplayVoucherInformation { voucher_details } => { StripeNextAction::DisplayVoucherInformation { voucher_details } } payments::NextActionData::WaitScreenInformation { display_from_timestamp, display_to_timestamp, poll_config: _, } => StripeNextAction::WaitScreenInformation { display_from_timestamp, display_to_timestamp, poll_config: None, }, payments::NextActionData::ThreeDsInvoke { .. } => StripeNextAction::RedirectToUrl { redirect_to_url: RedirectUrl { return_url: None, url: None, }, }, payments::NextActionData::InvokeSdkClient { next_action_data } => { StripeNextAction::InvokeSdkClient { next_action_data } } payments::NextActionData::CollectOtp { consent_data_required, } => StripeNextAction::CollectOtp { consent_data_required, }, payments::NextActionData::InvokeHiddenIframe { iframe_data } => { StripeNextAction::InvokeHiddenIframe { iframe_data } } payments::NextActionData::SdkUpiIntentInformation { sdk_uri } => { StripeNextAction::SdkUpiIntentInformation { sdk_uri } } }) } #[derive(Deserialize, Clone)] pub struct StripePaymentRetrieveBody { pub client_secret: Option<String>, } //To handle payment types that have empty payment method data fn get_pmd_based_on_payment_method_type( payment_method_type: Option<api_enums::PaymentMethodType>, billing_details: Option<hyperswitch_domain_models::address::Address>, ) -> Option<payments::PaymentMethodData> { match payment_method_type { Some(api_enums::PaymentMethodType::UpiIntent) => Some(payments::PaymentMethodData::Upi( payments::UpiData::UpiIntent(payments::UpiIntentData {}), )), Some(api_enums::PaymentMethodType::Fps) => { Some(payments::PaymentMethodData::RealTimePayment(Box::new( payments::RealTimePaymentData::Fps {}, ))) } Some(api_enums::PaymentMethodType::DuitNow) => { Some(payments::PaymentMethodData::RealTimePayment(Box::new( payments::RealTimePaymentData::DuitNow {}, ))) } Some(api_enums::PaymentMethodType::PromptPay) => { Some(payments::PaymentMethodData::RealTimePayment(Box::new( payments::RealTimePaymentData::PromptPay {}, ))) } Some(api_enums::PaymentMethodType::VietQr) => { Some(payments::PaymentMethodData::RealTimePayment(Box::new( payments::RealTimePaymentData::VietQr {}, ))) } Some(api_enums::PaymentMethodType::Ideal) => Some( payments::PaymentMethodData::BankRedirect(payments::BankRedirectData::Ideal { billing_details: billing_details.as_ref().map(|billing_data| { payments::BankRedirectBilling { billing_name: billing_data.get_optional_full_name(), email: billing_data.email.clone(), } }), bank_name: None, country: billing_details .as_ref() .and_then(|billing_data| billing_data.get_optional_country()), }), ), Some(api_enums::PaymentMethodType::LocalBankRedirect) => { Some(payments::PaymentMethodData::BankRedirect( payments::BankRedirectData::LocalBankRedirect {}, )) } _ => None, } }
{ "crate": "router", "file": "crates/router/src/compatibility/stripe/payment_intents/types.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 10, "num_structs": 20, "num_tables": null, "score": null, "total_crates": null }
file_router_2464384353903742856
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/compatibility/stripe/setup_intents/types.rs // Contains: 11 structs, 6 enums use std::str::FromStr; use api_models::payments; use common_utils::{date_time, ext_traits::StringExt, id_type, pii as secret}; use error_stack::ResultExt; use router_env::logger; use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::{ compatibility::stripe::{ payment_intents::types as payment_intent, refunds::types as stripe_refunds, }, consts, core::errors, pii::{self, PeekInterface}, types::{ api::{self as api_types, admin, enums as api_enums}, transformers::{ForeignFrom, ForeignTryFrom}, }, utils::OptionExt, }; #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct StripeBillingDetails { pub address: Option<payments::AddressDetails>, pub email: Option<pii::Email>, pub name: Option<String>, pub phone: Option<pii::Secret<String>>, } impl From<StripeBillingDetails> for payments::Address { fn from(details: StripeBillingDetails) -> Self { Self { address: details.address, phone: Some(payments::PhoneDetails { number: details.phone, country_code: None, }), email: details.email, } } } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct StripeCard { pub number: cards::CardNumber, pub exp_month: pii::Secret<String>, pub exp_year: pii::Secret<String>, pub cvc: pii::Secret<String>, } // ApplePay wallet param is not available in stripe Docs #[derive(Serialize, PartialEq, Eq, Deserialize, Clone)] #[serde(rename_all = "snake_case")] pub enum StripeWallet { ApplePay(payments::ApplePayWalletData), } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodType { #[default] Card, Wallet, } impl From<StripePaymentMethodType> for api_enums::PaymentMethod { fn from(item: StripePaymentMethodType) -> Self { match item { StripePaymentMethodType::Card => Self::Card, StripePaymentMethodType::Wallet => Self::Wallet, } } } #[derive(Default, PartialEq, Eq, Deserialize, Clone)] pub struct StripePaymentMethodData { #[serde(rename = "type")] pub stype: StripePaymentMethodType, pub billing_details: Option<StripeBillingDetails>, #[serde(flatten)] pub payment_method_details: Option<StripePaymentMethodDetails>, // enum pub metadata: Option<Value>, } #[derive(PartialEq, Eq, Deserialize, Clone)] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodDetails { Card(StripeCard), Wallet(StripeWallet), } impl From<StripeCard> for payments::Card { fn from(card: StripeCard) -> Self { Self { card_number: card.number, card_exp_month: card.exp_month, card_exp_year: card.exp_year, card_holder_name: Some(masking::Secret::new("stripe_cust".to_owned())), card_cvc: card.cvc, card_issuer: None, card_network: None, bank_code: None, card_issuing_country: None, card_type: None, nick_name: None, } } } impl From<StripeWallet> for payments::WalletData { fn from(wallet: StripeWallet) -> Self { match wallet { StripeWallet::ApplePay(data) => Self::ApplePay(data), } } } impl From<StripePaymentMethodDetails> for payments::PaymentMethodData { fn from(item: StripePaymentMethodDetails) -> Self { match item { StripePaymentMethodDetails::Card(card) => Self::Card(payments::Card::from(card)), StripePaymentMethodDetails::Wallet(wallet) => { Self::Wallet(payments::WalletData::from(wallet)) } } } } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct Shipping { pub address: Option<payments::AddressDetails>, pub name: Option<String>, pub carrier: Option<String>, pub phone: Option<pii::Secret<String>>, pub tracking_number: Option<pii::Secret<String>>, } impl From<Shipping> for payments::Address { fn from(details: Shipping) -> Self { Self { address: details.address, phone: Some(payments::PhoneDetails { number: details.phone, country_code: None, }), email: None, } } } #[derive(Default, Deserialize, Clone)] pub struct StripeSetupIntentRequest { pub confirm: Option<bool>, pub customer: Option<id_type::CustomerId>, pub connector: Option<Vec<api_enums::RoutableConnectors>>, pub description: Option<String>, pub currency: Option<String>, pub payment_method_data: Option<StripePaymentMethodData>, pub receipt_email: Option<pii::Email>, pub return_url: Option<url::Url>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub shipping: Option<Shipping>, pub billing_details: Option<StripeBillingDetails>, pub statement_descriptor: Option<String>, pub statement_descriptor_suffix: Option<String>, pub metadata: Option<secret::SecretSerdeValue>, pub client_secret: Option<pii::Secret<String>>, pub payment_method_options: Option<payment_intent::StripePaymentMethodOptions>, pub payment_method: Option<String>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, pub receipt_ipaddress: Option<String>, pub user_agent: Option<String>, pub mandate_data: Option<payment_intent::MandateData>, pub connector_metadata: Option<payments::ConnectorMetadata>, } impl TryFrom<StripeSetupIntentRequest> for payments::PaymentsRequest { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripeSetupIntentRequest) -> errors::RouterResult<Self> { let routable_connector: Option<api_enums::RoutableConnectors> = item.connector.and_then(|v| v.into_iter().next()); let routing = routable_connector .map(|connector| { api_models::routing::StaticRoutingAlgorithm::Single(Box::new( api_models::routing::RoutableConnectorChoice { choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, connector, merchant_connector_id: None, }, )) }) .map(|r| { serde_json::to_value(r) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("converting to routing failed") }) .transpose()?; let ip_address = item .receipt_ipaddress .map(|ip| std::net::IpAddr::from_str(ip.as_str())) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "receipt_ipaddress".to_string(), expected_format: "127.0.0.1".to_string(), })?; let metadata_object = item .metadata .clone() .parse_value("metadata") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "metadata mapping failed", })?; let request = Ok(Self { amount: Some(api_types::Amount::Zero), capture_method: None, amount_to_capture: None, confirm: item.confirm, customer_id: item.customer, currency: item .currency .as_ref() .map(|c| c.to_uppercase().parse_enum("currency")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "currency", })?, email: item.receipt_email, name: item .billing_details .as_ref() .and_then(|b| b.name.as_ref().map(|x| masking::Secret::new(x.to_owned()))), phone: item.shipping.as_ref().and_then(|s| s.phone.clone()), description: item.description, return_url: item.return_url, payment_method_data: item.payment_method_data.as_ref().and_then(|pmd| { pmd.payment_method_details .as_ref() .map(|spmd| payments::PaymentMethodDataRequest { payment_method_data: Some(payments::PaymentMethodData::from( spmd.to_owned(), )), billing: pmd.billing_details.clone().map(payments::Address::from), }) }), payment_method: item .payment_method_data .as_ref() .map(|pmd| api_enums::PaymentMethod::from(pmd.stype.to_owned())), shipping: item .shipping .as_ref() .map(|s| payments::Address::from(s.to_owned())), billing: item .billing_details .as_ref() .map(|b| payments::Address::from(b.to_owned())), statement_descriptor_name: item.statement_descriptor, statement_descriptor_suffix: item.statement_descriptor_suffix, metadata: metadata_object, client_secret: item.client_secret.map(|s| s.peek().clone()), setup_future_usage: item.setup_future_usage, merchant_connector_details: item.merchant_connector_details, routing, authentication_type: match item.payment_method_options { Some(pmo) => { let payment_intent::StripePaymentMethodOptions::Card { request_three_d_secure, }: payment_intent::StripePaymentMethodOptions = pmo; Some(api_enums::AuthenticationType::foreign_from( request_three_d_secure, )) } None => None, }, mandate_data: ForeignTryFrom::foreign_try_from(( item.mandate_data, item.currency.to_owned(), ))?, browser_info: Some( serde_json::to_value(crate::types::BrowserInformation { ip_address, user_agent: item.user_agent, ..Default::default() }) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("convert to browser info failed")?, ), connector_metadata: item.connector_metadata, ..Default::default() }); request } } #[derive(Clone, Default, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum StripeSetupStatus { Succeeded, Canceled, #[default] Processing, RequiresAction, RequiresPaymentMethod, RequiresConfirmation, } impl From<api_enums::IntentStatus> for StripeSetupStatus { fn from(item: api_enums::IntentStatus) -> Self { match item { api_enums::IntentStatus::Succeeded | api_enums::IntentStatus::PartiallyCaptured => { Self::Succeeded } api_enums::IntentStatus::Failed | api_enums::IntentStatus::Expired => Self::Canceled, api_enums::IntentStatus::Processing | api_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => Self::Processing, api_enums::IntentStatus::RequiresCustomerAction => Self::RequiresAction, api_enums::IntentStatus::RequiresMerchantAction | api_enums::IntentStatus::Conflicted => Self::RequiresAction, api_enums::IntentStatus::RequiresPaymentMethod => Self::RequiresPaymentMethod, api_enums::IntentStatus::RequiresConfirmation => Self::RequiresConfirmation, api_enums::IntentStatus::RequiresCapture | api_enums::IntentStatus::PartiallyCapturedAndCapturable => { logger::error!("Invalid status change"); Self::Canceled } api_enums::IntentStatus::Cancelled | api_enums::IntentStatus::CancelledPostCapture => { Self::Canceled } } } } #[derive(Debug, Serialize, Deserialize, Copy, Clone, strum::Display)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CancellationReason { Duplicate, Fraudulent, RequestedByCustomer, Abandoned, } #[derive(Debug, Deserialize, Serialize, Copy, Clone)] pub struct StripePaymentCancelRequest { cancellation_reason: Option<CancellationReason>, } impl From<StripePaymentCancelRequest> for payments::PaymentsCancelRequest { fn from(item: StripePaymentCancelRequest) -> Self { Self { cancellation_reason: item.cancellation_reason.map(|c| c.to_string()), ..Self::default() } } } #[derive(Default, Eq, PartialEq, Serialize)] pub struct RedirectUrl { pub return_url: Option<String>, pub url: Option<String>, } #[derive(Eq, PartialEq, serde::Serialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum StripeNextAction { RedirectToUrl { redirect_to_url: RedirectUrl, }, DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: payments::BankTransferNextStepsData, }, ThirdPartySdkSessionToken { session_token: Option<payments::SessionToken>, }, QrCodeInformation { image_data_url: Option<url::Url>, display_to_timestamp: Option<i64>, qr_code_url: Option<url::Url>, border_color: Option<String>, display_text: Option<String>, }, FetchQrCodeInformation { qr_code_fetch_url: url::Url, }, DisplayVoucherInformation { voucher_details: payments::VoucherNextStepData, }, WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, poll_config: Option<payments::PollConfig>, }, InvokeSdkClient { next_action_data: payments::SdkNextActionData, }, CollectOtp { consent_data_required: payments::MobilePaymentConsent, }, InvokeHiddenIframe { iframe_data: payments::IframeData, }, SdkUpiIntentInformation { sdk_uri: url::Url, }, } pub(crate) fn into_stripe_next_action( next_action: Option<payments::NextActionData>, return_url: Option<String>, ) -> Option<StripeNextAction> { next_action.map(|next_action_data| match next_action_data { payments::NextActionData::RedirectToUrl { redirect_to_url } => { StripeNextAction::RedirectToUrl { redirect_to_url: RedirectUrl { return_url, url: Some(redirect_to_url), }, } } payments::NextActionData::RedirectInsidePopup { popup_url, .. } => { StripeNextAction::RedirectToUrl { redirect_to_url: RedirectUrl { return_url, url: Some(popup_url), }, } } payments::NextActionData::DisplayBankTransferInformation { bank_transfer_steps_and_charges_details, } => StripeNextAction::DisplayBankTransferInformation { bank_transfer_steps_and_charges_details, }, payments::NextActionData::ThirdPartySdkSessionToken { session_token } => { StripeNextAction::ThirdPartySdkSessionToken { session_token } } payments::NextActionData::QrCodeInformation { image_data_url, display_to_timestamp, qr_code_url, display_text, border_color, } => StripeNextAction::QrCodeInformation { image_data_url, display_to_timestamp, qr_code_url, display_text, border_color, }, payments::NextActionData::FetchQrCodeInformation { qr_code_fetch_url } => { StripeNextAction::FetchQrCodeInformation { qr_code_fetch_url } } payments::NextActionData::DisplayVoucherInformation { voucher_details } => { StripeNextAction::DisplayVoucherInformation { voucher_details } } payments::NextActionData::WaitScreenInformation { display_from_timestamp, display_to_timestamp, poll_config: _, } => StripeNextAction::WaitScreenInformation { display_from_timestamp, display_to_timestamp, poll_config: None, }, payments::NextActionData::ThreeDsInvoke { .. } => StripeNextAction::RedirectToUrl { redirect_to_url: RedirectUrl { return_url: None, url: None, }, }, payments::NextActionData::InvokeSdkClient { next_action_data } => { StripeNextAction::InvokeSdkClient { next_action_data } } payments::NextActionData::CollectOtp { consent_data_required, } => StripeNextAction::CollectOtp { consent_data_required, }, payments::NextActionData::InvokeHiddenIframe { iframe_data } => { StripeNextAction::InvokeHiddenIframe { iframe_data } } payments::NextActionData::SdkUpiIntentInformation { sdk_uri } => { StripeNextAction::SdkUpiIntentInformation { sdk_uri } } }) } #[derive(Default, Eq, PartialEq, Serialize)] pub struct StripeSetupIntentResponse { pub id: id_type::PaymentId, pub object: String, pub status: StripeSetupStatus, pub client_secret: Option<masking::Secret<String>>, pub metadata: Option<Value>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<time::PrimitiveDateTime>, pub customer: Option<id_type::CustomerId>, pub refunds: Option<Vec<stripe_refunds::StripeRefundResponse>>, pub mandate_id: Option<String>, pub next_action: Option<StripeNextAction>, pub last_payment_error: Option<LastPaymentError>, pub charges: payment_intent::Charges, pub connector_transaction_id: Option<String>, } #[derive(Default, Eq, PartialEq, Serialize)] pub struct LastPaymentError { charge: Option<String>, code: Option<String>, decline_code: Option<String>, message: String, param: Option<String>, payment_method: StripePaymentMethod, #[serde(rename = "type")] error_type: String, } #[derive(Default, Eq, PartialEq, Serialize)] pub struct StripePaymentMethod { #[serde(rename = "id")] payment_method_id: String, object: &'static str, card: Option<StripeCard>, created: u64, #[serde(rename = "type")] method_type: String, livemode: bool, } impl From<payments::PaymentsResponse> for StripeSetupIntentResponse { fn from(resp: payments::PaymentsResponse) -> Self { Self { object: "setup_intent".to_owned(), status: StripeSetupStatus::from(resp.status), client_secret: resp.client_secret, charges: payment_intent::Charges::new(), created: resp.created, customer: resp.customer_id, metadata: resp.metadata, id: resp.payment_id, refunds: resp .refunds .map(|a| a.into_iter().map(Into::into).collect()), mandate_id: resp.mandate_id, next_action: into_stripe_next_action(resp.next_action, resp.return_url), last_payment_error: resp.error_code.map(|code| -> LastPaymentError { LastPaymentError { charge: None, code: Some(code.to_owned()), decline_code: None, message: resp .error_message .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), param: None, payment_method: StripePaymentMethod { payment_method_id: "place_holder_id".to_string(), object: "payment_method", card: None, created: u64::try_from(date_time::now().assume_utc().unix_timestamp()) .unwrap_or_default(), method_type: "card".to_string(), livemode: false, }, error_type: code, } }), connector_transaction_id: resp.connector_transaction_id, } } } #[derive(Clone, Debug, serde::Deserialize)] #[serde(deny_unknown_fields)] pub struct StripePaymentListConstraints { pub customer: Option<id_type::CustomerId>, pub starting_after: Option<id_type::PaymentId>, pub ending_before: Option<id_type::PaymentId>, #[serde(default = "default_limit")] pub limit: u32, pub created: Option<i64>, #[serde(rename = "created[lt]")] pub created_lt: Option<i64>, #[serde(rename = "created[gt]")] pub created_gt: Option<i64>, #[serde(rename = "created[lte]")] pub created_lte: Option<i64>, #[serde(rename = "created[gte]")] pub created_gte: Option<i64>, } fn default_limit() -> u32 { 10 } impl TryFrom<StripePaymentListConstraints> for payments::PaymentListConstraints { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripePaymentListConstraints) -> Result<Self, Self::Error> { Ok(Self { customer_id: item.customer, starting_after: item.starting_after, ending_before: item.ending_before, limit: item.limit, created: from_timestamp_to_datetime(item.created)?, created_lt: from_timestamp_to_datetime(item.created_lt)?, created_gt: from_timestamp_to_datetime(item.created_gt)?, created_lte: from_timestamp_to_datetime(item.created_lte)?, created_gte: from_timestamp_to_datetime(item.created_gte)?, }) } } #[inline] fn from_timestamp_to_datetime( time: Option<i64>, ) -> Result<Option<time::PrimitiveDateTime>, errors::ApiErrorResponse> { if let Some(time) = time { let time = time::OffsetDateTime::from_unix_timestamp(time).map_err(|err| { logger::error!("Error: from_unix_timestamp: {}", err); errors::ApiErrorResponse::InvalidRequestData { message: "Error while converting timestamp".to_string(), } })?; Ok(Some(time::PrimitiveDateTime::new(time.date(), time.time()))) } else { Ok(None) } }
{ "crate": "router", "file": "crates/router/src/compatibility/stripe/setup_intents/types.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 6, "num_structs": 11, "num_tables": null, "score": null, "total_crates": null }
file_router_7430255158729244881
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/compatibility/stripe/refunds/types.rs // Contains: 3 structs, 1 enums use std::{convert::From, default::Default}; use common_utils::pii; use serde::{Deserialize, Serialize}; use crate::types::api::{admin, refunds}; #[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug)] pub struct StripeCreateRefundRequest { pub refund_id: Option<String>, pub amount: Option<i64>, pub payment_intent: common_utils::id_type::PaymentId, pub reason: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct StripeUpdateRefundRequest { #[serde(skip)] pub refund_id: String, pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Clone, Serialize, PartialEq, Eq, Debug)] pub struct StripeRefundResponse { pub id: String, pub amount: i64, pub currency: String, pub payment_intent: common_utils::id_type::PaymentId, pub status: StripeRefundStatus, pub created: Option<i64>, pub metadata: pii::SecretSerdeValue, } #[derive(Clone, Serialize, Deserialize, Eq, PartialEq, Debug)] #[serde(rename_all = "snake_case")] pub enum StripeRefundStatus { Succeeded, Failed, Pending, RequiresAction, } impl From<StripeCreateRefundRequest> for refunds::RefundRequest { fn from(req: StripeCreateRefundRequest) -> Self { Self { refund_id: req.refund_id, amount: req.amount.map(common_utils::types::MinorUnit::new), payment_id: req.payment_intent, reason: req.reason, refund_type: Some(refunds::RefundType::Instant), metadata: req.metadata, merchant_connector_details: req.merchant_connector_details, ..Default::default() } } } impl From<StripeUpdateRefundRequest> for refunds::RefundUpdateRequest { fn from(req: StripeUpdateRefundRequest) -> Self { Self { refund_id: req.refund_id, metadata: req.metadata, reason: None, } } } impl From<refunds::RefundStatus> for StripeRefundStatus { fn from(status: refunds::RefundStatus) -> Self { match status { refunds::RefundStatus::Succeeded => Self::Succeeded, refunds::RefundStatus::Failed => Self::Failed, refunds::RefundStatus::Pending => Self::Pending, refunds::RefundStatus::Review => Self::RequiresAction, } } } impl From<refunds::RefundResponse> for StripeRefundResponse { fn from(res: refunds::RefundResponse) -> Self { Self { id: res.refund_id, amount: res.amount.get_amount_as_i64(), currency: res.currency.to_ascii_lowercase(), payment_intent: res.payment_id, status: res.status.into(), created: res.created_at.map(|t| t.assume_utc().unix_timestamp()), metadata: res .metadata .unwrap_or_else(|| masking::Secret::new(serde_json::json!({}))), } } }
{ "crate": "router", "file": "crates/router/src/compatibility/stripe/refunds/types.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_router_-1030645020729022226
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/payment_methods.rs // Contains: 37 structs, 2 enums use std::fmt::Debug; use api_models::enums as api_enums; #[cfg(feature = "v1")] use cards::CardNumber; #[cfg(feature = "v2")] use cards::{CardNumber, NetworkToken}; #[cfg(feature = "v2")] use common_types::primitive_wrappers; #[cfg(feature = "v2")] use common_utils::generate_id; use common_utils::id_type; #[cfg(feature = "v2")] use hyperswitch_domain_models::payment_method_data::NetworkTokenDetails; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::types::api; #[cfg(feature = "v2")] use crate::{ consts, types::{domain, storage}, }; #[cfg(feature = "v2")] pub trait VaultingInterface { fn get_vaulting_request_url() -> &'static str; fn get_vaulting_flow_name() -> &'static str; } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultFingerprintRequest { pub data: String, pub key: String, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultFingerprintResponse { pub fingerprint_id: String, } #[cfg(any(feature = "v2", feature = "tokenization_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AddVaultRequest<D> { pub entity_id: id_type::GlobalCustomerId, pub vault_id: domain::VaultId, pub data: D, pub ttl: i64, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AddVaultResponse { #[cfg(feature = "v2")] pub entity_id: Option<id_type::GlobalCustomerId>, #[cfg(feature = "v1")] pub entity_id: Option<id_type::CustomerId>, #[cfg(feature = "v2")] pub vault_id: domain::VaultId, #[cfg(feature = "v1")] pub vault_id: String, pub fingerprint_id: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AddVault; #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetVaultFingerprint; #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultRetrieve; #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultDelete; #[cfg(feature = "v2")] impl VaultingInterface for AddVault { fn get_vaulting_request_url() -> &'static str { consts::ADD_VAULT_REQUEST_URL } fn get_vaulting_flow_name() -> &'static str { consts::VAULT_ADD_FLOW_TYPE } } #[cfg(feature = "v2")] impl VaultingInterface for GetVaultFingerprint { fn get_vaulting_request_url() -> &'static str { consts::VAULT_FINGERPRINT_REQUEST_URL } fn get_vaulting_flow_name() -> &'static str { consts::VAULT_GET_FINGERPRINT_FLOW_TYPE } } #[cfg(feature = "v2")] impl VaultingInterface for VaultRetrieve { fn get_vaulting_request_url() -> &'static str { consts::VAULT_RETRIEVE_REQUEST_URL } fn get_vaulting_flow_name() -> &'static str { consts::VAULT_RETRIEVE_FLOW_TYPE } } #[cfg(feature = "v2")] impl VaultingInterface for VaultDelete { fn get_vaulting_request_url() -> &'static str { consts::VAULT_DELETE_REQUEST_URL } fn get_vaulting_flow_name() -> &'static str { consts::VAULT_DELETE_FLOW_TYPE } } #[cfg(feature = "v2")] pub struct SavedPMLPaymentsInfo { pub payment_intent: storage::PaymentIntent, pub profile: domain::Profile, pub collect_cvv_during_payment: Option<primitive_wrappers::ShouldCollectCvvDuringPayment>, pub off_session_payment_flag: bool, pub is_connector_agnostic_mit_enabled: bool, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultRetrieveRequest { pub entity_id: id_type::GlobalCustomerId, pub vault_id: domain::VaultId, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultRetrieveResponse { pub data: domain::PaymentMethodVaultingData, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultDeleteRequest { pub entity_id: id_type::GlobalCustomerId, pub vault_id: domain::VaultId, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultDeleteResponse { pub entity_id: id_type::GlobalCustomerId, pub vault_id: domain::VaultId, } #[cfg(feature = "v1")] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CardData { pub card_number: CardNumber, pub exp_month: Secret<String>, pub exp_year: Secret<String>, pub card_security_code: Option<Secret<String>>, } #[cfg(feature = "v2")] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CardData { pub card_number: CardNumber, pub exp_month: Secret<String>, pub exp_year: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub card_security_code: Option<Secret<String>>, } #[cfg(feature = "v1")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct OrderData { pub consent_id: String, pub customer_id: id_type::CustomerId, } #[cfg(feature = "v2")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct OrderData { pub consent_id: String, pub customer_id: id_type::GlobalCustomerId, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApiPayload { pub service: String, pub card_data: Secret<String>, //encrypted card data pub order_data: OrderData, pub key_id: String, pub should_send_token: bool, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct CardNetworkTokenResponse { pub payload: Secret<String>, //encrypted payload } #[cfg(feature = "v1")] #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CardNetworkTokenResponsePayload { pub card_brand: api_enums::CardNetwork, pub card_fingerprint: Option<Secret<String>>, pub card_reference: String, pub correlation_id: String, pub customer_id: String, pub par: String, pub token: CardNumber, pub token_expiry_month: Secret<String>, pub token_expiry_year: Secret<String>, pub token_isin: String, pub token_last_four: String, pub token_status: String, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct GenerateNetworkTokenResponsePayload { pub card_brand: api_enums::CardNetwork, pub card_fingerprint: Option<Secret<String>>, pub card_reference: String, pub correlation_id: String, pub customer_id: String, pub par: String, pub token: NetworkToken, pub token_expiry_month: Secret<String>, pub token_expiry_year: Secret<String>, pub token_isin: String, pub token_last_four: String, pub token_status: String, } #[cfg(feature = "v1")] #[derive(Debug, Serialize)] pub struct GetCardToken { pub card_reference: String, pub customer_id: id_type::CustomerId, } #[cfg(feature = "v2")] #[derive(Debug, Serialize)] pub struct GetCardToken { pub card_reference: String, pub customer_id: id_type::GlobalCustomerId, } #[cfg(feature = "v1")] #[derive(Debug, Deserialize)] pub struct AuthenticationDetails { pub cryptogram: Secret<String>, pub token: CardNumber, //network token } #[cfg(feature = "v2")] #[derive(Debug, Deserialize)] pub struct AuthenticationDetails { pub cryptogram: Secret<String>, pub token: NetworkToken, //network token } #[derive(Debug, Serialize, Deserialize)] pub struct TokenDetails { pub exp_month: Secret<String>, pub exp_year: Secret<String>, } #[derive(Debug, Deserialize)] pub struct TokenResponse { pub authentication_details: AuthenticationDetails, pub network: api_enums::CardNetwork, pub token_details: TokenDetails, pub eci: Option<String>, pub card_type: Option<String>, pub issuer: Option<String>, pub nickname: Option<Secret<String>>, } #[cfg(feature = "v1")] #[derive(Debug, Serialize, Deserialize)] pub struct DeleteCardToken { pub card_reference: String, //network token requestor ref id pub customer_id: id_type::CustomerId, } #[cfg(feature = "v2")] #[derive(Debug, Serialize, Deserialize)] pub struct DeleteCardToken { pub card_reference: String, //network token requestor ref id pub customer_id: id_type::GlobalCustomerId, } #[derive(Debug, Deserialize, Eq, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum DeleteNetworkTokenStatus { Success, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct NetworkTokenErrorInfo { pub code: String, pub developer_message: String, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct NetworkTokenErrorResponse { pub error_message: String, pub error_info: NetworkTokenErrorInfo, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct DeleteNetworkTokenResponse { pub status: DeleteNetworkTokenStatus, } #[cfg(feature = "v1")] #[derive(Debug, Serialize, Deserialize)] pub struct CheckTokenStatus { pub card_reference: String, pub customer_id: id_type::CustomerId, } #[cfg(feature = "v2")] #[derive(Debug, Serialize, Deserialize)] pub struct CheckTokenStatus { pub card_reference: String, pub customer_id: id_type::GlobalCustomerId, } #[derive(Debug, Deserialize, Clone)] #[serde(rename_all = "UPPERCASE")] pub enum TokenStatus { Active, Suspended, Deactivated, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CheckTokenStatusResponse { pub token_status: TokenStatus, pub token_expiry_month: Secret<String>, pub token_expiry_year: Secret<String>, pub card_last_4: String, pub card_expiry: String, pub token_last_4: String, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct NetworkTokenRequestorData { pub card_reference: String, pub customer_id: String, pub expiry_year: Secret<String>, pub expiry_month: Secret<String>, } impl NetworkTokenRequestorData { pub fn is_update_required( &self, data_stored_in_vault: api::payment_methods::CardDetailFromLocker, ) -> bool { //if the expiry year and month in the vault are not the same as the ones in the requestor data, //then we need to update the vault data with the updated expiry year and month. !((data_stored_in_vault.expiry_year.unwrap_or_default() == self.expiry_year) && (data_stored_in_vault.expiry_month.unwrap_or_default() == self.expiry_month)) } } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct NetworkTokenMetaDataUpdateBody { pub token: NetworkTokenRequestorData, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct PanMetadataUpdateBody { pub card: NetworkTokenRequestorData, }
{ "crate": "router", "file": "crates/router/src/types/payment_methods.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 37, "num_tables": null, "score": null, "total_crates": null }
file_router_-4694817511874872440
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/fraud_check.rs // Contains: 1 structs, 2 enums pub use hyperswitch_domain_models::{ router_request_types::fraud_check::{ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, FraudCheckSaleData, FraudCheckTransactionData, RefundMethod, }, router_response_types::fraud_check::FraudCheckResponseData, }; use crate::{ services, types::{api, ErrorResponse, RouterData}, }; pub type FrmSaleRouterData = RouterData<api::Sale, FraudCheckSaleData, FraudCheckResponseData>; pub type FrmSaleType = dyn services::ConnectorIntegration<api::Sale, FraudCheckSaleData, FraudCheckResponseData>; #[derive(Debug, Clone)] pub struct FrmRouterData { pub merchant_id: common_utils::id_type::MerchantId, pub connector: String, // TODO: change this to PaymentId type pub payment_id: String, pub attempt_id: String, pub request: FrmRequest, pub response: FrmResponse, } #[derive(Debug, Clone)] pub enum FrmRequest { Sale(FraudCheckSaleData), Checkout(Box<FraudCheckCheckoutData>), Transaction(FraudCheckTransactionData), Fulfillment(FraudCheckFulfillmentData), RecordReturn(FraudCheckRecordReturnData), } #[derive(Debug, Clone)] pub enum FrmResponse { Sale(Result<FraudCheckResponseData, ErrorResponse>), Checkout(Result<FraudCheckResponseData, ErrorResponse>), Transaction(Result<FraudCheckResponseData, ErrorResponse>), Fulfillment(Result<FraudCheckResponseData, ErrorResponse>), RecordReturn(Result<FraudCheckResponseData, ErrorResponse>), } pub type FrmCheckoutRouterData = RouterData<api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>; pub type FrmCheckoutType = dyn services::ConnectorIntegration< api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData, >; pub type FrmTransactionRouterData = RouterData<api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>; pub type FrmTransactionType = dyn services::ConnectorIntegration< api::Transaction, FraudCheckTransactionData, FraudCheckResponseData, >; pub type FrmFulfillmentRouterData = RouterData<api::Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>; pub type FrmFulfillmentType = dyn services::ConnectorIntegration< api::Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData, >; pub type FrmRecordReturnRouterData = RouterData<api::RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>; pub type FrmRecordReturnType = dyn services::ConnectorIntegration< api::RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData, >;
{ "crate": "router", "file": "crates/router/src/types/fraud_check.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-8076834505232194512
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/api.rs // Contains: 2 structs, 1 enums pub mod admin; pub mod api_keys; pub mod authentication; pub mod configs; #[cfg(feature = "olap")] pub mod connector_onboarding; pub mod customers; pub mod disputes; pub mod enums; pub mod ephemeral_key; pub mod files; #[cfg(feature = "frm")] pub mod fraud_check; pub mod mandates; pub mod payment_link; pub mod payment_methods; pub mod payments; #[cfg(feature = "payouts")] pub mod payouts; pub mod poll; pub mod refunds; pub mod routing; #[cfg(feature = "olap")] pub mod verify_connector; #[cfg(feature = "olap")] pub mod webhook_events; pub mod webhooks; pub mod authentication_v2; pub mod connector_mapping; pub mod disputes_v2; pub mod feature_matrix; pub mod files_v2; #[cfg(feature = "frm")] pub mod fraud_check_v2; pub mod payments_v2; #[cfg(feature = "payouts")] pub mod payouts_v2; pub mod refunds_v2; use std::{fmt::Debug, str::FromStr}; 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, AccessTokenAuthentication}, mandate_revoke::MandateRevoke, webhooks::VerifyWebhookSource, }; pub use hyperswitch_interfaces::{ api::{ authentication::{ ConnectorAuthentication, ConnectorPostAuthentication, ConnectorPreAuthentication, ConnectorPreAuthenticationVersionCall, ExternalAuthentication, }, authentication_v2::{ ConnectorAuthenticationV2, ConnectorPostAuthenticationV2, ConnectorPreAuthenticationV2, ConnectorPreAuthenticationVersionCallV2, ExternalAuthenticationV2, }, fraud_check::FraudCheck, revenue_recovery::{ BillingConnectorInvoiceSyncIntegration, BillingConnectorPaymentsSyncIntegration, RevenueRecovery, RevenueRecoveryRecordBack, }, revenue_recovery_v2::RevenueRecoveryV2, BoxedConnector, Connector, ConnectorAccessToken, ConnectorAccessTokenV2, ConnectorAuthenticationToken, ConnectorAuthenticationTokenV2, ConnectorCommon, ConnectorCommonExt, ConnectorMandateRevoke, ConnectorMandateRevokeV2, ConnectorTransactionId, ConnectorVerifyWebhookSource, ConnectorVerifyWebhookSourceV2, CurrencyUnit, }, connector_integration_v2::{BoxedConnectorV2, ConnectorV2}, }; use rustc_hash::FxHashMap; #[cfg(feature = "frm")] pub use self::fraud_check::*; #[cfg(feature = "payouts")] pub use self::payouts::*; pub use self::{ admin::*, api_keys::*, authentication::*, configs::*, connector_mapping::*, customers::*, disputes::*, files::*, payment_link::*, payment_methods::*, payments::*, poll::*, refunds::*, refunds_v2::*, webhooks::*, }; use super::transformers::ForeignTryFrom; use crate::{ connector, consts, core::{ errors::{self, CustomResult}, payments::types as payments_types, }, services::connector_integration_interface::ConnectorEnum, types::{self, api::enums as api_enums}, }; #[derive(Clone)] pub enum ConnectorCallType { PreDetermined(ConnectorRoutingData), Retryable(Vec<ConnectorRoutingData>), SessionMultiple(SessionConnectorDatas), #[cfg(feature = "v2")] Skip, } impl From<ConnectorData> for ConnectorRoutingData { fn from(connector_data: ConnectorData) -> Self { Self { connector_data, network: None, action_type: None, } } } #[derive(Clone, Debug)] pub struct SessionConnectorData { pub payment_method_sub_type: api_enums::PaymentMethodType, pub payment_method_type: api_enums::PaymentMethod, pub connector: ConnectorData, pub business_sub_label: Option<String>, } impl SessionConnectorData { pub fn new( payment_method_sub_type: api_enums::PaymentMethodType, connector: ConnectorData, business_sub_label: Option<String>, payment_method_type: api_enums::PaymentMethod, ) -> Self { Self { payment_method_sub_type, connector, business_sub_label, payment_method_type, } } } common_utils::create_list_wrapper!( SessionConnectorDatas, SessionConnectorData, impl_functions: { pub fn apply_filter_for_session_routing(&self) -> Self { let routing_enabled_pmts = &consts::ROUTING_ENABLED_PAYMENT_METHOD_TYPES; let routing_enabled_pms = &consts::ROUTING_ENABLED_PAYMENT_METHODS; self .iter() .filter(|connector_data| { routing_enabled_pmts.contains(&connector_data.payment_method_sub_type) || routing_enabled_pms.contains(&connector_data.payment_method_type) }) .cloned() .collect() } pub fn filter_and_validate_for_session_flow(self, routing_results: &FxHashMap<api_enums::PaymentMethodType, Vec<routing::SessionRoutingChoice>>) -> Result<Self, errors::ApiErrorResponse> { let mut final_list = Self::new(Vec::new()); let routing_enabled_pmts = &consts::ROUTING_ENABLED_PAYMENT_METHOD_TYPES; for connector_data in self { if !routing_enabled_pmts.contains(&connector_data.payment_method_sub_type) { final_list.push(connector_data); } else if let Some(choice) = routing_results.get(&connector_data.payment_method_sub_type) { let routing_choice = choice .first() .ok_or(errors::ApiErrorResponse::InternalServerError)?; if connector_data.connector.connector_name == routing_choice.connector.connector_name && connector_data.connector.merchant_connector_id == routing_choice.connector.merchant_connector_id { final_list.push(connector_data); } } } Ok(final_list) } } ); pub fn convert_connector_data_to_routable_connectors( connectors: &[ConnectorRoutingData], ) -> CustomResult<Vec<RoutableConnectorChoice>, common_utils::errors::ValidationError> { connectors .iter() .map(|connectors_routing_data| { RoutableConnectorChoice::foreign_try_from( connectors_routing_data.connector_data.clone(), ) }) .collect() } impl ForeignTryFrom<ConnectorData> for RoutableConnectorChoice { type Error = error_stack::Report<common_utils::errors::ValidationError>; fn foreign_try_from(from: ConnectorData) -> Result<Self, Self::Error> { match RoutableConnectors::foreign_try_from(from.connector_name) { Ok(connector) => Ok(Self { choice_kind: api_routing::RoutableChoiceKind::FullStruct, connector, merchant_connector_id: from.merchant_connector_id, }), Err(e) => Err(common_utils::errors::ValidationError::InvalidValue { message: format!("This is not a routable connector: {e:?}"), })?, } } } /// Session Surcharge type pub enum SessionSurchargeDetails { /// Surcharge is calculated by hyperswitch Calculated(payments_types::SurchargeMetadata), /// Surcharge is sent by merchant PreDetermined(payments_types::SurchargeDetails), } impl SessionSurchargeDetails { pub fn fetch_surcharge_details( &self, payment_method: enums::PaymentMethod, payment_method_type: enums::PaymentMethodType, card_network: Option<&enums::CardNetwork>, ) -> Option<payments_types::SurchargeDetails> { match self { Self::Calculated(surcharge_metadata) => surcharge_metadata .get_surcharge_details(payments_types::SurchargeKey::PaymentMethodData( payment_method, payment_method_type, card_network.cloned(), )) .cloned(), Self::PreDetermined(surcharge_details) => Some(surcharge_details.clone()), } } } pub enum ConnectorChoice { SessionMultiple(SessionConnectorDatas), StraightThrough(serde_json::Value), Decide, } #[cfg(test)] mod test { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_convert_connector_parsing_success() { let result = enums::Connector::from_str("aci"); assert!(result.is_ok()); assert_eq!(result.unwrap(), enums::Connector::Aci); let result = enums::Connector::from_str("shift4"); assert!(result.is_ok()); assert_eq!(result.unwrap(), enums::Connector::Shift4); let result = enums::Connector::from_str("authorizedotnet"); assert!(result.is_ok()); assert_eq!(result.unwrap(), enums::Connector::Authorizedotnet); } #[test] fn test_convert_connector_parsing_fail_for_unknown_type() { let result = enums::Connector::from_str("unknowntype"); assert!(result.is_err()); let result = enums::Connector::from_str("randomstring"); assert!(result.is_err()); } #[test] fn test_convert_connector_parsing_fail_for_camel_case() { let result = enums::Connector::from_str("Paypal"); assert!(result.is_err()); let result = enums::Connector::from_str("Authorizedotnet"); assert!(result.is_err()); let result = enums::Connector::from_str("Opennode"); assert!(result.is_err()); } } #[derive(Clone)] pub struct TaxCalculateConnectorData { pub connector: ConnectorEnum, pub connector_name: enums::TaxConnectors, } impl TaxCalculateConnectorData { pub fn get_connector_by_name(name: &str) -> CustomResult<Self, errors::ApiErrorResponse> { let connector_name = enums::TaxConnectors::from_str(name) .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven) .attach_printable_lazy(|| format!("unable to parse connector: {name}"))?; let connector = Self::convert_connector(connector_name)?; Ok(Self { connector, connector_name, }) } fn convert_connector( connector_name: enums::TaxConnectors, ) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> { match connector_name { enums::TaxConnectors::Taxjar => { Ok(ConnectorEnum::Old(Box::new(connector::Taxjar::new()))) } } } }
{ "crate": "router", "file": "crates/router/src/types/api.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_router_-7875187235876652786
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/storage/revenue_recovery_redis_operation.rs // Contains: 4 structs, 0 enums use std::collections::HashMap; use api_models::revenue_recovery_data_backfill::{self, RedisKeyType}; use common_enums::enums::CardNetwork; use common_utils::{date_time, errors::CustomResult, id_type}; use error_stack::ResultExt; use masking::{ExposeInterface, Secret}; use redis_interface::{DelReply, SetnxReply}; use router_env::{instrument, logger, tracing}; use serde::{Deserialize, Serialize}; use time::{Date, Duration, OffsetDateTime, PrimitiveDateTime}; use crate::{db::errors, types::storage::enums::RevenueRecoveryAlgorithmType, SessionState}; // Constants for retry window management const RETRY_WINDOW_DAYS: i32 = 30; const INITIAL_RETRY_COUNT: i32 = 0; /// Payment processor token details including card information #[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] pub struct PaymentProcessorTokenDetails { pub payment_processor_token: String, pub expiry_month: Option<Secret<String>>, pub expiry_year: Option<Secret<String>>, pub card_issuer: Option<String>, pub last_four_digits: Option<String>, pub card_network: Option<CardNetwork>, pub card_type: Option<String>, } /// Represents the status and retry history of a payment processor token #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentProcessorTokenStatus { /// Payment processor token details including card information and token ID pub payment_processor_token_details: PaymentProcessorTokenDetails, /// Payment intent ID that originally inserted this token pub inserted_by_attempt_id: id_type::GlobalAttemptId, /// Error code associated with the token failure pub error_code: Option<String>, /// Daily retry count history for the last 30 days (date -> retry_count) pub daily_retry_history: HashMap<Date, i32>, /// Scheduled time for the next retry attempt pub scheduled_at: Option<PrimitiveDateTime>, /// Indicates if the token is a hard decline (no retries allowed) pub is_hard_decline: Option<bool>, } /// Token retry availability information with detailed wait times #[derive(Debug, Clone)] pub struct TokenRetryInfo { pub monthly_wait_hours: i64, // Hours to wait for 30-day limit reset pub daily_wait_hours: i64, // Hours to wait for daily limit reset pub total_30_day_retries: i32, // Current total retry count in 30-day window } /// Complete token information with retry limits and wait times #[derive(Debug, Clone)] pub struct PaymentProcessorTokenWithRetryInfo { /// The complete token status information pub token_status: PaymentProcessorTokenStatus, /// Hours to wait before next retry attempt (max of daily/monthly wait) pub retry_wait_time_hours: i64, /// Number of retries remaining in the 30-day rolling window pub monthly_retry_remaining: i32, // Current total retry count in 30-day window pub total_30_day_retries: i32, } /// Redis-based token management struct pub struct RedisTokenManager; impl RedisTokenManager { fn get_connector_customer_lock_key(connector_customer_id: &str) -> String { format!("customer:{connector_customer_id}:status") } fn get_connector_customer_tokens_key(connector_customer_id: &str) -> String { format!("customer:{connector_customer_id}:tokens") } /// Lock connector customer #[instrument(skip_all)] pub async fn lock_connector_customer_status( state: &SessionState, connector_customer_id: &str, payment_id: &id_type::GlobalPaymentId, ) -> CustomResult<bool, errors::StorageError> { let redis_conn = state .store .get_redis_conn() .change_context(errors::StorageError::RedisError( errors::RedisError::RedisConnectionError.into(), ))?; let lock_key = Self::get_connector_customer_lock_key(connector_customer_id); let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds; let result: bool = match redis_conn .set_key_if_not_exists_with_expiry( &lock_key.into(), payment_id.get_string_repr(), Some(*seconds), ) .await { Ok(resp) => resp == SetnxReply::KeySet, Err(error) => { tracing::error!(operation = "lock_stream", err = ?error); false } }; tracing::debug!( connector_customer_id = connector_customer_id, payment_id = payment_id.get_string_repr(), lock_acquired = %result, "Connector customer lock attempt" ); Ok(result) } #[instrument(skip_all)] pub async fn update_connector_customer_lock_ttl( state: &SessionState, connector_customer_id: &str, exp_in_seconds: i64, ) -> CustomResult<bool, errors::StorageError> { let redis_conn = state .store .get_redis_conn() .change_context(errors::StorageError::RedisError( errors::RedisError::RedisConnectionError.into(), ))?; let lock_key = Self::get_connector_customer_lock_key(connector_customer_id); let result: bool = redis_conn .set_expiry(&lock_key.into(), exp_in_seconds) .await .map_or_else( |error| { tracing::error!(operation = "update_lock_ttl", err = ?error); false }, |_| true, ); tracing::debug!( connector_customer_id = connector_customer_id, new_ttl_in_seconds = exp_in_seconds, ttl_updated = %result, "Connector customer lock TTL update with new expiry time" ); Ok(result) } /// Unlock connector customer status #[instrument(skip_all)] pub async fn unlock_connector_customer_status( state: &SessionState, connector_customer_id: &str, ) -> CustomResult<bool, errors::StorageError> { let redis_conn = state .store .get_redis_conn() .change_context(errors::StorageError::RedisError( errors::RedisError::RedisConnectionError.into(), ))?; let lock_key = Self::get_connector_customer_lock_key(connector_customer_id); match redis_conn.delete_key(&lock_key.into()).await { Ok(DelReply::KeyDeleted) => { tracing::debug!( connector_customer_id = connector_customer_id, "Connector customer unlocked" ); Ok(true) } Ok(DelReply::KeyNotDeleted) => { tracing::debug!("Tried to unlock a stream which is already unlocked"); Ok(false) } Err(err) => { tracing::error!(?err, "Failed to delete lock key"); Ok(false) } } } /// Get all payment processor tokens for a connector customer #[instrument(skip_all)] pub async fn get_connector_customer_payment_processor_tokens( state: &SessionState, connector_customer_id: &str, ) -> CustomResult<HashMap<String, PaymentProcessorTokenStatus>, errors::StorageError> { let redis_conn = state .store .get_redis_conn() .change_context(errors::StorageError::RedisError( errors::RedisError::RedisConnectionError.into(), ))?; let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id); let get_hash_err = errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into()); let payment_processor_tokens: HashMap<String, String> = redis_conn .get_hash_fields(&tokens_key.into()) .await .change_context(get_hash_err)?; let payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus> = payment_processor_tokens .into_iter() .filter_map(|(token_id, token_data)| { match serde_json::from_str::<PaymentProcessorTokenStatus>(&token_data) { Ok(token_status) => Some((token_id, token_status)), Err(err) => { tracing::warn!( connector_customer_id = %connector_customer_id, token_id = %token_id, error = %err, "Failed to deserialize token data, skipping", ); None } } }) .collect(); tracing::debug!( connector_customer_id = connector_customer_id, "Fetched payment processor tokens", ); Ok(payment_processor_token_info_map) } /// Update connector customer payment processor tokens or add if doesn't exist #[instrument(skip_all)] pub async fn update_or_add_connector_customer_payment_processor_tokens( state: &SessionState, connector_customer_id: &str, payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus>, ) -> CustomResult<(), errors::StorageError> { let redis_conn = state .store .get_redis_conn() .change_context(errors::StorageError::RedisError( errors::RedisError::RedisConnectionError.into(), ))?; let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id); // allocate capacity up-front to avoid rehashing let mut serialized_payment_processor_tokens: HashMap<String, String> = HashMap::with_capacity(payment_processor_token_info_map.len()); // serialize all tokens, preserving explicit error handling and attachable diagnostics for (payment_processor_token_id, payment_processor_token_status) in payment_processor_token_info_map { let serialized = serde_json::to_string(&payment_processor_token_status) .change_context(errors::StorageError::SerializationFailed) .attach_printable("Failed to serialize token status")?; serialized_payment_processor_tokens.insert(payment_processor_token_id, serialized); } let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds; // Update or add tokens redis_conn .set_hash_fields( &tokens_key.into(), serialized_payment_processor_tokens, Some(*seconds), ) .await .change_context(errors::StorageError::RedisError( errors::RedisError::SetHashFieldFailed.into(), ))?; tracing::info!( connector_customer_id = %connector_customer_id, "Successfully updated or added customer tokens", ); Ok(()) } /// Get current date in `yyyy-mm-dd` format. pub fn get_current_date() -> String { let today = date_time::now().date(); let (year, month, day) = (today.year(), today.month(), today.day()); format!("{year:04}-{month:02}-{day:02}",) } /// Normalize retry window to exactly `RETRY_WINDOW_DAYS` days (today to `RETRY_WINDOW_DAYS - 1` days ago). pub fn normalize_retry_window( payment_processor_token: &mut PaymentProcessorTokenStatus, today: Date, ) { let mut normalized_retry_history: HashMap<Date, i32> = HashMap::new(); for days_ago in 0..RETRY_WINDOW_DAYS { let date = today - Duration::days(days_ago.into()); payment_processor_token .daily_retry_history .get(&date) .map(|&retry_count| { normalized_retry_history.insert(date, retry_count); }); } payment_processor_token.daily_retry_history = normalized_retry_history; } /// Get all payment processor tokens with retry information and wait times. pub fn get_tokens_with_retry_metadata( state: &SessionState, payment_processor_token_info_map: &HashMap<String, PaymentProcessorTokenStatus>, ) -> HashMap<String, PaymentProcessorTokenWithRetryInfo> { let today = OffsetDateTime::now_utc().date(); let card_config = &state.conf.revenue_recovery.card_config; let mut result: HashMap<String, PaymentProcessorTokenWithRetryInfo> = HashMap::with_capacity(payment_processor_token_info_map.len()); for (payment_processor_token_id, payment_processor_token_status) in payment_processor_token_info_map.iter() { let card_network = payment_processor_token_status .payment_processor_token_details .card_network .clone(); // Calculate retry information. let retry_info = Self::payment_processor_token_retry_info( state, payment_processor_token_status, today, card_network.clone(), ); // Determine the wait time (max of monthly and daily wait hours). let retry_wait_time_hours = retry_info .monthly_wait_hours .max(retry_info.daily_wait_hours); // Obtain network-specific limits and compute remaining monthly retries. let card_network_config = card_config.get_network_config(card_network); let monthly_retry_remaining = std::cmp::max( 0, card_network_config.max_retry_count_for_thirty_day - retry_info.total_30_day_retries, ); // Build the per-token result struct. let token_with_retry_info = PaymentProcessorTokenWithRetryInfo { token_status: payment_processor_token_status.clone(), retry_wait_time_hours, monthly_retry_remaining, total_30_day_retries: retry_info.total_30_day_retries, }; result.insert(payment_processor_token_id.clone(), token_with_retry_info); } tracing::debug!("Fetched payment processor tokens with retry metadata",); result } /// Sum retries over exactly the last 30 days fn calculate_total_30_day_retries(token: &PaymentProcessorTokenStatus, today: Date) -> i32 { (0..RETRY_WINDOW_DAYS) .map(|i| { let date = today - Duration::days(i.into()); token .daily_retry_history .get(&date) .copied() .unwrap_or(INITIAL_RETRY_COUNT) }) .sum() } /// Calculate wait hours fn calculate_wait_hours(target_date: Date, now: OffsetDateTime) -> i64 { let expiry_time = target_date.midnight().assume_utc(); (expiry_time - now).whole_hours().max(0) } /// Calculate retry counts for exactly the last 30 days pub fn payment_processor_token_retry_info( state: &SessionState, token: &PaymentProcessorTokenStatus, today: Date, network_type: Option<CardNetwork>, ) -> TokenRetryInfo { let card_config = &state.conf.revenue_recovery.card_config; let card_network_config = card_config.get_network_config(network_type); let now = OffsetDateTime::now_utc(); let total_30_day_retries = Self::calculate_total_30_day_retries(token, today); let monthly_wait_hours = if total_30_day_retries >= card_network_config.max_retry_count_for_thirty_day { (0..RETRY_WINDOW_DAYS) .rev() .map(|i| today - Duration::days(i.into())) .find(|date| token.daily_retry_history.get(date).copied().unwrap_or(0) > 0) .map(|date| Self::calculate_wait_hours(date + Duration::days(31), now)) .unwrap_or(0) } else { 0 }; let today_retries = token .daily_retry_history .get(&today) .copied() .unwrap_or(INITIAL_RETRY_COUNT); let daily_wait_hours = if today_retries >= card_network_config.max_retries_per_day { Self::calculate_wait_hours(today + Duration::days(1), now) } else { 0 }; TokenRetryInfo { monthly_wait_hours, daily_wait_hours, total_30_day_retries, } } // Upsert payment processor token #[instrument(skip_all)] pub async fn upsert_payment_processor_token( state: &SessionState, connector_customer_id: &str, token_data: PaymentProcessorTokenStatus, ) -> CustomResult<bool, errors::StorageError> { let mut token_map = Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id) .await?; let token_id = token_data .payment_processor_token_details .payment_processor_token .clone(); let was_existing = token_map.contains_key(&token_id); let error_code = token_data.error_code.clone(); let today = OffsetDateTime::now_utc().date(); token_map .get_mut(&token_id) .map(|existing_token| { error_code.map(|err| existing_token.error_code = Some(err)); Self::normalize_retry_window(existing_token, today); for (date, &value) in &token_data.daily_retry_history { existing_token .daily_retry_history .entry(*date) .and_modify(|v| *v += value) .or_insert(value); } }) .or_else(|| { token_map.insert(token_id.clone(), token_data); None }); Self::update_or_add_connector_customer_payment_processor_tokens( state, connector_customer_id, token_map, ) .await?; tracing::debug!( connector_customer_id = connector_customer_id, "Upsert payment processor tokens", ); Ok(!was_existing) } // Update payment processor token error code with billing connector response #[instrument(skip_all)] pub async fn update_payment_processor_token_error_code_from_process_tracker( state: &SessionState, connector_customer_id: &str, error_code: &Option<String>, is_hard_decline: &Option<bool>, payment_processor_token_id: Option<&str>, ) -> CustomResult<bool, errors::StorageError> { let today = OffsetDateTime::now_utc().date(); let updated_token = match payment_processor_token_id { Some(token_id) => { Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id) .await? .values() .find(|status| { status .payment_processor_token_details .payment_processor_token == token_id }) .map(|status| PaymentProcessorTokenStatus { payment_processor_token_details: status .payment_processor_token_details .clone(), inserted_by_attempt_id: status.inserted_by_attempt_id.clone(), error_code: error_code.clone(), daily_retry_history: status.daily_retry_history.clone(), scheduled_at: None, is_hard_decline: *is_hard_decline, }) } None => None, }; match updated_token { Some(mut token) => { Self::normalize_retry_window(&mut token, today); match token.error_code { None => token.daily_retry_history.clear(), Some(_) => { let current_count = token .daily_retry_history .get(&today) .copied() .unwrap_or(INITIAL_RETRY_COUNT); token.daily_retry_history.insert(today, current_count + 1); } } let mut tokens_map = HashMap::new(); tokens_map.insert( token .payment_processor_token_details .payment_processor_token .clone(), token.clone(), ); Self::update_or_add_connector_customer_payment_processor_tokens( state, connector_customer_id, tokens_map, ) .await?; tracing::debug!( connector_customer_id = connector_customer_id, "Updated payment processor tokens with error code", ); Ok(true) } None => { tracing::debug!( connector_customer_id = connector_customer_id, "No Token found with token id to update error code", ); Ok(false) } } } // Update payment processor token schedule time #[instrument(skip_all)] pub async fn update_payment_processor_token_schedule_time( state: &SessionState, connector_customer_id: &str, payment_processor_token: &str, schedule_time: Option<PrimitiveDateTime>, ) -> CustomResult<bool, errors::StorageError> { let updated_token = Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id) .await? .values() .find(|status| { status .payment_processor_token_details .payment_processor_token == payment_processor_token }) .map(|status| PaymentProcessorTokenStatus { payment_processor_token_details: status.payment_processor_token_details.clone(), inserted_by_attempt_id: status.inserted_by_attempt_id.clone(), error_code: status.error_code.clone(), daily_retry_history: status.daily_retry_history.clone(), scheduled_at: schedule_time, is_hard_decline: status.is_hard_decline, }); match updated_token { Some(token) => { let mut tokens_map = HashMap::new(); tokens_map.insert( token .payment_processor_token_details .payment_processor_token .clone(), token.clone(), ); Self::update_or_add_connector_customer_payment_processor_tokens( state, connector_customer_id, tokens_map, ) .await?; tracing::debug!( connector_customer_id = connector_customer_id, "Updated payment processor tokens with schedule time", ); Ok(true) } None => { tracing::debug!( connector_customer_id = connector_customer_id, "payment processor tokens with not found", ); Ok(false) } } } // Get payment processor token with schedule time #[instrument(skip_all)] pub async fn get_payment_processor_token_with_schedule_time( state: &SessionState, connector_customer_id: &str, ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> { let tokens = Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id) .await?; let scheduled_token = tokens .values() .find(|status| status.scheduled_at.is_some()) .cloned(); tracing::debug!( connector_customer_id = connector_customer_id, "Fetched payment processor token with schedule time", ); Ok(scheduled_token) } // Get payment processor token using token id #[instrument(skip_all)] pub async fn get_payment_processor_token_using_token_id( state: &SessionState, connector_customer_id: &str, payment_processor_token: &str, ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> { // Get all tokens for the customer let tokens_map = Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id) .await?; let token_details = tokens_map.get(payment_processor_token).cloned(); tracing::debug!( token_found = token_details.is_some(), customer_id = connector_customer_id, "Fetched payment processor token & Checked existence ", ); Ok(token_details) } // Check if all tokens are hard declined or no token found for the customer #[instrument(skip_all)] pub async fn are_all_tokens_hard_declined( state: &SessionState, connector_customer_id: &str, ) -> CustomResult<bool, errors::StorageError> { let tokens_map = Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id) .await?; let all_hard_declined = tokens_map .values() .all(|token| token.is_hard_decline.unwrap_or(false)); tracing::debug!( connector_customer_id = connector_customer_id, all_hard_declined, "Checked if all tokens are hard declined or no token found for the customer", ); Ok(all_hard_declined) } // Get token based on retry type pub async fn get_token_based_on_retry_type( state: &SessionState, connector_customer_id: &str, retry_algorithm_type: RevenueRecoveryAlgorithmType, last_token_used: Option<&str>, ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> { let mut token = None; match retry_algorithm_type { RevenueRecoveryAlgorithmType::Monitoring => { logger::error!("Monitoring type found for Revenue Recovery retry payment"); } RevenueRecoveryAlgorithmType::Cascading => { token = match last_token_used { Some(token_id) => { Self::get_payment_processor_token_using_token_id( state, connector_customer_id, token_id, ) .await? } None => None, }; } RevenueRecoveryAlgorithmType::Smart => { token = Self::get_payment_processor_token_with_schedule_time( state, connector_customer_id, ) .await?; } } token = token.and_then(|t| { t.is_hard_decline .unwrap_or(false) .then(|| { logger::error!("Token is hard declined"); }) .map_or(Some(t), |_| None) }); Ok(token) } /// Get Redis key data for revenue recovery #[instrument(skip_all)] pub async fn get_redis_key_data_raw( state: &SessionState, connector_customer_id: &str, key_type: &RedisKeyType, ) -> CustomResult<(bool, i64, Option<serde_json::Value>), errors::StorageError> { let redis_conn = state .store .get_redis_conn() .change_context(errors::StorageError::RedisError( errors::RedisError::RedisConnectionError.into(), ))?; let redis_key = match key_type { RedisKeyType::Status => Self::get_connector_customer_lock_key(connector_customer_id), RedisKeyType::Tokens => Self::get_connector_customer_tokens_key(connector_customer_id), }; // Get TTL let ttl = redis_conn .get_ttl(&redis_key.clone().into()) .await .map_err(|error| { tracing::error!(operation = "get_ttl", err = ?error); errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into()) })?; // Get data based on key type and determine existence let (key_exists, data) = match key_type { RedisKeyType::Status => match redis_conn.get_key::<String>(&redis_key.into()).await { Ok(status_value) => (true, serde_json::Value::String(status_value)), Err(error) => { tracing::error!(operation = "get_status_key", err = ?error); ( false, serde_json::Value::String(format!( "Error retrieving status key: {}", error )), ) } }, RedisKeyType::Tokens => { match redis_conn .get_hash_fields::<HashMap<String, String>>(&redis_key.into()) .await { Ok(hash_fields) => { let exists = !hash_fields.is_empty(); let data = if exists { serde_json::to_value(hash_fields).unwrap_or(serde_json::Value::Null) } else { serde_json::Value::Object(serde_json::Map::new()) }; (exists, data) } Err(error) => { tracing::error!(operation = "get_tokens_hash", err = ?error); (false, serde_json::Value::Null) } } } }; tracing::debug!( connector_customer_id = connector_customer_id, key_type = ?key_type, exists = key_exists, ttl = ttl, "Retrieved Redis key data" ); Ok((key_exists, ttl, Some(data))) } /// Update Redis token with comprehensive card data #[instrument(skip_all)] pub async fn update_redis_token_with_comprehensive_card_data( state: &SessionState, customer_id: &str, token: &str, card_data: &revenue_recovery_data_backfill::ComprehensiveCardData, cutoff_datetime: Option<PrimitiveDateTime>, ) -> CustomResult<(), errors::StorageError> { // Get existing token data let mut token_map = Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?; // Find the token to update let existing_token = token_map.get_mut(token).ok_or_else(|| { tracing::warn!( customer_id = customer_id, "Token not found in parsed Redis data - may be corrupted or missing for " ); error_stack::Report::new(errors::StorageError::ValueNotFound( "Token not found in Redis".to_string(), )) })?; // Update the token details with new card data card_data.card_type.as_ref().map(|card_type| { existing_token.payment_processor_token_details.card_type = Some(card_type.clone()) }); card_data.card_exp_month.as_ref().map(|exp_month| { existing_token.payment_processor_token_details.expiry_month = Some(exp_month.clone()) }); card_data.card_exp_year.as_ref().map(|exp_year| { existing_token.payment_processor_token_details.expiry_year = Some(exp_year.clone()) }); card_data.card_network.as_ref().map(|card_network| { existing_token.payment_processor_token_details.card_network = Some(card_network.clone()) }); card_data.card_issuer.as_ref().map(|card_issuer| { existing_token.payment_processor_token_details.card_issuer = Some(card_issuer.clone()) }); // Update daily retry history if provided card_data .daily_retry_history .as_ref() .map(|retry_history| existing_token.daily_retry_history = retry_history.clone()); // If cutoff_datetime is provided and existing scheduled_at < cutoff_datetime, set to None // If no scheduled_at value exists, leave it as None existing_token.scheduled_at = existing_token .scheduled_at .and_then(|existing_scheduled_at| { cutoff_datetime .map(|cutoff| { if existing_scheduled_at < cutoff { tracing::info!( customer_id = customer_id, existing_scheduled_at = %existing_scheduled_at, cutoff_datetime = %cutoff, "Set scheduled_at to None because existing time is before cutoff time" ); None } else { Some(existing_scheduled_at) } }) .unwrap_or(Some(existing_scheduled_at)) // No cutoff provided, keep existing value }); // Save the updated token map back to Redis Self::update_or_add_connector_customer_payment_processor_tokens( state, customer_id, token_map, ) .await?; tracing::info!( customer_id = customer_id, "Updated Redis token data with comprehensive card data using struct" ); Ok(()) } }
{ "crate": "router", "file": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_router_2864769865326053381
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/storage/payment_method.rs // Contains: 7 structs, 4 enums use api_models::payment_methods; use diesel_models::enums; pub use diesel_models::payment_method::{ PaymentMethod, PaymentMethodNew, PaymentMethodUpdate, PaymentMethodUpdateInternal, TokenizeCoreWorkflow, }; use crate::types::{api, domain}; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum PaymentTokenKind { Temporary, Permanent, } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct CardTokenData { pub payment_method_id: Option<String>, pub locker_id: Option<String>, pub token: String, pub network_token_locker_id: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct CardTokenData { pub payment_method_id: common_utils::id_type::GlobalPaymentMethodId, pub locker_id: Option<String>, pub token: String, } #[derive(Debug, Clone, serde::Serialize, Default, serde::Deserialize)] pub struct PaymentMethodDataWithId { pub payment_method: Option<enums::PaymentMethod>, pub payment_method_data: Option<domain::PaymentMethodData>, pub payment_method_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GenericTokenData { pub token: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct WalletTokenData { pub payment_method_id: String, } #[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 Temporary(GenericTokenData), TemporaryGeneric(GenericTokenData), Permanent(CardTokenData), PermanentCard(CardTokenData), AuthBankDebit(payment_methods::BankAccountTokenData), WalletToken(WalletTokenData), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(tag = "kind", rename_all = "snake_case")] #[cfg(feature = "v2")] pub enum PaymentTokenData { TemporaryGeneric(GenericTokenData), PermanentCard(CardTokenData), AuthBankDebit(payment_methods::BankAccountTokenData), } impl PaymentTokenData { #[cfg(feature = "v1")] pub fn permanent_card( payment_method_id: Option<String>, locker_id: Option<String>, token: String, network_token_locker_id: Option<String>, ) -> Self { Self::PermanentCard(CardTokenData { payment_method_id, locker_id, token, network_token_locker_id, }) } #[cfg(feature = "v2")] pub fn permanent_card( payment_method_id: common_utils::id_type::GlobalPaymentMethodId, locker_id: Option<String>, token: String, ) -> Self { Self::PermanentCard(CardTokenData { payment_method_id, locker_id, token, }) } pub fn temporary_generic(token: String) -> Self { 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(feature = "v2")] pub fn is_permanent_card(&self) -> bool { matches!(self, Self::PermanentCard(_)) } } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodListContext { pub card_details: Option<api::CardDetailFromLocker>, pub hyperswitch_token_data: Option<PaymentTokenData>, #[cfg(feature = "payouts")] pub bank_transfer_details: Option<api::BankPayout>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub enum PaymentMethodListContext { Card { card_details: api::CardDetailFromLocker, // TODO: Why can't these fields be mandatory? token_data: Option<PaymentTokenData>, }, Bank { token_data: Option<PaymentTokenData>, }, #[cfg(feature = "payouts")] BankTransfer { bank_transfer_details: api::BankPayout, token_data: Option<PaymentTokenData>, }, TemporaryToken { token_data: Option<PaymentTokenData>, }, } #[cfg(feature = "v2")] impl PaymentMethodListContext { pub(crate) fn get_token_data(&self) -> Option<PaymentTokenData> { match self { Self::Card { token_data, .. } | Self::Bank { token_data } | Self::BankTransfer { token_data, .. } | Self::TemporaryToken { token_data } => token_data.clone(), } } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentMethodStatusTrackingData { pub payment_method_id: String, pub prev_status: enums::PaymentMethodStatus, pub curr_status: enums::PaymentMethodStatus, pub merchant_id: common_utils::id_type::MerchantId, }
{ "crate": "router", "file": "crates/router/src/types/storage/payment_method.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 4, "num_structs": 7, "num_tables": null, "score": null, "total_crates": null }
file_router_-4284986983481416589
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/storage/revenue_recovery.rs // Contains: 6 structs, 0 enums use std::{collections::HashMap, fmt::Debug}; use common_enums::enums::{self, CardNetwork}; use common_utils::{date_time, ext_traits::ValueExt, id_type}; use error_stack::ResultExt; 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, PaymentStatusData}, }; use masking::PeekInterface; use router_env::logger; use serde::{Deserialize, Serialize}; use crate::{db::StorageInterface, routes::SessionState, types, 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, pub invoice_scheduled_time: Option<time::PrimitiveDateTime>, } #[derive(Debug, Clone)] pub struct RevenueRecoveryPaymentData { pub merchant_account: merchant_account::MerchantAccount, pub profile: business_profile::Profile, pub key_store: merchant_key_store::MerchantKeyStore, pub billing_mca: merchant_connector_account::MerchantConnectorAccount, pub retry_algorithm: enums::RevenueRecoveryAlgorithmType, pub psync_data: Option<PaymentStatusData<types::api::PSync>>, } impl RevenueRecoveryPaymentData { pub async fn get_schedule_time_based_on_retry_type( &self, state: &SessionState, merchant_id: &id_type::MerchantId, retry_count: i32, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, is_hard_decline: bool, ) -> Option<time::PrimitiveDateTime> { if is_hard_decline { logger::info!("Hard Decline encountered"); return None; } match self.retry_algorithm { enums::RevenueRecoveryAlgorithmType::Monitoring => { logger::error!("Monitoring type found for Revenue Recovery retry payment"); None } enums::RevenueRecoveryAlgorithmType::Cascading => { logger::info!("Cascading type found for Revenue Recovery retry payment"); revenue_recovery::get_schedule_time_to_retry_mit_payments( state.store.as_ref(), merchant_id, retry_count, ) .await } enums::RevenueRecoveryAlgorithmType::Smart => None, } } } #[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, pub card_config: RetryLimitsConfig, pub redis_ttl_in_seconds: i64, } #[derive(Debug, serde::Deserialize, Clone)] pub struct RecoveryTimestamp { pub initial_timestamp_in_seconds: i64, pub job_schedule_buffer_time_in_seconds: i64, pub reopen_workflow_buffer_time_in_seconds: i64, pub max_random_schedule_delay_in_seconds: i64, pub redis_ttl_buffer_in_seconds: i64, } impl Default for RecoveryTimestamp { fn default() -> Self { Self { initial_timestamp_in_seconds: 1, job_schedule_buffer_time_in_seconds: 15, reopen_workflow_buffer_time_in_seconds: 60, max_random_schedule_delay_in_seconds: 300, redis_ttl_buffer_in_seconds: 300, } } } #[derive(Debug, serde::Deserialize, Clone, Default)] pub struct RetryLimitsConfig(pub HashMap<CardNetwork, NetworkRetryConfig>); #[derive(Debug, serde::Deserialize, Clone, Default)] pub struct NetworkRetryConfig { pub max_retries_per_day: i32, pub max_retry_count_for_thirty_day: i32, } impl RetryLimitsConfig { pub fn get_network_config(&self, network: Option<CardNetwork>) -> &NetworkRetryConfig { // Hardcoded fallback default config static DEFAULT_CONFIG: NetworkRetryConfig = NetworkRetryConfig { max_retries_per_day: 20, max_retry_count_for_thirty_day: 20, }; if let Some(net) = network { self.0.get(&net).unwrap_or(&DEFAULT_CONFIG) } else { self.0.get(&CardNetwork::Visa).unwrap_or(&DEFAULT_CONFIG) } } }
{ "crate": "router", "file": "crates/router/src/types/storage/revenue_recovery.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 6, "num_tables": null, "score": null, "total_crates": null }
file_router_8414076604994798444
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/api/connector_mapping.rs // Contains: 1 structs, 1 enums use std::str::FromStr; use error_stack::{report, ResultExt}; use hyperswitch_connectors::connectors::{Paytm, Phonepe}; use crate::{ configs::settings::Connectors, connector, core::errors::{self, CustomResult}, services::connector_integration_interface::ConnectorEnum, types::{self, api::enums}, }; /// Routing algorithm will output merchant connector identifier instead of connector name /// In order to support backwards compatibility for older routing algorithms and merchant accounts /// the support for connector name is retained #[derive(Clone, Debug)] pub struct ConnectorData { pub connector: ConnectorEnum, pub connector_name: types::Connector, pub get_token: GetToken, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } // Normal flow will call the connector and follow the flow specific operations (capture, authorize) // SessionTokenFromMetadata will avoid calling the connector instead create the session token ( for sdk ) #[derive(Clone, Eq, PartialEq, Debug)] pub enum GetToken { GpayMetadata, SamsungPayMetadata, AmazonPayMetadata, ApplePayMetadata, PaypalSdkMetadata, PazeMetadata, Connector, } impl ConnectorData { pub fn get_connector_by_name( _connectors: &Connectors, name: &str, connector_type: GetToken, connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, ) -> CustomResult<Self, errors::ApiErrorResponse> { let connector = Self::convert_connector(name)?; let connector_name = enums::Connector::from_str(name) .change_context(errors::ConnectorError::InvalidConnectorName) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("unable to parse connector name {name}"))?; Ok(Self { connector, connector_name, get_token: connector_type, merchant_connector_id: connector_id, }) } #[cfg(feature = "payouts")] pub fn get_payout_connector_by_name( _connectors: &Connectors, name: &str, connector_type: GetToken, connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, ) -> CustomResult<Self, errors::ApiErrorResponse> { let connector = Self::convert_connector(name)?; let payout_connector_name = enums::PayoutConnectors::from_str(name) .change_context(errors::ConnectorError::InvalidConnectorName) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("unable to parse payout connector name {name}"))?; let connector_name = enums::Connector::from(payout_connector_name); Ok(Self { connector, connector_name, get_token: connector_type, merchant_connector_id: connector_id, }) } pub fn get_external_vault_connector_by_name( _connectors: &Connectors, connector: String, connector_type: GetToken, connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, ) -> CustomResult<Self, errors::ApiErrorResponse> { let connector_enum = Self::convert_connector(&connector)?; let external_vault_connector_name = enums::VaultConnectors::from_str(&connector) .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 = enums::Connector::from(external_vault_connector_name); Ok(Self { connector: connector_enum, connector_name, get_token: connector_type, merchant_connector_id: connector_id, }) } pub fn convert_connector( connector_name: &str, ) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> { match enums::Connector::from_str(connector_name) { Ok(name) => match name { enums::Connector::Aci => Ok(ConnectorEnum::Old(Box::new(connector::Aci::new()))), enums::Connector::Adyen => { Ok(ConnectorEnum::Old(Box::new(connector::Adyen::new()))) } enums::Connector::Affirm => { Ok(ConnectorEnum::Old(Box::new(connector::Affirm::new()))) } enums::Connector::Adyenplatform => Ok(ConnectorEnum::Old(Box::new( connector::Adyenplatform::new(), ))), enums::Connector::Airwallex => { Ok(ConnectorEnum::Old(Box::new(connector::Airwallex::new()))) } enums::Connector::Amazonpay => { Ok(ConnectorEnum::Old(Box::new(connector::Amazonpay::new()))) } enums::Connector::Archipel => { Ok(ConnectorEnum::Old(Box::new(connector::Archipel::new()))) } enums::Connector::Authipay => { Ok(ConnectorEnum::Old(Box::new(connector::Authipay::new()))) } enums::Connector::Authorizedotnet => Ok(ConnectorEnum::Old(Box::new( connector::Authorizedotnet::new(), ))), enums::Connector::Bambora => { Ok(ConnectorEnum::Old(Box::new(connector::Bambora::new()))) } enums::Connector::Bamboraapac => { Ok(ConnectorEnum::Old(Box::new(connector::Bamboraapac::new()))) } enums::Connector::Bankofamerica => Ok(ConnectorEnum::Old(Box::new( connector::Bankofamerica::new(), ))), enums::Connector::Barclaycard => { Ok(ConnectorEnum::Old(Box::new(connector::Barclaycard::new()))) } enums::Connector::Billwerk => { Ok(ConnectorEnum::Old(Box::new(connector::Billwerk::new()))) } enums::Connector::Bitpay => { Ok(ConnectorEnum::Old(Box::new(connector::Bitpay::new()))) } enums::Connector::Blackhawknetwork => Ok(ConnectorEnum::Old(Box::new( connector::Blackhawknetwork::new(), ))), enums::Connector::Bluesnap => { Ok(ConnectorEnum::Old(Box::new(connector::Bluesnap::new()))) } enums::Connector::Calida => { Ok(ConnectorEnum::Old(Box::new(connector::Calida::new()))) } enums::Connector::Boku => Ok(ConnectorEnum::Old(Box::new(connector::Boku::new()))), enums::Connector::Braintree => { Ok(ConnectorEnum::Old(Box::new(connector::Braintree::new()))) } enums::Connector::Breadpay => { Ok(ConnectorEnum::Old(Box::new(connector::Breadpay::new()))) } enums::Connector::Cashtocode => { Ok(ConnectorEnum::Old(Box::new(connector::Cashtocode::new()))) } enums::Connector::Celero => { Ok(ConnectorEnum::Old(Box::new(connector::Celero::new()))) } enums::Connector::Chargebee => { Ok(ConnectorEnum::Old(Box::new(connector::Chargebee::new()))) } enums::Connector::Checkbook => { Ok(ConnectorEnum::Old(Box::new(connector::Checkbook::new()))) } enums::Connector::Checkout => { Ok(ConnectorEnum::Old(Box::new(connector::Checkout::new()))) } enums::Connector::Coinbase => { Ok(ConnectorEnum::Old(Box::new(connector::Coinbase::new()))) } enums::Connector::Coingate => { Ok(ConnectorEnum::Old(Box::new(connector::Coingate::new()))) } enums::Connector::Cryptopay => { Ok(ConnectorEnum::Old(Box::new(connector::Cryptopay::new()))) } enums::Connector::CtpMastercard => { Ok(ConnectorEnum::Old(Box::new(&connector::CtpMastercard))) } enums::Connector::Custombilling => Ok(ConnectorEnum::Old(Box::new( connector::Custombilling::new(), ))), enums::Connector::CtpVisa => Ok(ConnectorEnum::Old(Box::new( connector::UnifiedAuthenticationService::new(), ))), enums::Connector::Cybersource => { Ok(ConnectorEnum::Old(Box::new(connector::Cybersource::new()))) } enums::Connector::Datatrans => { Ok(ConnectorEnum::Old(Box::new(connector::Datatrans::new()))) } enums::Connector::Deutschebank => { Ok(ConnectorEnum::Old(Box::new(connector::Deutschebank::new()))) } enums::Connector::Digitalvirgo => { Ok(ConnectorEnum::Old(Box::new(connector::Digitalvirgo::new()))) } enums::Connector::Dlocal => { Ok(ConnectorEnum::Old(Box::new(connector::Dlocal::new()))) } #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector1 => Ok(ConnectorEnum::Old(Box::new( connector::DummyConnector::<1>::new(), ))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector2 => Ok(ConnectorEnum::Old(Box::new( connector::DummyConnector::<2>::new(), ))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector3 => Ok(ConnectorEnum::Old(Box::new( connector::DummyConnector::<3>::new(), ))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector4 => Ok(ConnectorEnum::Old(Box::new( connector::DummyConnector::<4>::new(), ))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector5 => Ok(ConnectorEnum::Old(Box::new( connector::DummyConnector::<5>::new(), ))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector6 => Ok(ConnectorEnum::Old(Box::new( connector::DummyConnector::<6>::new(), ))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector7 => Ok(ConnectorEnum::Old(Box::new( connector::DummyConnector::<7>::new(), ))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyBillingConnector => Ok(ConnectorEnum::Old(Box::new( connector::DummyConnector::<8>::new(), ))), enums::Connector::Dwolla => { Ok(ConnectorEnum::Old(Box::new(connector::Dwolla::new()))) } enums::Connector::Ebanx => { Ok(ConnectorEnum::Old(Box::new(connector::Ebanx::new()))) } enums::Connector::Elavon => { Ok(ConnectorEnum::Old(Box::new(connector::Elavon::new()))) } enums::Connector::Facilitapay => { Ok(ConnectorEnum::Old(Box::new(connector::Facilitapay::new()))) } enums::Connector::Finix => { Ok(ConnectorEnum::Old(Box::new(connector::Finix::new()))) } enums::Connector::Fiserv => { Ok(ConnectorEnum::Old(Box::new(connector::Fiserv::new()))) } enums::Connector::Fiservemea => { Ok(ConnectorEnum::Old(Box::new(connector::Fiservemea::new()))) } enums::Connector::Fiuu => Ok(ConnectorEnum::Old(Box::new(connector::Fiuu::new()))), enums::Connector::Flexiti => { Ok(ConnectorEnum::Old(Box::new(connector::Flexiti::new()))) } enums::Connector::Forte => { Ok(ConnectorEnum::Old(Box::new(connector::Forte::new()))) } enums::Connector::Getnet => { Ok(ConnectorEnum::Old(Box::new(connector::Getnet::new()))) } enums::Connector::Gigadat => { Ok(ConnectorEnum::Old(Box::new(connector::Gigadat::new()))) } enums::Connector::Globalpay => { Ok(ConnectorEnum::Old(Box::new(connector::Globalpay::new()))) } enums::Connector::Globepay => { Ok(ConnectorEnum::Old(Box::new(connector::Globepay::new()))) } enums::Connector::Gocardless => { Ok(ConnectorEnum::Old(Box::new(connector::Gocardless::new()))) } enums::Connector::Hipay => { Ok(ConnectorEnum::Old(Box::new(connector::Hipay::new()))) } enums::Connector::Helcim => { Ok(ConnectorEnum::Old(Box::new(connector::Helcim::new()))) } enums::Connector::HyperswitchVault => { Ok(ConnectorEnum::Old(Box::new(&connector::HyperswitchVault))) } enums::Connector::Iatapay => { Ok(ConnectorEnum::Old(Box::new(connector::Iatapay::new()))) } enums::Connector::Inespay => { Ok(ConnectorEnum::Old(Box::new(connector::Inespay::new()))) } enums::Connector::Itaubank => { Ok(ConnectorEnum::Old(Box::new(connector::Itaubank::new()))) } enums::Connector::Jpmorgan => { Ok(ConnectorEnum::Old(Box::new(connector::Jpmorgan::new()))) } enums::Connector::Juspaythreedsserver => Ok(ConnectorEnum::Old(Box::new( connector::Juspaythreedsserver::new(), ))), enums::Connector::Klarna => { Ok(ConnectorEnum::Old(Box::new(connector::Klarna::new()))) } enums::Connector::Loonio => { Ok(ConnectorEnum::Old(Box::new(connector::Loonio::new()))) } enums::Connector::Mollie => { // enums::Connector::Moneris => Ok(ConnectorEnum::Old(Box::new(connector::Moneris))), Ok(ConnectorEnum::Old(Box::new(connector::Mollie::new()))) } enums::Connector::Moneris => { Ok(ConnectorEnum::Old(Box::new(connector::Moneris::new()))) } enums::Connector::Nexixpay => { Ok(ConnectorEnum::Old(Box::new(connector::Nexixpay::new()))) } enums::Connector::Nmi => Ok(ConnectorEnum::Old(Box::new(connector::Nmi::new()))), enums::Connector::Nomupay => { 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()))) } enums::Connector::Nuvei => { Ok(ConnectorEnum::Old(Box::new(connector::Nuvei::new()))) } enums::Connector::Opennode => { Ok(ConnectorEnum::Old(Box::new(connector::Opennode::new()))) } enums::Connector::Paybox => { Ok(ConnectorEnum::Old(Box::new(connector::Paybox::new()))) } // "payeezy" => Ok(ConnectorIntegrationEnum::Old(Box::new(&connector::Payeezy)), As psync and rsync are not supported by this connector, it is added as template code for future usage // enums::Connector::Payload => { // Ok(ConnectorEnum::Old(Box::new(connector::Paybload::new()))) // } enums::Connector::Payload => { Ok(ConnectorEnum::Old(Box::new(connector::Payload::new()))) } enums::Connector::Payme => { Ok(ConnectorEnum::Old(Box::new(connector::Payme::new()))) } enums::Connector::Payone => { Ok(ConnectorEnum::Old(Box::new(connector::Payone::new()))) } enums::Connector::Payu => Ok(ConnectorEnum::Old(Box::new(connector::Payu::new()))), enums::Connector::Peachpayments => Ok(ConnectorEnum::Old(Box::new( hyperswitch_connectors::connectors::Peachpayments::new(), ))), enums::Connector::Placetopay => { Ok(ConnectorEnum::Old(Box::new(connector::Placetopay::new()))) } enums::Connector::Powertranz => { Ok(ConnectorEnum::Old(Box::new(connector::Powertranz::new()))) } enums::Connector::Prophetpay => { Ok(ConnectorEnum::Old(Box::new(&connector::Prophetpay))) } enums::Connector::Razorpay => { Ok(ConnectorEnum::Old(Box::new(connector::Razorpay::new()))) } enums::Connector::Rapyd => { Ok(ConnectorEnum::Old(Box::new(connector::Rapyd::new()))) } enums::Connector::Recurly => { Ok(ConnectorEnum::New(Box::new(connector::Recurly::new()))) } enums::Connector::Redsys => { Ok(ConnectorEnum::Old(Box::new(connector::Redsys::new()))) } enums::Connector::Santander => { Ok(ConnectorEnum::Old(Box::new(connector::Santander::new()))) } enums::Connector::Shift4 => { Ok(ConnectorEnum::Old(Box::new(connector::Shift4::new()))) } enums::Connector::Silverflow => { Ok(ConnectorEnum::Old(Box::new(connector::Silverflow::new()))) } enums::Connector::Square => Ok(ConnectorEnum::Old(Box::new(&connector::Square))), enums::Connector::Stax => Ok(ConnectorEnum::Old(Box::new(&connector::Stax))), enums::Connector::Stripe => { Ok(ConnectorEnum::Old(Box::new(connector::Stripe::new()))) } enums::Connector::Stripebilling => Ok(ConnectorEnum::Old(Box::new( connector::Stripebilling::new(), ))), enums::Connector::Wise => Ok(ConnectorEnum::Old(Box::new(connector::Wise::new()))), enums::Connector::Worldline => { Ok(ConnectorEnum::Old(Box::new(&connector::Worldline))) } enums::Connector::Worldpay => { Ok(ConnectorEnum::Old(Box::new(connector::Worldpay::new()))) } enums::Connector::Worldpayvantiv => Ok(ConnectorEnum::Old(Box::new( connector::Worldpayvantiv::new(), ))), enums::Connector::Worldpayxml => { Ok(ConnectorEnum::Old(Box::new(connector::Worldpayxml::new()))) } enums::Connector::Xendit => { Ok(ConnectorEnum::Old(Box::new(connector::Xendit::new()))) } enums::Connector::Mifinity => { Ok(ConnectorEnum::Old(Box::new(connector::Mifinity::new()))) } enums::Connector::Multisafepay => { Ok(ConnectorEnum::Old(Box::new(connector::Multisafepay::new()))) } enums::Connector::Netcetera => { Ok(ConnectorEnum::Old(Box::new(&connector::Netcetera))) } enums::Connector::Nexinets => { Ok(ConnectorEnum::Old(Box::new(&connector::Nexinets))) } // enums::Connector::Nexixpay => { // Ok(ConnectorEnum::Old(Box::new(&connector::Nexixpay))) // } enums::Connector::Paypal => { Ok(ConnectorEnum::Old(Box::new(connector::Paypal::new()))) } enums::Connector::Paysafe => { Ok(ConnectorEnum::Old(Box::new(connector::Paysafe::new()))) } enums::Connector::Paystack => { Ok(ConnectorEnum::Old(Box::new(connector::Paystack::new()))) } // enums::Connector::Thunes => Ok(ConnectorEnum::Old(Box::new(connector::Thunes))), enums::Connector::Tesouro => { Ok(ConnectorEnum::Old(Box::new(connector::Tesouro::new()))) } enums::Connector::Tokenex => Ok(ConnectorEnum::Old(Box::new(&connector::Tokenex))), enums::Connector::Tokenio => { Ok(ConnectorEnum::Old(Box::new(connector::Tokenio::new()))) } enums::Connector::Trustpay => { Ok(ConnectorEnum::Old(Box::new(connector::Trustpay::new()))) } enums::Connector::Trustpayments => Ok(ConnectorEnum::Old(Box::new( connector::Trustpayments::new(), ))), enums::Connector::Tsys => Ok(ConnectorEnum::Old(Box::new(connector::Tsys::new()))), // enums::Connector::UnifiedAuthenticationService => Ok(ConnectorEnum::Old(Box::new( // connector::UnifiedAuthenticationService, // ))), enums::Connector::Vgs => Ok(ConnectorEnum::Old(Box::new(&connector::Vgs))), enums::Connector::Volt => Ok(ConnectorEnum::Old(Box::new(connector::Volt::new()))), enums::Connector::Wellsfargo => { Ok(ConnectorEnum::Old(Box::new(connector::Wellsfargo::new()))) } // enums::Connector::Wellsfargopayout => { // Ok(Box::new(connector::Wellsfargopayout::new())) // } enums::Connector::Zen => Ok(ConnectorEnum::Old(Box::new(&connector::Zen))), enums::Connector::Zsl => Ok(ConnectorEnum::Old(Box::new(&connector::Zsl))), enums::Connector::Plaid => { Ok(ConnectorEnum::Old(Box::new(connector::Plaid::new()))) } enums::Connector::Signifyd | enums::Connector::Riskified | enums::Connector::Gpayments | enums::Connector::Threedsecureio | enums::Connector::Cardinal | enums::Connector::Taxjar => { Err(report!(errors::ConnectorError::InvalidConnectorName) .attach_printable(format!("invalid connector name: {connector_name}"))) .change_context(errors::ApiErrorResponse::InternalServerError) } enums::Connector::Phonepe => Ok(ConnectorEnum::Old(Box::new(Phonepe::new()))), enums::Connector::Paytm => Ok(ConnectorEnum::Old(Box::new(Paytm::new()))), }, Err(_) => Err(report!(errors::ConnectorError::InvalidConnectorName) .attach_printable(format!("invalid connector name: {connector_name}"))) .change_context(errors::ApiErrorResponse::InternalServerError), } } }
{ "crate": "router", "file": "crates/router/src/types/api/connector_mapping.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_6350916903989931761
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/api/fraud_check.rs // Contains: 2 structs, 0 enums use std::str::FromStr; use api_models::enums; use common_utils::errors::CustomResult; use error_stack::ResultExt; pub use hyperswitch_domain_models::router_flow_types::fraud_check::{ Checkout, Fulfillment, RecordReturn, Sale, Transaction, }; pub use hyperswitch_interfaces::api::fraud_check::{ FraudCheckCheckout, FraudCheckFulfillment, FraudCheckRecordReturn, FraudCheckSale, FraudCheckTransaction, }; pub use super::fraud_check_v2::{ FraudCheckCheckoutV2, FraudCheckFulfillmentV2, FraudCheckRecordReturnV2, FraudCheckSaleV2, FraudCheckTransactionV2, FraudCheckV2, }; use super::{ConnectorData, SessionConnectorDatas}; use crate::{ connector, core::{errors, payments::ActionType}, services::connector_integration_interface::ConnectorEnum, }; #[derive(Clone)] pub struct FraudCheckConnectorData { pub connector: ConnectorEnum, pub connector_name: enums::FrmConnectors, } pub enum ConnectorCallType { PreDetermined(ConnectorRoutingData), Retryable(Vec<ConnectorRoutingData>), SessionMultiple(SessionConnectorDatas), } #[derive(Clone)] pub struct ConnectorRoutingData { pub connector_data: ConnectorData, pub network: Option<common_enums::CardNetwork>, // action_type is used for mandates currently pub action_type: Option<ActionType>, } impl FraudCheckConnectorData { pub fn get_connector_by_name(name: &str) -> CustomResult<Self, errors::ApiErrorResponse> { let connector_name = enums::FrmConnectors::from_str(name) .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven) .attach_printable_lazy(|| { format!("unable to parse connector: {:?}", name.to_string()) })?; let connector = Self::convert_connector(connector_name)?; Ok(Self { connector, connector_name, }) } fn convert_connector( connector_name: enums::FrmConnectors, ) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> { match connector_name { enums::FrmConnectors::Signifyd => { Ok(ConnectorEnum::Old(Box::new(&connector::Signifyd))) } enums::FrmConnectors::Riskified => { Ok(ConnectorEnum::Old(Box::new(connector::Riskified::new()))) } } } }
{ "crate": "router", "file": "crates/router/src/types/api/fraud_check.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_router_5089349197498657528
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/api/configs.rs // Contains: 2 structs, 0 enums #[derive(Clone, serde::Serialize, Debug, serde::Deserialize)] pub struct Config { pub key: String, pub value: String, } #[derive(Clone, serde::Deserialize, Debug, serde::Serialize)] pub struct ConfigUpdate { #[serde(skip_deserializing)] pub key: String, pub value: String, }
{ "crate": "router", "file": "crates/router/src/types/api/configs.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_router_-748368895273374639
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/api/disputes.rs // Contains: 6 structs, 1 enums pub use hyperswitch_interfaces::{ api::disputes::{ AcceptDispute, DefendDispute, Dispute, DisputeSync, FetchDisputes, SubmitEvidence, }, disputes::DisputePayload, }; use masking::{Deserialize, Serialize}; use crate::types; #[derive(Default, Debug, Deserialize, Serialize)] pub struct DisputeId { pub dispute_id: String, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct DisputeFetchQueryData { pub fetch_from: String, pub fetch_till: String, } pub use hyperswitch_domain_models::router_flow_types::dispute::{ Accept, Defend, Dsync, Evidence, Fetch, }; pub use super::disputes_v2::{ AcceptDisputeV2, DefendDisputeV2, DisputeSyncV2, DisputeV2, FetchDisputesV2, SubmitEvidenceV2, }; #[derive(Default, Debug, Deserialize, Serialize)] pub struct DisputeEvidence { pub cancellation_policy: Option<String>, pub customer_communication: Option<String>, pub customer_signature: Option<String>, pub receipt: Option<String>, pub refund_policy: Option<String>, pub service_documentation: Option<String>, pub shipping_documentation: Option<String>, pub invoice_showing_distinct_transactions: Option<String>, pub recurring_transaction_agreement: Option<String>, pub uncategorized_file: Option<String>, } #[derive(Debug, Clone, Serialize)] pub struct AttachEvidenceRequest { pub create_file_request: types::api::CreateFileRequest, pub evidence_type: EvidenceType, } #[derive(Debug, serde::Deserialize, strum::Display, strum::EnumString, Clone, serde::Serialize)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EvidenceType { CancellationPolicy, CustomerCommunication, CustomerSignature, Receipt, RefundPolicy, ServiceDocumentation, ShippingDocumentation, InvoiceShowingDistinctTransactions, RecurringTransactionAgreement, UncategorizedFile, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ProcessDisputePTData { pub connector_name: String, pub dispute_payload: types::DisputeSyncResponse, pub merchant_id: common_utils::id_type::MerchantId, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct DisputeListPTData { pub connector_name: String, pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, pub merchant_id: common_utils::id_type::MerchantId, pub profile_id: common_utils::id_type::ProfileId, pub created_from: time::PrimitiveDateTime, pub created_till: time::PrimitiveDateTime, }
{ "crate": "router", "file": "crates/router/src/types/api/disputes.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 6, "num_tables": null, "score": null, "total_crates": null }
file_router_819086509798805167
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/api/files.rs // Contains: 3 structs, 1 enums use api_models::enums::FileUploadProvider; pub use hyperswitch_domain_models::router_flow_types::files::{Retrieve, Upload}; pub use hyperswitch_interfaces::api::files::{FilePurpose, FileUpload, RetrieveFile, UploadFile}; use masking::{Deserialize, Serialize}; use serde_with::serde_as; pub use super::files_v2::{FileUploadV2, RetrieveFileV2, UploadFileV2}; use crate::{ core::errors, types::{self, transformers::ForeignTryFrom}, }; #[derive(Default, Debug, Deserialize, Serialize)] pub struct FileId { pub file_id: String, } #[derive(Default, Debug, Deserialize, Serialize)] pub struct FileRetrieveRequest { pub file_id: String, pub dispute_id: Option<String>, } #[derive(Debug)] pub enum FileDataRequired { Required, NotRequired, } impl ForeignTryFrom<FileUploadProvider> for types::Connector { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from(item: FileUploadProvider) -> Result<Self, Self::Error> { match item { FileUploadProvider::Stripe => Ok(Self::Stripe), FileUploadProvider::Checkout => Ok(Self::Checkout), FileUploadProvider::Worldpayvantiv => Ok(Self::Worldpayvantiv), FileUploadProvider::Router => Err(errors::ApiErrorResponse::NotSupported { message: "File upload provider is not a connector".to_owned(), } .into()), } } } impl ForeignTryFrom<&types::Connector> for FileUploadProvider { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from(item: &types::Connector) -> Result<Self, Self::Error> { match *item { types::Connector::Stripe => Ok(Self::Stripe), types::Connector::Checkout => Ok(Self::Checkout), types::Connector::Worldpayvantiv => Ok(Self::Worldpayvantiv), _ => Err(errors::ApiErrorResponse::NotSupported { message: "Connector not supported as file provider".to_owned(), } .into()), } } } #[serde_as] #[derive(Debug, Clone, serde::Serialize)] pub struct CreateFileRequest { pub file: Vec<u8>, pub file_name: Option<String>, pub file_size: i32, #[serde_as(as = "serde_with::DisplayFromStr")] pub file_type: mime::Mime, pub purpose: FilePurpose, pub dispute_id: Option<String>, }
{ "crate": "router", "file": "crates/router/src/types/api/files.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_router_-869961563489485431
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/api/verify_connector.rs // Contains: 1 structs, 0 enums pub mod paypal; pub mod stripe; use error_stack::ResultExt; use crate::{ consts, core::errors, services::{ self, connector_integration_interface::{BoxedConnectorIntegrationInterface, ConnectorEnum}, }, types::{self, api, api::ConnectorCommon, domain, storage::enums as storage_enums}, SessionState, }; #[derive(Clone)] pub struct VerifyConnectorData { pub connector: ConnectorEnum, pub connector_auth: types::ConnectorAuthType, pub card_details: domain::Card, } impl VerifyConnectorData { fn get_payment_authorize_data(&self) -> types::PaymentsAuthorizeData { types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(self.card_details.clone()), email: None, customer_name: None, amount: 1000, minor_amount: common_utils::types::MinorUnit::new(1000), confirm: true, order_tax_amount: None, currency: storage_enums::Currency::USD, metadata: None, mandate_id: None, webhook_url: None, customer_id: None, off_session: None, browser_info: None, session_token: None, order_details: None, order_category: None, capture_method: None, enrolled_for_3ds: false, router_return_url: None, surcharge_details: None, setup_future_usage: None, payment_experience: None, payment_method_type: None, statement_descriptor: None, setup_mandate_details: None, complete_authorize_url: None, related_transaction_id: None, statement_descriptor_suffix: None, request_extended_authorization: None, request_incremental_authorization: false, authentication_data: None, customer_acceptance: None, split_payments: None, merchant_order_reference_id: None, integrity_object: None, additional_payment_method_data: None, shipping_cost: None, merchant_account_id: None, merchant_config_currency: None, connector_testing_data: None, order_id: None, locale: None, payment_channel: None, enable_partial_authorization: None, enable_overcapture: None, is_stored_credential: None, mit_category: None, } } fn get_router_data<F, R1, R2>( &self, state: &SessionState, request_data: R1, access_token: Option<types::AccessToken>, ) -> types::RouterData<F, R1, R2> { let attempt_id = common_utils::generate_id_with_default_len(consts::VERIFY_CONNECTOR_ID_PREFIX); types::RouterData { flow: std::marker::PhantomData, status: storage_enums::AttemptStatus::Started, request: request_data, response: Err(errors::ApiErrorResponse::InternalServerError.into()), connector: self.connector.id().to_string(), auth_type: storage_enums::AuthenticationType::NoThreeDs, test_mode: None, attempt_id: attempt_id.clone(), description: None, customer_id: None, tenant_id: state.tenant.tenant_id.clone(), merchant_id: common_utils::id_type::MerchantId::default(), reference_id: None, access_token, session_token: None, payment_method: storage_enums::PaymentMethod::Card, payment_method_type: None, amount_captured: None, minor_amount_captured: None, preprocessing_id: None, connector_customer: None, connector_auth_type: self.connector_auth.clone(), connector_meta_data: None, connector_wallets_details: None, payment_method_token: None, connector_api_version: None, recurring_mandate_payment_data: None, payment_method_status: None, connector_request_reference_id: attempt_id, address: types::PaymentAddress::new(None, None, None, None), payment_id: common_utils::id_type::PaymentId::default() .get_string_repr() .to_owned(), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, payment_method_balance: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, } } } #[async_trait::async_trait] pub trait VerifyConnector { async fn verify( state: &SessionState, connector_data: VerifyConnectorData, ) -> errors::RouterResponse<()> { let authorize_data = connector_data.get_payment_authorize_data(); let access_token = Self::get_access_token(state, connector_data.clone()).await?; let router_data = connector_data.get_router_data(state, authorize_data, access_token); let request = connector_data .connector .get_connector_integration() .build_request(&router_data, &state.conf.connectors) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Payment request cannot be built".to_string(), })? .ok_or(errors::ApiErrorResponse::InternalServerError)?; let response = services::call_connector_api(&state.to_owned(), request, "verify_connector_request") .await .change_context(errors::ApiErrorResponse::InternalServerError)?; match response { Ok(_) => Ok(services::ApplicationResponse::StatusOk), Err(error_response) => { Self::handle_payment_error_response::< api::Authorize, types::PaymentFlowData, types::PaymentsAuthorizeData, types::PaymentsResponseData, >( connector_data.connector.get_connector_integration(), error_response, ) .await } } } async fn get_access_token( _state: &SessionState, _connector_data: VerifyConnectorData, ) -> errors::CustomResult<Option<types::AccessToken>, errors::ApiErrorResponse> { // AccessToken is None for the connectors without the AccessToken Flow. // If a connector has that, then it should override this implementation. Ok(None) } async fn handle_payment_error_response<F, ResourceCommonData, Req, Resp>( // connector: &(dyn api::Connector + Sync), connector: BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>, error_response: types::Response, ) -> errors::RouterResponse<()> { let error = connector .get_error_response(error_response, None) .change_context(errors::ApiErrorResponse::InternalServerError)?; Err(errors::ApiErrorResponse::InvalidRequestData { message: error.reason.unwrap_or(error.message), } .into()) } async fn handle_access_token_error_response<F, ResourceCommonData, Req, Resp>( connector: BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>, error_response: types::Response, ) -> errors::RouterResult<Option<types::AccessToken>> { let error = connector .get_error_response(error_response, None) .change_context(errors::ApiErrorResponse::InternalServerError)?; Err(errors::ApiErrorResponse::InvalidRequestData { message: error.reason.unwrap_or(error.message), } .into()) } }
{ "crate": "router", "file": "crates/router/src/types/api/verify_connector.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_7306143953390590640
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/api/poll.rs // Contains: 1 structs, 0 enums use serde; #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct PollId { pub poll_id: String, }
{ "crate": "router", "file": "crates/router/src/types/api/poll.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-4997653595332311018
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/api/authentication.rs // Contains: 4 structs, 0 enums use std::str::FromStr; use api_models::enums; use common_utils::errors::CustomResult; use error_stack::ResultExt; pub use hyperswitch_domain_models::{ router_flow_types::authentication::{ Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall, }, router_request_types::authentication::MessageCategory, }; use crate::{ connector, core::errors, services::connector_integration_interface::ConnectorEnum, types::storage, }; #[derive(Clone, serde::Deserialize, Debug, serde::Serialize)] pub struct AcquirerDetails { pub acquirer_bin: String, pub acquirer_merchant_mid: String, pub acquirer_country_code: Option<String>, } #[derive(Clone, serde::Deserialize, Debug, serde::Serialize)] pub struct AuthenticationResponse { pub trans_status: common_enums::TransactionStatus, pub acs_url: Option<url::Url>, pub challenge_request: Option<String>, pub challenge_request_key: Option<String>, pub acs_reference_number: Option<String>, pub acs_trans_id: Option<String>, pub three_dsserver_trans_id: Option<String>, pub acs_signed_content: Option<String>, } impl TryFrom<storage::Authentication> for AuthenticationResponse { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(authentication: storage::Authentication) -> Result<Self, Self::Error> { let trans_status = authentication.trans_status.ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("trans_status must be populated in authentication table authentication call is successful")?; let acs_url = authentication .acs_url .map(|url| url::Url::from_str(&url)) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("not a valid URL")?; Ok(Self { trans_status, acs_url, challenge_request: authentication.challenge_request, acs_reference_number: authentication.acs_reference_number, acs_trans_id: authentication.acs_trans_id, three_dsserver_trans_id: authentication.threeds_server_transaction_id, acs_signed_content: authentication.acs_signed_content, challenge_request_key: authentication.challenge_request_key, }) } } #[derive(Clone, serde::Deserialize, Debug, serde::Serialize)] pub struct PostAuthenticationResponse { pub trans_status: String, pub authentication_value: Option<masking::Secret<String>>, pub eci: Option<String>, } #[derive(Clone)] pub struct AuthenticationConnectorData { pub connector: ConnectorEnum, pub connector_name: enums::AuthenticationConnectors, } impl AuthenticationConnectorData { pub fn get_connector_by_name(name: &str) -> CustomResult<Self, errors::ApiErrorResponse> { let connector_name = enums::AuthenticationConnectors::from_str(name) .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven) .attach_printable_lazy(|| format!("unable to parse connector: {name}"))?; let connector = Self::convert_connector(connector_name)?; Ok(Self { connector, connector_name, }) } fn convert_connector( connector_name: enums::AuthenticationConnectors, ) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> { match connector_name { enums::AuthenticationConnectors::Threedsecureio => { Ok(ConnectorEnum::Old(Box::new(&connector::Threedsecureio))) } enums::AuthenticationConnectors::Netcetera => { Ok(ConnectorEnum::Old(Box::new(&connector::Netcetera))) } enums::AuthenticationConnectors::Gpayments => { Ok(ConnectorEnum::Old(Box::new(connector::Gpayments::new()))) } enums::AuthenticationConnectors::CtpMastercard => { Ok(ConnectorEnum::Old(Box::new(&connector::CtpMastercard))) } enums::AuthenticationConnectors::CtpVisa => Ok(ConnectorEnum::Old(Box::new( connector::UnifiedAuthenticationService::new(), ))), enums::AuthenticationConnectors::UnifiedAuthenticationService => Ok( ConnectorEnum::Old(Box::new(connector::UnifiedAuthenticationService::new())), ), enums::AuthenticationConnectors::Juspaythreedsserver => Ok(ConnectorEnum::Old( Box::new(connector::Juspaythreedsserver::new()), )), enums::AuthenticationConnectors::Cardinal => Ok(ConnectorEnum::Old(Box::new( connector::UnifiedAuthenticationService::new(), ))), } } }
{ "crate": "router", "file": "crates/router/src/types/api/authentication.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_router_-8017065726551503132
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/api/routing.rs // Contains: 2 structs, 1 enums pub use api_models::{ enums as api_enums, routing::{ ConnectorVolumeSplit, RoutableChoiceKind, RoutableConnectorChoice, RoutingAlgorithmKind, RoutingAlgorithmRef, RoutingConfigRequest, RoutingDictionary, RoutingDictionaryRecord, StaticRoutingAlgorithm, StraightThroughAlgorithm, }, }; use super::types::api as api_oss; pub struct SessionRoutingChoice { pub connector: api_oss::ConnectorData, pub payment_method_type: api_enums::PaymentMethodType, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ConnectorVolumeSplitV0 { pub connector: RoutableConnectorChoice, pub split: u8, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum RoutingAlgorithmV0 { Single(Box<RoutableConnectorChoice>), Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplitV0>), Custom { timestamp: i64 }, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct FrmRoutingAlgorithm { pub data: String, #[serde(rename = "type")] pub algorithm_type: String, }
{ "crate": "router", "file": "crates/router/src/types/api/routing.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_router_-4354416053398750890
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/api/feature_matrix.rs // Contains: 1 structs, 0 enums use std::str::FromStr; use error_stack::{report, ResultExt}; use crate::{ connector, core::errors::{self, CustomResult}, services::connector_integration_interface::ConnectorEnum, types::api::enums, }; #[derive(Clone)] pub struct FeatureMatrixConnectorData {} impl FeatureMatrixConnectorData { pub fn convert_connector( connector_name: &str, ) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> { match enums::Connector::from_str(connector_name) { Ok(name) => match name { enums::Connector::Aci => Ok(ConnectorEnum::Old(Box::new(connector::Aci::new()))), enums::Connector::Adyen => { Ok(ConnectorEnum::Old(Box::new(connector::Adyen::new()))) } enums::Connector::Affirm => { Ok(ConnectorEnum::Old(Box::new(connector::Affirm::new()))) } enums::Connector::Adyenplatform => Ok(ConnectorEnum::Old(Box::new( connector::Adyenplatform::new(), ))), enums::Connector::Airwallex => { Ok(ConnectorEnum::Old(Box::new(connector::Airwallex::new()))) } enums::Connector::Amazonpay => { Ok(ConnectorEnum::Old(Box::new(connector::Amazonpay::new()))) } enums::Connector::Archipel => { Ok(ConnectorEnum::Old(Box::new(connector::Archipel::new()))) } enums::Connector::Authipay => { Ok(ConnectorEnum::Old(Box::new(connector::Authipay::new()))) } enums::Connector::Authorizedotnet => Ok(ConnectorEnum::Old(Box::new( connector::Authorizedotnet::new(), ))), enums::Connector::Bambora => { Ok(ConnectorEnum::Old(Box::new(connector::Bambora::new()))) } enums::Connector::Bamboraapac => { Ok(ConnectorEnum::Old(Box::new(connector::Bamboraapac::new()))) } enums::Connector::Bankofamerica => Ok(ConnectorEnum::Old(Box::new( connector::Bankofamerica::new(), ))), enums::Connector::Barclaycard => { Ok(ConnectorEnum::Old(Box::new(connector::Barclaycard::new()))) } enums::Connector::Billwerk => { Ok(ConnectorEnum::Old(Box::new(connector::Billwerk::new()))) } enums::Connector::Bitpay => { Ok(ConnectorEnum::Old(Box::new(connector::Bitpay::new()))) } enums::Connector::Blackhawknetwork => Ok(ConnectorEnum::Old(Box::new( connector::Blackhawknetwork::new(), ))), enums::Connector::Bluesnap => { Ok(ConnectorEnum::Old(Box::new(connector::Bluesnap::new()))) } enums::Connector::Calida => { Ok(ConnectorEnum::Old(Box::new(connector::Calida::new()))) } enums::Connector::Boku => Ok(ConnectorEnum::Old(Box::new(connector::Boku::new()))), enums::Connector::Braintree => { Ok(ConnectorEnum::Old(Box::new(connector::Braintree::new()))) } enums::Connector::Breadpay => { Ok(ConnectorEnum::Old(Box::new(connector::Breadpay::new()))) } enums::Connector::Cashtocode => { Ok(ConnectorEnum::Old(Box::new(connector::Cashtocode::new()))) } enums::Connector::Celero => { Ok(ConnectorEnum::Old(Box::new(connector::Celero::new()))) } enums::Connector::Chargebee => { Ok(ConnectorEnum::Old(Box::new(connector::Chargebee::new()))) } enums::Connector::Checkbook => { Ok(ConnectorEnum::Old(Box::new(connector::Checkbook::new()))) } enums::Connector::Checkout => { Ok(ConnectorEnum::Old(Box::new(connector::Checkout::new()))) } enums::Connector::Coinbase => { Ok(ConnectorEnum::Old(Box::new(connector::Coinbase::new()))) } enums::Connector::Coingate => { Ok(ConnectorEnum::Old(Box::new(connector::Coingate::new()))) } enums::Connector::Cryptopay => { Ok(ConnectorEnum::Old(Box::new(connector::Cryptopay::new()))) } enums::Connector::CtpMastercard => { Ok(ConnectorEnum::Old(Box::new(&connector::CtpMastercard))) } enums::Connector::Custombilling => Ok(ConnectorEnum::Old(Box::new( connector::Custombilling::new(), ))), enums::Connector::CtpVisa => Ok(ConnectorEnum::Old(Box::new( connector::UnifiedAuthenticationService::new(), ))), enums::Connector::Cybersource => { Ok(ConnectorEnum::Old(Box::new(connector::Cybersource::new()))) } enums::Connector::Datatrans => { Ok(ConnectorEnum::Old(Box::new(connector::Datatrans::new()))) } enums::Connector::Deutschebank => { Ok(ConnectorEnum::Old(Box::new(connector::Deutschebank::new()))) } enums::Connector::Digitalvirgo => { Ok(ConnectorEnum::Old(Box::new(connector::Digitalvirgo::new()))) } enums::Connector::Dlocal => { Ok(ConnectorEnum::Old(Box::new(connector::Dlocal::new()))) } #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector1 => Ok(ConnectorEnum::Old(Box::new( connector::DummyConnector::<1>::new(), ))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector2 => Ok(ConnectorEnum::Old(Box::new( connector::DummyConnector::<2>::new(), ))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector3 => Ok(ConnectorEnum::Old(Box::new( connector::DummyConnector::<3>::new(), ))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector4 => Ok(ConnectorEnum::Old(Box::new( connector::DummyConnector::<4>::new(), ))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector5 => Ok(ConnectorEnum::Old(Box::new( connector::DummyConnector::<5>::new(), ))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector6 => Ok(ConnectorEnum::Old(Box::new( connector::DummyConnector::<6>::new(), ))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector7 => Ok(ConnectorEnum::Old(Box::new( connector::DummyConnector::<7>::new(), ))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyBillingConnector => Ok(ConnectorEnum::Old(Box::new( connector::DummyConnector::<8>::new(), ))), enums::Connector::Dwolla => { Ok(ConnectorEnum::Old(Box::new(connector::Dwolla::new()))) } enums::Connector::Ebanx => { Ok(ConnectorEnum::Old(Box::new(connector::Ebanx::new()))) } enums::Connector::Elavon => { Ok(ConnectorEnum::Old(Box::new(connector::Elavon::new()))) } enums::Connector::Facilitapay => { Ok(ConnectorEnum::Old(Box::new(connector::Facilitapay::new()))) } enums::Connector::Finix => { Ok(ConnectorEnum::Old(Box::new(connector::Finix::new()))) } enums::Connector::Fiserv => { Ok(ConnectorEnum::Old(Box::new(connector::Fiserv::new()))) } enums::Connector::Fiservemea => { Ok(ConnectorEnum::Old(Box::new(connector::Fiservemea::new()))) } enums::Connector::Fiuu => Ok(ConnectorEnum::Old(Box::new(connector::Fiuu::new()))), enums::Connector::Forte => { Ok(ConnectorEnum::Old(Box::new(connector::Forte::new()))) } enums::Connector::Flexiti => { Ok(ConnectorEnum::Old(Box::new(connector::Flexiti::new()))) } enums::Connector::Getnet => { Ok(ConnectorEnum::Old(Box::new(connector::Getnet::new()))) } enums::Connector::Gigadat => { Ok(ConnectorEnum::Old(Box::new(connector::Gigadat::new()))) } enums::Connector::Globalpay => { Ok(ConnectorEnum::Old(Box::new(connector::Globalpay::new()))) } enums::Connector::Globepay => { Ok(ConnectorEnum::Old(Box::new(connector::Globepay::new()))) } enums::Connector::Gocardless => { Ok(ConnectorEnum::Old(Box::new(connector::Gocardless::new()))) } enums::Connector::Hipay => { Ok(ConnectorEnum::Old(Box::new(connector::Hipay::new()))) } enums::Connector::Helcim => { Ok(ConnectorEnum::Old(Box::new(connector::Helcim::new()))) } enums::Connector::HyperswitchVault => { Ok(ConnectorEnum::Old(Box::new(&connector::HyperswitchVault))) } enums::Connector::Iatapay => { Ok(ConnectorEnum::Old(Box::new(connector::Iatapay::new()))) } enums::Connector::Inespay => { Ok(ConnectorEnum::Old(Box::new(connector::Inespay::new()))) } enums::Connector::Itaubank => { Ok(ConnectorEnum::Old(Box::new(connector::Itaubank::new()))) } enums::Connector::Jpmorgan => { Ok(ConnectorEnum::Old(Box::new(connector::Jpmorgan::new()))) } enums::Connector::Juspaythreedsserver => Ok(ConnectorEnum::Old(Box::new( connector::Juspaythreedsserver::new(), ))), enums::Connector::Klarna => { Ok(ConnectorEnum::Old(Box::new(connector::Klarna::new()))) } enums::Connector::Loonio => { Ok(ConnectorEnum::Old(Box::new(connector::Loonio::new()))) } enums::Connector::Mollie => { // enums::Connector::Moneris => Ok(ConnectorEnum::Old(Box::new(connector::Moneris))), Ok(ConnectorEnum::Old(Box::new(connector::Mollie::new()))) } enums::Connector::Moneris => { Ok(ConnectorEnum::Old(Box::new(connector::Moneris::new()))) } enums::Connector::Nexixpay => { Ok(ConnectorEnum::Old(Box::new(connector::Nexixpay::new()))) } enums::Connector::Nmi => Ok(ConnectorEnum::Old(Box::new(connector::Nmi::new()))), enums::Connector::Nomupay => { 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()))) } enums::Connector::Nuvei => { Ok(ConnectorEnum::Old(Box::new(connector::Nuvei::new()))) } enums::Connector::Opennode => { Ok(ConnectorEnum::Old(Box::new(connector::Opennode::new()))) } enums::Connector::Phonepe => { Ok(ConnectorEnum::Old(Box::new(connector::Phonepe::new()))) } enums::Connector::Paybox => { Ok(ConnectorEnum::Old(Box::new(connector::Paybox::new()))) } enums::Connector::Paytm => { Ok(ConnectorEnum::Old(Box::new(connector::Paytm::new()))) } // "payeezy" => Ok(ConnectorIntegrationEnum::Old(Box::new(&connector::Payeezy)), As psync and rsync are not supported by this connector, it is added as template code for future usage // enums::Connector::Payload => { // Ok(ConnectorEnum::Old(Box::new(connector::Paybload::new()))) // } enums::Connector::Payload => { Ok(ConnectorEnum::Old(Box::new(connector::Payload::new()))) } enums::Connector::Payme => { Ok(ConnectorEnum::Old(Box::new(connector::Payme::new()))) } enums::Connector::Payone => { Ok(ConnectorEnum::Old(Box::new(connector::Payone::new()))) } enums::Connector::Payu => Ok(ConnectorEnum::Old(Box::new(connector::Payu::new()))), enums::Connector::Peachpayments => Ok(ConnectorEnum::Old(Box::new( connector::Peachpayments::new(), ))), enums::Connector::Placetopay => { Ok(ConnectorEnum::Old(Box::new(connector::Placetopay::new()))) } enums::Connector::Powertranz => { Ok(ConnectorEnum::Old(Box::new(connector::Powertranz::new()))) } enums::Connector::Prophetpay => { Ok(ConnectorEnum::Old(Box::new(&connector::Prophetpay))) } enums::Connector::Razorpay => { Ok(ConnectorEnum::Old(Box::new(connector::Razorpay::new()))) } enums::Connector::Rapyd => { Ok(ConnectorEnum::Old(Box::new(connector::Rapyd::new()))) } enums::Connector::Recurly => { Ok(ConnectorEnum::New(Box::new(connector::Recurly::new()))) } enums::Connector::Redsys => { Ok(ConnectorEnum::Old(Box::new(connector::Redsys::new()))) } enums::Connector::Santander => { Ok(ConnectorEnum::Old(Box::new(connector::Santander::new()))) } enums::Connector::Shift4 => { Ok(ConnectorEnum::Old(Box::new(connector::Shift4::new()))) } enums::Connector::Square => Ok(ConnectorEnum::Old(Box::new(&connector::Square))), enums::Connector::Stax => Ok(ConnectorEnum::Old(Box::new(&connector::Stax))), enums::Connector::Stripe => { Ok(ConnectorEnum::Old(Box::new(connector::Stripe::new()))) } enums::Connector::Stripebilling => Ok(ConnectorEnum::Old(Box::new( connector::Stripebilling::new(), ))), enums::Connector::Wise => Ok(ConnectorEnum::Old(Box::new(connector::Wise::new()))), enums::Connector::Worldline => { Ok(ConnectorEnum::Old(Box::new(&connector::Worldline))) } enums::Connector::Worldpay => { Ok(ConnectorEnum::Old(Box::new(connector::Worldpay::new()))) } enums::Connector::Worldpayvantiv => Ok(ConnectorEnum::Old(Box::new( connector::Worldpayvantiv::new(), ))), enums::Connector::Worldpayxml => { Ok(ConnectorEnum::Old(Box::new(connector::Worldpayxml::new()))) } enums::Connector::Xendit => { Ok(ConnectorEnum::Old(Box::new(connector::Xendit::new()))) } enums::Connector::Mifinity => { Ok(ConnectorEnum::Old(Box::new(connector::Mifinity::new()))) } enums::Connector::Multisafepay => { Ok(ConnectorEnum::Old(Box::new(connector::Multisafepay::new()))) } enums::Connector::Netcetera => { Ok(ConnectorEnum::Old(Box::new(&connector::Netcetera))) } enums::Connector::Nexinets => { Ok(ConnectorEnum::Old(Box::new(&connector::Nexinets))) } // enums::Connector::Nexixpay => { // Ok(ConnectorEnum::Old(Box::new(&connector::Nexixpay))) // } enums::Connector::Paypal => { Ok(ConnectorEnum::Old(Box::new(connector::Paypal::new()))) } enums::Connector::Paysafe => { Ok(ConnectorEnum::Old(Box::new(connector::Paysafe::new()))) } enums::Connector::Paystack => { Ok(ConnectorEnum::Old(Box::new(connector::Paystack::new()))) } // enums::Connector::Thunes => Ok(ConnectorEnum::Old(Box::new(connector::Thunes))), enums::Connector::Tesouro => { Ok(ConnectorEnum::Old(Box::new(connector::Tesouro::new()))) } enums::Connector::Tokenex => Ok(ConnectorEnum::Old(Box::new(&connector::Tokenex))), enums::Connector::Tokenio => { Ok(ConnectorEnum::Old(Box::new(connector::Tokenio::new()))) } enums::Connector::Trustpay => { Ok(ConnectorEnum::Old(Box::new(connector::Trustpay::new()))) } enums::Connector::Trustpayments => Ok(ConnectorEnum::Old(Box::new( connector::Trustpayments::new(), ))), enums::Connector::Tsys => Ok(ConnectorEnum::Old(Box::new(connector::Tsys::new()))), // enums::Connector::UnifiedAuthenticationService => Ok(ConnectorEnum::Old(Box::new( // connector::UnifiedAuthenticationService, // ))), enums::Connector::Vgs => Ok(ConnectorEnum::Old(Box::new(&connector::Vgs))), enums::Connector::Volt => Ok(ConnectorEnum::Old(Box::new(connector::Volt::new()))), enums::Connector::Wellsfargo => { Ok(ConnectorEnum::Old(Box::new(connector::Wellsfargo::new()))) } // enums::Connector::Wellsfargopayout => { // Ok(Box::new(connector::Wellsfargopayout::new())) // } enums::Connector::Zen => Ok(ConnectorEnum::Old(Box::new(&connector::Zen))), enums::Connector::Zsl => Ok(ConnectorEnum::Old(Box::new(&connector::Zsl))), enums::Connector::Plaid => { Ok(ConnectorEnum::Old(Box::new(connector::Plaid::new()))) } enums::Connector::Signifyd => { Ok(ConnectorEnum::Old(Box::new(&connector::Signifyd))) } enums::Connector::Silverflow => { Ok(ConnectorEnum::Old(Box::new(connector::Silverflow::new()))) } enums::Connector::Riskified => { Ok(ConnectorEnum::Old(Box::new(connector::Riskified::new()))) } enums::Connector::Gpayments => { Ok(ConnectorEnum::Old(Box::new(connector::Gpayments::new()))) } enums::Connector::Threedsecureio => { Ok(ConnectorEnum::Old(Box::new(&connector::Threedsecureio))) } enums::Connector::Taxjar => { Ok(ConnectorEnum::Old(Box::new(connector::Taxjar::new()))) } enums::Connector::Cardinal => { Err(report!(errors::ConnectorError::InvalidConnectorName) .attach_printable(format!("invalid connector name: {connector_name}"))) .change_context(errors::ApiErrorResponse::InternalServerError) } }, Err(_) => Err(report!(errors::ConnectorError::InvalidConnectorName) .attach_printable(format!("invalid connector name: {connector_name}"))) .change_context(errors::ApiErrorResponse::InternalServerError), } } }
{ "crate": "router", "file": "crates/router/src/types/api/feature_matrix.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-6171339204425949807
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/api/admin.rs // Contains: 1 structs, 0 enums use std::collections::HashMap; #[cfg(feature = "v2")] pub use api_models::admin; pub use api_models::{ admin::{ MaskedHeaders, MerchantAccountCreate, MerchantAccountDeleteResponse, MerchantAccountResponse, MerchantAccountUpdate, MerchantConnectorCreate, MerchantConnectorDeleteResponse, MerchantConnectorDetails, MerchantConnectorDetailsWrap, MerchantConnectorId, MerchantConnectorResponse, MerchantDetails, MerchantId, PaymentMethodsEnabled, ProfileCreate, ProfileResponse, ProfileUpdate, ToggleAllKVRequest, ToggleAllKVResponse, ToggleKVRequest, ToggleKVResponse, WebhookDetails, }, organization::{ OrganizationCreateRequest, OrganizationId, OrganizationResponse, OrganizationUpdateRequest, }, }; use common_utils::{ext_traits::ValueExt, types::keymanager as km_types}; use diesel_models::{business_profile::CardTestingGuardConfig, organization::OrganizationBridge}; use error_stack::ResultExt; use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore; use masking::{ExposeInterface, PeekInterface, Secret}; use crate::{ consts, core::errors, routes::SessionState, types::{ domain::{ self, types::{self as domain_types, AsyncLift}, }, transformers::{ForeignInto, ForeignTryFrom}, ForeignFrom, }, utils, }; #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct ProfileAcquirerConfigs { pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>, pub profile_id: common_utils::id_type::ProfileId, } impl From<ProfileAcquirerConfigs> for Option<Vec<api_models::profile_acquirer::ProfileAcquirerResponse>> { fn from(item: ProfileAcquirerConfigs) -> Self { item.acquirer_config_map.map(|config_map_val| { let mut vec: Vec<_> = config_map_val.0.into_iter().collect(); vec.sort_by_key(|k| k.0.clone()); vec.into_iter() .map(|(profile_acquirer_id, acquirer_config)| { api_models::profile_acquirer::ProfileAcquirerResponse::from(( profile_acquirer_id, &item.profile_id, &acquirer_config, )) }) .collect::<Vec<api_models::profile_acquirer::ProfileAcquirerResponse>>() }) } } impl ForeignFrom<diesel_models::organization::Organization> for OrganizationResponse { fn foreign_from(org: diesel_models::organization::Organization) -> Self { Self { #[cfg(feature = "v2")] id: org.get_organization_id(), #[cfg(feature = "v1")] organization_id: org.get_organization_id(), organization_name: org.get_organization_name(), organization_details: org.organization_details, metadata: org.metadata, modified_at: org.modified_at, created_at: org.created_at, organization_type: org.organization_type, } } } #[cfg(feature = "v1")] impl ForeignTryFrom<domain::MerchantAccount> for MerchantAccountResponse { type Error = error_stack::Report<errors::ParsingError>; fn foreign_try_from(item: domain::MerchantAccount) -> Result<Self, Self::Error> { let merchant_id = item.get_id().to_owned(); let primary_business_details: Vec<api_models::admin::PrimaryBusinessDetails> = item .primary_business_details .parse_value("primary_business_details")?; let pm_collect_link_config: Option<api_models::admin::BusinessCollectLinkConfig> = item .pm_collect_link_config .map(|config| config.parse_value("pm_collect_link_config")) .transpose()?; Ok(Self { merchant_id, merchant_name: item.merchant_name, return_url: item.return_url, enable_payment_response_hash: item.enable_payment_response_hash, payment_response_hash_key: item.payment_response_hash_key, redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, merchant_details: item.merchant_details, webhook_details: item.webhook_details.clone().map(ForeignInto::foreign_into), routing_algorithm: item.routing_algorithm, sub_merchants_enabled: item.sub_merchants_enabled, parent_merchant_id: item.parent_merchant_id, publishable_key: Some(item.publishable_key), metadata: item.metadata, locker_id: item.locker_id, primary_business_details, frm_routing_algorithm: item.frm_routing_algorithm, #[cfg(feature = "payouts")] payout_routing_algorithm: item.payout_routing_algorithm, organization_id: item.organization_id, is_recon_enabled: item.is_recon_enabled, default_profile: item.default_profile, recon_status: item.recon_status, pm_collect_link_config, product_type: item.product_type, merchant_account_type: item.merchant_account_type, }) } } #[cfg(feature = "v2")] impl ForeignTryFrom<domain::MerchantAccount> for MerchantAccountResponse { type Error = error_stack::Report<errors::ValidationError>; fn foreign_try_from(item: domain::MerchantAccount) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let id = item.get_id().to_owned(); let merchant_name = item .merchant_name .get_required_value("merchant_name")? .into_inner(); Ok(Self { id, merchant_name, merchant_details: item.merchant_details, publishable_key: item.publishable_key, metadata: item.metadata, organization_id: item.organization_id, recon_status: item.recon_status, product_type: item.product_type, }) } } #[cfg(feature = "v1")] impl ForeignTryFrom<domain::Profile> for ProfileResponse { type Error = error_stack::Report<errors::ParsingError>; fn foreign_try_from(item: domain::Profile) -> Result<Self, Self::Error> { let profile_id = item.get_id().to_owned(); let outgoing_webhook_custom_http_headers = item .outgoing_webhook_custom_http_headers .map(|headers| { headers .into_inner() .expose() .parse_value::<HashMap<String, Secret<String>>>( "HashMap<String, Secret<String>>", ) }) .transpose()?; let masked_outgoing_webhook_custom_http_headers = outgoing_webhook_custom_http_headers.map(MaskedHeaders::from_headers); let card_testing_guard_config = item .card_testing_guard_config .or(Some(CardTestingGuardConfig::default())); let (is_external_vault_enabled, external_vault_connector_details) = item.external_vault_details.into(); Ok(Self { merchant_id: item.merchant_id, profile_id: profile_id.clone(), profile_name: item.profile_name, return_url: item.return_url, enable_payment_response_hash: item.enable_payment_response_hash, payment_response_hash_key: item.payment_response_hash_key, redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, webhook_details: item.webhook_details.map(ForeignInto::foreign_into), metadata: item.metadata, routing_algorithm: item.routing_algorithm, intent_fulfillment_time: item.intent_fulfillment_time, frm_routing_algorithm: item.frm_routing_algorithm, #[cfg(feature = "payouts")] payout_routing_algorithm: item.payout_routing_algorithm, applepay_verified_domains: item.applepay_verified_domains, payment_link_config: item.payment_link_config.map(ForeignInto::foreign_into), session_expiry: item.session_expiry, authentication_connector_details: item .authentication_connector_details .map(ForeignInto::foreign_into), payout_link_config: item.payout_link_config.map(ForeignInto::foreign_into), use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing, extended_card_info_config: item .extended_card_info_config .map(|config| config.expose().parse_value("ExtendedCardInfoConfig")) .transpose()?, collect_shipping_details_from_wallet_connector: item .collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector: item .collect_billing_details_from_wallet_connector, always_collect_billing_details_from_wallet_connector: item .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: item .always_collect_shipping_details_from_wallet_connector, is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled, outgoing_webhook_custom_http_headers: masked_outgoing_webhook_custom_http_headers, tax_connector_id: item.tax_connector_id, is_tax_connector_enabled: item.is_tax_connector_enabled, is_network_tokenization_enabled: item.is_network_tokenization_enabled, is_auto_retries_enabled: item.is_auto_retries_enabled, max_auto_retries_enabled: item.max_auto_retries_enabled, always_request_extended_authorization: item.always_request_extended_authorization, is_click_to_pay_enabled: item.is_click_to_pay_enabled, authentication_product_ids: item.authentication_product_ids, card_testing_guard_config: card_testing_guard_config.map(ForeignInto::foreign_into), is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled, force_3ds_challenge: item.force_3ds_challenge, is_debit_routing_enabled: Some(item.is_debit_routing_enabled), merchant_business_country: item.merchant_business_country, is_pre_network_tokenization_enabled: item.is_pre_network_tokenization_enabled, acquirer_configs: ProfileAcquirerConfigs { acquirer_config_map: item.acquirer_config_map.clone(), profile_id: profile_id.clone(), } .into(), is_iframe_redirection_enabled: item.is_iframe_redirection_enabled, merchant_category_code: item.merchant_category_code, merchant_country_code: item.merchant_country_code, dispute_polling_interval: item.dispute_polling_interval, is_manual_retry_enabled: item.is_manual_retry_enabled, always_enable_overcapture: item.always_enable_overcapture, is_external_vault_enabled, external_vault_connector_details: external_vault_connector_details .map(ForeignFrom::foreign_from), billing_processor_id: item.billing_processor_id, is_l2_l3_enabled: Some(item.is_l2_l3_enabled), }) } } #[cfg(feature = "v2")] impl ForeignTryFrom<domain::Profile> for ProfileResponse { type Error = error_stack::Report<errors::ParsingError>; fn foreign_try_from(item: domain::Profile) -> Result<Self, Self::Error> { let id = item.get_id().to_owned(); let outgoing_webhook_custom_http_headers = item .outgoing_webhook_custom_http_headers .map(|headers| { headers .into_inner() .expose() .parse_value::<HashMap<String, Secret<String>>>( "HashMap<String, Secret<String>>", ) }) .transpose()?; let order_fulfillment_time = item .order_fulfillment_time .map(admin::OrderFulfillmentTime::try_new) .transpose() .change_context(errors::ParsingError::IntegerOverflow)?; let masked_outgoing_webhook_custom_http_headers = outgoing_webhook_custom_http_headers.map(MaskedHeaders::from_headers); let card_testing_guard_config = item .card_testing_guard_config .or(Some(CardTestingGuardConfig::default())); Ok(Self { merchant_id: item.merchant_id, id, profile_name: item.profile_name, return_url: item.return_url, enable_payment_response_hash: item.enable_payment_response_hash, payment_response_hash_key: item.payment_response_hash_key, redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, webhook_details: item.webhook_details.map(ForeignInto::foreign_into), metadata: item.metadata, applepay_verified_domains: item.applepay_verified_domains, payment_link_config: item.payment_link_config.map(ForeignInto::foreign_into), session_expiry: item.session_expiry, authentication_connector_details: item .authentication_connector_details .map(ForeignInto::foreign_into), payout_link_config: item.payout_link_config.map(ForeignInto::foreign_into), use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing, extended_card_info_config: item .extended_card_info_config .map(|config| config.expose().parse_value("ExtendedCardInfoConfig")) .transpose()?, collect_shipping_details_from_wallet_connector_if_required: item .collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector_if_required: item .collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: item .always_collect_shipping_details_from_wallet_connector, always_collect_billing_details_from_wallet_connector: item .always_collect_billing_details_from_wallet_connector, is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled, outgoing_webhook_custom_http_headers: masked_outgoing_webhook_custom_http_headers, order_fulfillment_time, order_fulfillment_time_origin: item.order_fulfillment_time_origin, should_collect_cvv_during_payment: item.should_collect_cvv_during_payment, tax_connector_id: item.tax_connector_id, is_tax_connector_enabled: item.is_tax_connector_enabled, is_network_tokenization_enabled: item.is_network_tokenization_enabled, is_click_to_pay_enabled: item.is_click_to_pay_enabled, authentication_product_ids: item.authentication_product_ids, card_testing_guard_config: card_testing_guard_config.map(ForeignInto::foreign_into), is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled, is_debit_routing_enabled: Some(item.is_debit_routing_enabled), merchant_business_country: item.merchant_business_country, is_iframe_redirection_enabled: item.is_iframe_redirection_enabled, is_external_vault_enabled: item.is_external_vault_enabled, is_l2_l3_enabled: None, external_vault_connector_details: item .external_vault_connector_details .map(ForeignInto::foreign_into), merchant_category_code: item.merchant_category_code, merchant_country_code: item.merchant_country_code, split_txns_enabled: item.split_txns_enabled, revenue_recovery_retry_algorithm_type: item.revenue_recovery_retry_algorithm_type, billing_processor_id: item.billing_processor_id, }) } } #[cfg(feature = "v1")] pub async fn create_profile_from_merchant_account( state: &SessionState, merchant_account: domain::MerchantAccount, request: ProfileCreate, key_store: &MerchantKeyStore, ) -> Result<domain::Profile, error_stack::Report<errors::ApiErrorResponse>> { use common_utils::ext_traits::AsyncExt; use diesel_models::business_profile::CardTestingGuardConfig; use crate::core; // Generate a unique profile id let profile_id = common_utils::generate_profile_id_of_default_length(); let merchant_id = merchant_account.get_id().to_owned(); let current_time = common_utils::date_time::now(); let webhook_details = request.webhook_details.map(ForeignInto::foreign_into); let payment_response_hash_key = request .payment_response_hash_key .or(merchant_account.payment_response_hash_key) .unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64)); let payment_link_config = request.payment_link_config.map(ForeignInto::foreign_into); let key_manager_state = state.into(); let outgoing_webhook_custom_http_headers = request .outgoing_webhook_custom_http_headers .async_map(|headers| { core::payment_methods::cards::create_encrypted_data( &key_manager_state, key_store, headers, ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?; let payout_link_config = request .payout_link_config .map(|payout_conf| match payout_conf.config.validate() { Ok(_) => Ok(payout_conf.foreign_into()), Err(e) => Err(error_stack::report!( errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() } )), }) .transpose()?; let key = key_store.key.clone().into_inner(); let key_manager_state = state.into(); let card_testing_secret_key = Some(Secret::new(utils::generate_id( consts::FINGERPRINT_SECRET_LENGTH, "fs", ))); let card_testing_guard_config = request .card_testing_guard_config .map(CardTestingGuardConfig::foreign_from) .or(Some(CardTestingGuardConfig::default())); Ok(domain::Profile::from(domain::ProfileSetter { profile_id, merchant_id, profile_name: request.profile_name.unwrap_or("default".to_string()), created_at: current_time, modified_at: current_time, return_url: request .return_url .map(|return_url| return_url.to_string()) .or(merchant_account.return_url), enable_payment_response_hash: request .enable_payment_response_hash .unwrap_or(merchant_account.enable_payment_response_hash), payment_response_hash_key: Some(payment_response_hash_key), redirect_to_merchant_with_http_post: request .redirect_to_merchant_with_http_post .unwrap_or(merchant_account.redirect_to_merchant_with_http_post), webhook_details: webhook_details.or(merchant_account.webhook_details), metadata: request.metadata, routing_algorithm: None, intent_fulfillment_time: request .intent_fulfillment_time .map(i64::from) .or(merchant_account.intent_fulfillment_time) .or(Some(common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME)), frm_routing_algorithm: request .frm_routing_algorithm .or(merchant_account.frm_routing_algorithm), #[cfg(feature = "payouts")] payout_routing_algorithm: request .payout_routing_algorithm .or(merchant_account.payout_routing_algorithm), #[cfg(not(feature = "payouts"))] payout_routing_algorithm: None, is_recon_enabled: merchant_account.is_recon_enabled, applepay_verified_domains: request.applepay_verified_domains, payment_link_config, session_expiry: request .session_expiry .map(i64::from) .or(Some(common_utils::consts::DEFAULT_SESSION_EXPIRY)), authentication_connector_details: request .authentication_connector_details .map(ForeignInto::foreign_into), payout_link_config, is_connector_agnostic_mit_enabled: request.is_connector_agnostic_mit_enabled, is_extended_card_info_enabled: None, extended_card_info_config: None, use_billing_as_payment_method_billing: request .use_billing_as_payment_method_billing .or(Some(true)), collect_shipping_details_from_wallet_connector: request .collect_shipping_details_from_wallet_connector .or(Some(false)), collect_billing_details_from_wallet_connector: request .collect_billing_details_from_wallet_connector .or(Some(false)), always_collect_billing_details_from_wallet_connector: request .always_collect_billing_details_from_wallet_connector .or(Some(false)), always_collect_shipping_details_from_wallet_connector: request .always_collect_shipping_details_from_wallet_connector .or(Some(false)), outgoing_webhook_custom_http_headers, tax_connector_id: request.tax_connector_id, is_tax_connector_enabled: request.is_tax_connector_enabled, dynamic_routing_algorithm: None, is_network_tokenization_enabled: request.is_network_tokenization_enabled, is_auto_retries_enabled: request.is_auto_retries_enabled.unwrap_or_default(), max_auto_retries_enabled: request.max_auto_retries_enabled.map(i16::from), always_request_extended_authorization: request.always_request_extended_authorization, is_click_to_pay_enabled: request.is_click_to_pay_enabled, authentication_product_ids: request.authentication_product_ids, card_testing_guard_config, card_testing_secret_key: card_testing_secret_key .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, common_utils::type_name!(domain::Profile), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating card testing secret key")?, is_clear_pan_retries_enabled: request.is_clear_pan_retries_enabled.unwrap_or_default(), force_3ds_challenge: request.force_3ds_challenge.unwrap_or_default(), is_debit_routing_enabled: request.is_debit_routing_enabled.unwrap_or_default(), merchant_business_country: request.merchant_business_country, is_iframe_redirection_enabled: request.is_iframe_redirection_enabled, is_pre_network_tokenization_enabled: request .is_pre_network_tokenization_enabled .unwrap_or_default(), merchant_category_code: request.merchant_category_code, merchant_country_code: request.merchant_country_code, dispute_polling_interval: request.dispute_polling_interval, is_manual_retry_enabled: request.is_manual_retry_enabled, always_enable_overcapture: request.always_enable_overcapture, external_vault_details: domain::ExternalVaultDetails::try_from(( request.is_external_vault_enabled, request .external_vault_connector_details .map(ForeignInto::foreign_into), )) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating external_vault_details")?, billing_processor_id: request.billing_processor_id, is_l2_l3_enabled: request.is_l2_l3_enabled.unwrap_or(false), })) }
{ "crate": "router", "file": "crates/router/src/types/api/admin.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_937478481328602089
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/api/connector_onboarding/paypal.rs // Contains: 12 structs, 8 enums use api_models::connector_onboarding as api; use error_stack::ResultExt; use crate::core::errors::{ApiErrorResponse, RouterResult}; #[derive(serde::Deserialize, Debug)] pub struct HateoasLink { pub href: String, pub rel: String, pub method: String, } #[derive(serde::Deserialize, Debug)] pub struct PartnerReferralResponse { pub links: Vec<HateoasLink>, } #[derive(serde::Serialize, Debug)] pub struct PartnerReferralRequest { pub tracking_id: String, pub operations: Vec<PartnerReferralOperations>, pub products: Vec<PayPalProducts>, pub capabilities: Vec<PayPalCapabilities>, pub partner_config_override: PartnerConfigOverride, pub legal_consents: Vec<LegalConsent>, } #[derive(serde::Serialize, Debug)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PayPalProducts { Ppcp, AdvancedVaulting, } #[derive(serde::Serialize, Debug)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PayPalCapabilities { PaypalWalletVaultingAdvanced, } #[derive(serde::Serialize, Debug)] pub struct PartnerReferralOperations { pub operation: PayPalReferralOperationType, pub api_integration_preference: PartnerReferralIntegrationPreference, } #[derive(serde::Serialize, Debug)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PayPalReferralOperationType { ApiIntegration, } #[derive(serde::Serialize, Debug)] pub struct PartnerReferralIntegrationPreference { pub rest_api_integration: PartnerReferralRestApiIntegration, } #[derive(serde::Serialize, Debug)] pub struct PartnerReferralRestApiIntegration { pub integration_method: IntegrationMethod, pub integration_type: PayPalIntegrationType, pub third_party_details: PartnerReferralThirdPartyDetails, } #[derive(serde::Serialize, Debug)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum IntegrationMethod { Paypal, } #[derive(serde::Serialize, Debug)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PayPalIntegrationType { ThirdParty, } #[derive(serde::Serialize, Debug)] pub struct PartnerReferralThirdPartyDetails { pub features: Vec<PayPalFeatures>, } #[derive(serde::Serialize, Debug)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PayPalFeatures { Payment, Refund, Vault, AccessMerchantInformation, BillingAgreement, ReadSellerDispute, } #[derive(serde::Serialize, Debug)] pub struct PartnerConfigOverride { pub partner_logo_url: String, pub return_url: String, } #[derive(serde::Serialize, Debug)] pub struct LegalConsent { #[serde(rename = "type")] pub consent_type: LegalConsentType, pub granted: bool, } #[derive(serde::Serialize, Debug)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum LegalConsentType { ShareDataConsent, } impl PartnerReferralRequest { pub fn new(tracking_id: String, return_url: String) -> Self { Self { tracking_id, operations: vec![PartnerReferralOperations { operation: PayPalReferralOperationType::ApiIntegration, api_integration_preference: PartnerReferralIntegrationPreference { rest_api_integration: PartnerReferralRestApiIntegration { integration_method: IntegrationMethod::Paypal, integration_type: PayPalIntegrationType::ThirdParty, third_party_details: PartnerReferralThirdPartyDetails { features: vec![ PayPalFeatures::Payment, PayPalFeatures::Refund, PayPalFeatures::Vault, PayPalFeatures::AccessMerchantInformation, PayPalFeatures::BillingAgreement, PayPalFeatures::ReadSellerDispute, ], }, }, }, }], products: vec![PayPalProducts::Ppcp, PayPalProducts::AdvancedVaulting], capabilities: vec![PayPalCapabilities::PaypalWalletVaultingAdvanced], partner_config_override: PartnerConfigOverride { partner_logo_url: "https://hyperswitch.io/img/websiteIcon.svg".to_string(), return_url, }, legal_consents: vec![LegalConsent { consent_type: LegalConsentType::ShareDataConsent, granted: true, }], } } } #[derive(serde::Deserialize, Debug)] pub struct SellerStatusResponse { pub merchant_id: common_utils::id_type::MerchantId, pub links: Vec<HateoasLink>, } #[derive(serde::Deserialize, Debug)] pub struct SellerStatusDetailsResponse { pub merchant_id: common_utils::id_type::MerchantId, pub primary_email_confirmed: bool, pub payments_receivable: bool, pub products: Vec<SellerStatusProducts>, } #[derive(serde::Deserialize, Debug)] pub struct SellerStatusProducts { pub name: String, pub vetting_status: Option<VettingStatus>, } #[derive(serde::Deserialize, Debug, Clone)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum VettingStatus { NeedMoreData, Subscribed, Denied, } impl SellerStatusResponse { pub fn extract_merchant_details_url(self, paypal_base_url: &str) -> RouterResult<String> { self.links .first() .and_then(|link| link.href.strip_prefix('/')) .map(|link| format!("{paypal_base_url}{link}")) .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Merchant details not received in onboarding status") } } impl SellerStatusDetailsResponse { pub fn check_payments_receivable(&self) -> Option<api::PayPalOnboardingStatus> { if !self.payments_receivable { return Some(api::PayPalOnboardingStatus::PaymentsNotReceivable); } None } pub fn check_ppcp_custom_status(&self) -> Option<api::PayPalOnboardingStatus> { match self.get_ppcp_custom_status() { Some(VettingStatus::Denied) => Some(api::PayPalOnboardingStatus::PpcpCustomDenied), Some(VettingStatus::Subscribed) => None, _ => Some(api::PayPalOnboardingStatus::MorePermissionsNeeded), } } fn check_email_confirmation(&self) -> Option<api::PayPalOnboardingStatus> { if !self.primary_email_confirmed { return Some(api::PayPalOnboardingStatus::EmailNotVerified); } None } pub async fn get_eligibility_status(&self) -> RouterResult<api::PayPalOnboardingStatus> { Ok(self .check_payments_receivable() .or(self.check_email_confirmation()) .or(self.check_ppcp_custom_status()) .unwrap_or(api::PayPalOnboardingStatus::Success( api::PayPalOnboardingDone { payer_id: self.get_payer_id(), }, ))) } fn get_ppcp_custom_status(&self) -> Option<VettingStatus> { self.products .iter() .find(|product| product.name == "PPCP_CUSTOM") .and_then(|ppcp_custom| ppcp_custom.vetting_status.clone()) } fn get_payer_id(&self) -> common_utils::id_type::MerchantId { self.merchant_id.to_owned() } } impl PartnerReferralResponse { pub fn extract_action_url(self) -> RouterResult<String> { Ok(self .links .into_iter() .find(|hateoas_link| hateoas_link.rel == "action_url") .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get action_url from paypal response")? .href) } }
{ "crate": "router", "file": "crates/router/src/types/api/connector_onboarding/paypal.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 8, "num_structs": 12, "num_tables": null, "score": null, "total_crates": null }
file_router_-5062530007062652132
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/domain/address.rs // Contains: 3 structs, 1 enums use async_trait::async_trait; use common_utils::{ crypto::{self, Encryptable}, date_time, encryption::Encryption, errors::{CustomResult, ValidationError}, id_type, pii, type_name, types::keymanager::{Identifier, KeyManagerState, ToEncryptable}, }; use diesel_models::{address::AddressUpdateInternal, enums}; use error_stack::ResultExt; use masking::{PeekInterface, Secret, SwitchStrategy}; use rustc_hash::FxHashMap; use time::{OffsetDateTime, PrimitiveDateTime}; use super::{behaviour, types}; #[derive(Clone, Debug, serde::Serialize, router_derive::ToEncryption)] pub struct Address { pub address_id: String, pub city: Option<String>, pub country: Option<enums::CountryAlpha2>, #[encrypt] pub line1: Option<Encryptable<Secret<String>>>, #[encrypt] pub line2: Option<Encryptable<Secret<String>>>, #[encrypt] pub line3: Option<Encryptable<Secret<String>>>, #[encrypt] pub state: Option<Encryptable<Secret<String>>>, #[encrypt] pub zip: Option<Encryptable<Secret<String>>>, #[encrypt] pub first_name: Option<Encryptable<Secret<String>>>, #[encrypt] pub last_name: Option<Encryptable<Secret<String>>>, #[encrypt] pub phone_number: Option<Encryptable<Secret<String>>>, pub country_code: Option<String>, #[serde(skip_serializing)] #[serde(with = "custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(skip_serializing)] #[serde(with = "custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub merchant_id: id_type::MerchantId, pub updated_by: String, #[encrypt] pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>, #[encrypt] pub origin_zip: Option<Encryptable<Secret<String>>>, } /// Based on the flow, appropriate address has to be used /// In case of Payments, The `PaymentAddress`[PaymentAddress] has to be used /// which contains only the `Address`[Address] object and `payment_id` and optional `customer_id` #[derive(Debug, Clone)] pub struct PaymentAddress { pub address: Address, pub payment_id: id_type::PaymentId, // This is present in `PaymentAddress` because even `payouts` uses `PaymentAddress` pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, Clone)] pub struct CustomerAddress { pub address: Address, pub customer_id: id_type::CustomerId, } #[async_trait] impl behaviour::Conversion for CustomerAddress { type DstType = diesel_models::address::Address; type NewDstType = diesel_models::address::AddressNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { let converted_address = Address::convert(self.address).await?; Ok(diesel_models::address::Address { customer_id: Some(self.customer_id), payment_id: None, ..converted_address }) } async fn convert_back( state: &KeyManagerState, other: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: Identifier, ) -> CustomResult<Self, ValidationError> { let customer_id = other .customer_id .clone() .ok_or(ValidationError::MissingRequiredField { field_name: "customer_id".to_string(), })?; let address = Address::convert_back(state, other, key, key_manager_identifier).await?; Ok(Self { address, customer_id, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let address_new = Address::construct_new(self.address).await?; Ok(Self::NewDstType { customer_id: Some(self.customer_id), payment_id: None, ..address_new }) } } #[async_trait] impl behaviour::Conversion for PaymentAddress { type DstType = diesel_models::address::Address; type NewDstType = diesel_models::address::AddressNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { let converted_address = Address::convert(self.address).await?; Ok(diesel_models::address::Address { customer_id: self.customer_id, payment_id: Some(self.payment_id), ..converted_address }) } async fn convert_back( state: &KeyManagerState, other: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: Identifier, ) -> CustomResult<Self, ValidationError> { let payment_id = other .payment_id .clone() .ok_or(ValidationError::MissingRequiredField { field_name: "payment_id".to_string(), })?; let customer_id = other.customer_id.clone(); let address = Address::convert_back(state, other, key, key_manager_identifier).await?; Ok(Self { address, payment_id, customer_id, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let address_new = Address::construct_new(self.address).await?; Ok(Self::NewDstType { customer_id: self.customer_id, payment_id: Some(self.payment_id), ..address_new }) } } #[async_trait] impl behaviour::Conversion for Address { type DstType = diesel_models::address::Address; type NewDstType = diesel_models::address::AddressNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::address::Address { address_id: self.address_id, city: self.city, country: self.country, line1: self.line1.map(Encryption::from), line2: self.line2.map(Encryption::from), line3: self.line3.map(Encryption::from), state: self.state.map(Encryption::from), zip: self.zip.map(Encryption::from), first_name: self.first_name.map(Encryption::from), last_name: self.last_name.map(Encryption::from), phone_number: self.phone_number.map(Encryption::from), country_code: self.country_code, created_at: self.created_at, modified_at: self.modified_at, merchant_id: self.merchant_id, updated_by: self.updated_by, email: self.email.map(Encryption::from), payment_id: None, customer_id: None, origin_zip: self.origin_zip.map(Encryption::from), }) } async fn convert_back( state: &KeyManagerState, other: Self::DstType, key: &Secret<Vec<u8>>, _key_manager_identifier: Identifier, ) -> CustomResult<Self, ValidationError> { let identifier = Identifier::Merchant(other.merchant_id.clone()); let decrypted: FxHashMap<String, Encryptable<Secret<String>>> = types::crypto_operation( state, type_name!(Self::DstType), types::CryptoOperation::BatchDecrypt(EncryptedAddress::to_encryptable( EncryptedAddress { line1: other.line1, line2: other.line2, line3: other.line3, state: other.state, zip: other.zip, first_name: other.first_name, last_name: other.last_name, phone_number: other.phone_number, email: other.email, origin_zip: other.origin_zip, }, )), identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(ValidationError::InvalidValue { message: "Failed while decrypting".to_string(), })?; let encryptable_address = EncryptedAddress::from_encryptable(decrypted).change_context( ValidationError::InvalidValue { message: "Failed while decrypting".to_string(), }, )?; Ok(Self { address_id: other.address_id, city: other.city, country: other.country, line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, state: encryptable_address.state, zip: encryptable_address.zip, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: other.country_code, created_at: other.created_at, modified_at: other.modified_at, updated_by: other.updated_by, merchant_id: other.merchant_id, email: encryptable_address.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), origin_zip: encryptable_address.origin_zip, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let now = date_time::now(); Ok(Self::NewDstType { address_id: self.address_id, city: self.city, country: self.country, line1: self.line1.map(Encryption::from), line2: self.line2.map(Encryption::from), line3: self.line3.map(Encryption::from), state: self.state.map(Encryption::from), zip: self.zip.map(Encryption::from), first_name: self.first_name.map(Encryption::from), last_name: self.last_name.map(Encryption::from), phone_number: self.phone_number.map(Encryption::from), country_code: self.country_code, merchant_id: self.merchant_id, created_at: now, modified_at: now, updated_by: self.updated_by, email: self.email.map(Encryption::from), customer_id: None, payment_id: None, origin_zip: self.origin_zip.map(Encryption::from), }) } } #[derive(Debug, Clone)] pub enum AddressUpdate { Update { city: Option<String>, country: Option<enums::CountryAlpha2>, line1: crypto::OptionalEncryptableSecretString, line2: crypto::OptionalEncryptableSecretString, line3: crypto::OptionalEncryptableSecretString, state: crypto::OptionalEncryptableSecretString, zip: crypto::OptionalEncryptableSecretString, first_name: crypto::OptionalEncryptableSecretString, last_name: crypto::OptionalEncryptableSecretString, phone_number: crypto::OptionalEncryptableSecretString, country_code: Option<String>, updated_by: String, email: crypto::OptionalEncryptableEmail, origin_zip: crypto::OptionalEncryptableSecretString, }, } impl From<AddressUpdate> for AddressUpdateInternal { fn from(address_update: AddressUpdate) -> Self { match address_update { AddressUpdate::Update { city, country, line1, line2, line3, state, zip, first_name, last_name, phone_number, country_code, updated_by, email, origin_zip, } => Self { city, country, line1: line1.map(Encryption::from), line2: line2.map(Encryption::from), line3: line3.map(Encryption::from), state: state.map(Encryption::from), zip: zip.map(Encryption::from), first_name: first_name.map(Encryption::from), last_name: last_name.map(Encryption::from), phone_number: phone_number.map(Encryption::from), country_code, modified_at: date_time::convert_to_pdt(OffsetDateTime::now_utc()), updated_by, email: email.map(Encryption::from), origin_zip: origin_zip.map(Encryption::from), }, } } }
{ "crate": "router", "file": "crates/router/src/types/domain/address.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_router_3311481318934360305
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/domain/event.rs // Contains: 1 structs, 1 enums use common_utils::{ crypto::{Encryptable, OptionalEncryptableSecretString}, encryption::Encryption, type_name, types::keymanager::{KeyManagerState, ToEncryptable}, }; use diesel_models::{ enums::{EventClass, EventObjectType, EventType, WebhookDeliveryAttempt}, events::{EventMetadata, EventUpdateInternal}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; use rustc_hash::FxHashMap; use crate::{ errors::{CustomResult, ValidationError}, types::domain::types, }; #[derive(Clone, Debug, router_derive::ToEncryption)] pub struct Event { /// A string that uniquely identifies the event. pub event_id: String, /// Represents the type of event for the webhook. pub event_type: EventType, /// Represents the class of event for the webhook. pub event_class: EventClass, /// Indicates whether the current webhook delivery was successful. pub is_webhook_notified: bool, /// Reference to the object for which the webhook was created. pub primary_object_id: String, /// Type of the object type for which the webhook was created. pub primary_object_type: EventObjectType, /// The timestamp when the webhook was created. pub created_at: time::PrimitiveDateTime, /// Merchant Account identifier to which the object is associated with. pub merchant_id: Option<common_utils::id_type::MerchantId>, /// Business Profile identifier to which the object is associated with. pub business_profile_id: Option<common_utils::id_type::ProfileId>, /// The timestamp when the primary object was created. pub primary_object_created_at: Option<time::PrimitiveDateTime>, /// This allows the event to be uniquely identified to prevent multiple processing. pub idempotent_event_id: Option<String>, /// Links to the initial attempt of the event. pub initial_attempt_id: Option<String>, /// This field contains the encrypted request data sent as part of the event. #[encrypt] pub request: Option<Encryptable<Secret<String>>>, /// This field contains the encrypted response data received as part of the event. #[encrypt] pub response: Option<Encryptable<Secret<String>>>, /// Represents the event delivery type. pub delivery_attempt: Option<WebhookDeliveryAttempt>, /// Holds any additional data related to the event. pub metadata: Option<EventMetadata>, /// Indicates whether the event was ultimately delivered. pub is_overall_delivery_successful: Option<bool>, } #[derive(Debug)] pub enum EventUpdate { UpdateResponse { is_webhook_notified: bool, response: OptionalEncryptableSecretString, }, OverallDeliveryStatusUpdate { is_overall_delivery_successful: bool, }, } impl From<EventUpdate> for EventUpdateInternal { fn from(event_update: EventUpdate) -> Self { match event_update { EventUpdate::UpdateResponse { is_webhook_notified, response, } => Self { is_webhook_notified: Some(is_webhook_notified), response: response.map(Into::into), is_overall_delivery_successful: None, }, EventUpdate::OverallDeliveryStatusUpdate { is_overall_delivery_successful, } => Self { is_webhook_notified: None, response: None, is_overall_delivery_successful: Some(is_overall_delivery_successful), }, } } } #[async_trait::async_trait] impl super::behaviour::Conversion for Event { type DstType = diesel_models::events::Event; type NewDstType = diesel_models::events::EventNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::events::Event { event_id: self.event_id, event_type: self.event_type, event_class: self.event_class, is_webhook_notified: self.is_webhook_notified, primary_object_id: self.primary_object_id, primary_object_type: self.primary_object_type, created_at: self.created_at, merchant_id: self.merchant_id, business_profile_id: self.business_profile_id, primary_object_created_at: self.primary_object_created_at, idempotent_event_id: self.idempotent_event_id, initial_attempt_id: self.initial_attempt_id, request: self.request.map(Into::into), response: self.response.map(Into::into), delivery_attempt: self.delivery_attempt, metadata: self.metadata, is_overall_delivery_successful: self.is_overall_delivery_successful, }) } async fn convert_back( state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: common_utils::types::keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { let decrypted = types::crypto_operation( state, type_name!(Self::DstType), types::CryptoOperation::BatchDecrypt(EncryptedEvent::to_encryptable(EncryptedEvent { request: item.request.clone(), response: item.response.clone(), })), key_manager_identifier, key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(ValidationError::InvalidValue { message: "Failed while decrypting event data".to_string(), })?; let encryptable_event = EncryptedEvent::from_encryptable(decrypted).change_context( ValidationError::InvalidValue { message: "Failed while decrypting event data".to_string(), }, )?; Ok(Self { event_id: item.event_id, event_type: item.event_type, event_class: item.event_class, is_webhook_notified: item.is_webhook_notified, primary_object_id: item.primary_object_id, primary_object_type: item.primary_object_type, created_at: item.created_at, merchant_id: item.merchant_id, business_profile_id: item.business_profile_id, primary_object_created_at: item.primary_object_created_at, idempotent_event_id: item.idempotent_event_id, initial_attempt_id: item.initial_attempt_id, request: encryptable_event.request, response: encryptable_event.response, delivery_attempt: item.delivery_attempt, metadata: item.metadata, is_overall_delivery_successful: item.is_overall_delivery_successful, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(diesel_models::events::EventNew { event_id: self.event_id, event_type: self.event_type, event_class: self.event_class, is_webhook_notified: self.is_webhook_notified, primary_object_id: self.primary_object_id, primary_object_type: self.primary_object_type, created_at: self.created_at, merchant_id: self.merchant_id, business_profile_id: self.business_profile_id, primary_object_created_at: self.primary_object_created_at, idempotent_event_id: self.idempotent_event_id, initial_attempt_id: self.initial_attempt_id, request: self.request.map(Into::into), response: self.response.map(Into::into), delivery_attempt: self.delivery_attempt, metadata: self.metadata, is_overall_delivery_successful: self.is_overall_delivery_successful, }) } }
{ "crate": "router", "file": "crates/router/src/types/domain/event.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-8592499810404010108
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/domain/user.rs // Contains: 19 structs, 0 enums use std::{ collections::HashSet, ops::{Deref, Not}, str::FromStr, sync::LazyLock, }; use api_models::{ admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api, }; use common_enums::EntityType; use common_utils::{ crypto::Encryptable, id_type, new_type::MerchantName, pii, type_name, types::keymanager::Identifier, }; use diesel_models::{ enums::{TotpStatus, UserRoleVersion, UserStatus}, organization::{self as diesel_org, Organization, OrganizationBridge}, user as storage_user, user_role::{UserRole, UserRoleNew}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::api::ApplicationResponse; use masking::{ExposeInterface, PeekInterface, Secret}; use rand::distributions::{Alphanumeric, DistString}; use time::PrimitiveDateTime; use unicode_segmentation::UnicodeSegmentation; #[cfg(feature = "keymanager_create")] use {base64::Engine, common_utils::types::keymanager::EncryptionTransferRequest}; use crate::{ consts, core::{ admin, errors::{UserErrors, UserResult}, }, db::GlobalStorageInterface, routes::SessionState, services::{ self, authentication::{AuthenticationDataWithOrg, UserFromToken}, }, types::{domain, transformers::ForeignFrom}, utils::{self, user::password}, }; pub mod dashboard_metadata; pub mod decision_manager; pub use decision_manager::*; pub mod user_authentication_method; use super::{types as domain_types, UserKeyStore}; #[derive(Clone)] pub struct UserName(Secret<String>); impl UserName { pub fn new(name: Secret<String>) -> UserResult<Self> { let name = name.expose(); let is_empty_or_whitespace = name.trim().is_empty(); let is_too_long = name.graphemes(true).count() > consts::user::MAX_NAME_LENGTH; let forbidden_characters = ['/', '(', ')', '"', '<', '>', '\\', '{', '}']; let contains_forbidden_characters = name.chars().any(|g| forbidden_characters.contains(&g)); if is_empty_or_whitespace || is_too_long || contains_forbidden_characters { Err(UserErrors::NameParsingError.into()) } else { Ok(Self(name.into())) } } pub fn get_secret(self) -> Secret<String> { self.0 } } impl TryFrom<pii::Email> for UserName { type Error = error_stack::Report<UserErrors>; fn try_from(value: pii::Email) -> UserResult<Self> { Self::new(Secret::new( value .peek() .split_once('@') .ok_or(UserErrors::InvalidEmailError)? .0 .to_string(), )) } } #[derive(Clone, Debug)] pub struct UserEmail(pii::Email); static BLOCKED_EMAIL: LazyLock<HashSet<String>> = LazyLock::new(|| { let blocked_emails_content = include_str!("../../utils/user/blocker_emails.txt"); let blocked_emails: HashSet<String> = blocked_emails_content .lines() .map(|s| s.trim().to_owned()) .collect(); blocked_emails }); impl UserEmail { pub fn new(email: Secret<String, pii::EmailStrategy>) -> UserResult<Self> { use validator::ValidateEmail; let email_string = email.expose().to_lowercase(); let email = pii::Email::from_str(&email_string).change_context(UserErrors::EmailParsingError)?; if email_string.validate_email() { let (_username, domain) = match email_string.as_str().split_once('@') { Some((u, d)) => (u, d), None => return Err(UserErrors::EmailParsingError.into()), }; if BLOCKED_EMAIL.contains(domain) { return Err(UserErrors::InvalidEmailError.into()); } Ok(Self(email)) } else { Err(UserErrors::EmailParsingError.into()) } } pub fn from_pii_email(email: pii::Email) -> UserResult<Self> { let email_string = email.expose().map(|inner| inner.to_lowercase()); Self::new(email_string) } pub fn into_inner(self) -> pii::Email { self.0 } pub fn get_inner(&self) -> &pii::Email { &self.0 } pub fn get_secret(self) -> Secret<String, pii::EmailStrategy> { (*self.0).clone() } pub fn extract_domain(&self) -> UserResult<&str> { let (_username, domain) = self .peek() .split_once('@') .ok_or(UserErrors::InternalServerError)?; Ok(domain) } } impl TryFrom<pii::Email> for UserEmail { type Error = error_stack::Report<UserErrors>; fn try_from(value: pii::Email) -> Result<Self, Self::Error> { Self::from_pii_email(value) } } impl Deref for UserEmail { type Target = Secret<String, pii::EmailStrategy>; fn deref(&self) -> &Self::Target { &self.0 } } #[derive(Clone)] pub struct UserPassword(Secret<String>); impl UserPassword { pub fn new(password: Secret<String>) -> UserResult<Self> { let password = password.expose(); let mut has_upper_case = false; let mut has_lower_case = false; let mut has_numeric_value = false; let mut has_special_character = false; let mut has_whitespace = false; for c in password.chars() { has_upper_case = has_upper_case || c.is_uppercase(); has_lower_case = has_lower_case || c.is_lowercase(); has_numeric_value = has_numeric_value || c.is_numeric(); has_special_character = has_special_character || !c.is_alphanumeric(); has_whitespace = has_whitespace || c.is_whitespace(); } let is_password_format_valid = has_upper_case && has_lower_case && has_numeric_value && has_special_character && !has_whitespace; let is_too_long = password.graphemes(true).count() > consts::user::MAX_PASSWORD_LENGTH; let is_too_short = password.graphemes(true).count() < consts::user::MIN_PASSWORD_LENGTH; if is_too_short || is_too_long || !is_password_format_valid { return Err(UserErrors::PasswordParsingError.into()); } Ok(Self(password.into())) } pub fn new_password_without_validation(password: Secret<String>) -> UserResult<Self> { let password = password.expose(); if password.is_empty() { return Err(UserErrors::PasswordParsingError.into()); } Ok(Self(password.into())) } pub fn get_secret(&self) -> Secret<String> { self.0.clone() } } #[derive(Clone)] pub struct UserCompanyName(String); impl UserCompanyName { pub fn new(company_name: String) -> UserResult<Self> { let company_name = company_name.trim(); let is_empty_or_whitespace = company_name.is_empty(); let is_too_long = company_name.graphemes(true).count() > consts::user::MAX_COMPANY_NAME_LENGTH; let is_all_valid_characters = company_name .chars() .all(|x| x.is_alphanumeric() || x.is_ascii_whitespace() || x == '_'); if is_empty_or_whitespace || is_too_long || !is_all_valid_characters { Err(UserErrors::CompanyNameParsingError.into()) } else { Ok(Self(company_name.to_string())) } } pub fn get_secret(self) -> String { self.0 } } #[derive(Clone)] pub struct NewUserOrganization(diesel_org::OrganizationNew); impl NewUserOrganization { pub async fn insert_org_in_db(self, state: SessionState) -> UserResult<Organization> { state .accounts_store .insert_organization(self.0) .await .map_err(|e| { if e.current_context().is_db_unique_violation() { e.change_context(UserErrors::DuplicateOrganizationId) } else { e.change_context(UserErrors::InternalServerError) } }) .attach_printable("Error while inserting organization") } pub fn get_organization_id(&self) -> id_type::OrganizationId { self.0.get_organization_id() } } impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUserOrganization { type Error = error_stack::Report<UserErrors>; fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult<Self> { let new_organization = api_org::OrganizationNew::new( common_enums::OrganizationType::Standard, Some(UserCompanyName::new(value.company_name)?.get_secret()), ); let db_organization = ForeignFrom::foreign_from(new_organization); Ok(Self(db_organization)) } } impl From<user_api::SignUpRequest> for NewUserOrganization { fn from(_value: user_api::SignUpRequest) -> Self { let new_organization = api_org::OrganizationNew::new(common_enums::OrganizationType::Standard, None); let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } } impl From<user_api::ConnectAccountRequest> for NewUserOrganization { fn from(_value: user_api::ConnectAccountRequest) -> Self { let new_organization = api_org::OrganizationNew::new(common_enums::OrganizationType::Standard, None); let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } } impl From<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for NewUserOrganization { fn from( (_value, org_id): (user_api::CreateInternalUserRequest, id_type::OrganizationId), ) -> Self { let new_organization = api_org::OrganizationNew { org_id, org_type: common_enums::OrganizationType::Standard, org_name: None, }; let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } } impl From<UserMerchantCreateRequestWithToken> for NewUserOrganization { fn from(value: UserMerchantCreateRequestWithToken) -> Self { Self(diesel_org::OrganizationNew::new( value.2.org_id, common_enums::OrganizationType::Standard, Some(value.1.company_name), )) } } impl From<user_api::PlatformAccountCreateRequest> for NewUserOrganization { fn from(value: user_api::PlatformAccountCreateRequest) -> Self { let new_organization = api_org::OrganizationNew::new( common_enums::OrganizationType::Platform, Some(value.organization_name.expose()), ); let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } } type InviteeUserRequestWithInvitedUserToken = (user_api::InviteUserRequest, UserFromToken); impl From<InviteeUserRequestWithInvitedUserToken> for NewUserOrganization { fn from(_value: InviteeUserRequestWithInvitedUserToken) -> Self { let new_organization = api_org::OrganizationNew::new(common_enums::OrganizationType::Standard, None); let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } } impl From<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)> for NewUserOrganization { fn from( (_value, merchant_account_identifier): ( user_api::CreateTenantUserRequest, MerchantAccountIdentifier, ), ) -> Self { let new_organization = api_org::OrganizationNew { org_id: merchant_account_identifier.org_id, org_type: common_enums::OrganizationType::Standard, org_name: None, }; let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } } impl ForeignFrom<api_models::user::UserOrgMerchantCreateRequest> for diesel_models::organization::OrganizationNew { fn foreign_from(item: api_models::user::UserOrgMerchantCreateRequest) -> Self { let org_id = id_type::OrganizationId::default(); let api_models::user::UserOrgMerchantCreateRequest { organization_name, organization_details, metadata, .. } = item; let mut org_new_db = Self::new( org_id, common_enums::OrganizationType::Standard, Some(organization_name.expose()), ); org_new_db.organization_details = organization_details; org_new_db.metadata = metadata; org_new_db } } #[derive(Clone)] pub struct MerchantId(String); impl MerchantId { pub fn new(merchant_id: String) -> UserResult<Self> { let merchant_id = merchant_id.trim().to_lowercase().replace(' ', "_"); let is_empty_or_whitespace = merchant_id.is_empty(); let is_all_valid_characters = merchant_id.chars().all(|x| x.is_alphanumeric() || x == '_'); if is_empty_or_whitespace || !is_all_valid_characters { Err(UserErrors::MerchantIdParsingError.into()) } else { Ok(Self(merchant_id.to_string())) } } pub fn get_secret(&self) -> String { self.0.clone() } } impl TryFrom<MerchantId> for id_type::MerchantId { type Error = error_stack::Report<UserErrors>; fn try_from(value: MerchantId) -> Result<Self, Self::Error> { Self::try_from(std::borrow::Cow::from(value.0)) .change_context(UserErrors::MerchantIdParsingError) .attach_printable("Could not convert user merchant_id to merchant_id type") } } #[derive(Clone)] pub struct NewUserMerchant { merchant_id: id_type::MerchantId, company_name: Option<UserCompanyName>, new_organization: NewUserOrganization, product_type: Option<common_enums::MerchantProductType>, merchant_account_type: Option<common_enums::MerchantAccountRequestType>, } impl TryFrom<UserCompanyName> for MerchantName { // We should ideally not get this error because all the validations are done for company name type Error = error_stack::Report<UserErrors>; fn try_from(company_name: UserCompanyName) -> Result<Self, Self::Error> { Self::try_new(company_name.get_secret()).change_context(UserErrors::CompanyNameParsingError) } } impl NewUserMerchant { pub fn get_company_name(&self) -> Option<String> { self.company_name.clone().map(UserCompanyName::get_secret) } pub fn get_merchant_id(&self) -> id_type::MerchantId { self.merchant_id.clone() } pub fn get_new_organization(&self) -> NewUserOrganization { self.new_organization.clone() } pub fn get_product_type(&self) -> Option<common_enums::MerchantProductType> { self.product_type } pub async fn check_if_already_exists_in_db(&self, state: SessionState) -> UserResult<()> { if state .store .get_merchant_key_store_by_merchant_id( &(&state).into(), &self.get_merchant_id(), &state.store.get_master_key().to_vec().into(), ) .await .is_ok() { return Err(UserErrors::MerchantAccountCreationError(format!( "Merchant with {:?} already exists", self.get_merchant_id() )) .into()); } Ok(()) } #[cfg(feature = "v2")] fn create_merchant_account_request(&self) -> UserResult<admin_api::MerchantAccountCreate> { let merchant_name = if let Some(company_name) = self.company_name.clone() { MerchantName::try_from(company_name) } else { MerchantName::try_new("merchant".to_string()) .change_context(UserErrors::InternalServerError) .attach_printable("merchant name validation failed") } .map(Secret::new)?; Ok(admin_api::MerchantAccountCreate { merchant_name, organization_id: self.new_organization.get_organization_id(), metadata: None, merchant_details: None, product_type: self.get_product_type(), }) } #[cfg(feature = "v1")] fn create_merchant_account_request(&self) -> UserResult<admin_api::MerchantAccountCreate> { Ok(admin_api::MerchantAccountCreate { merchant_id: self.get_merchant_id(), metadata: None, locker_id: None, return_url: None, merchant_name: self.get_company_name().map(Secret::new), webhook_details: None, publishable_key: None, organization_id: Some(self.new_organization.get_organization_id()), merchant_details: None, routing_algorithm: None, parent_merchant_id: None, sub_merchants_enabled: None, frm_routing_algorithm: None, #[cfg(feature = "payouts")] payout_routing_algorithm: None, primary_business_details: None, payment_response_hash_key: None, enable_payment_response_hash: None, redirect_to_merchant_with_http_post: None, pm_collect_link_config: None, product_type: self.get_product_type(), merchant_account_type: self.merchant_account_type, }) } #[cfg(feature = "v1")] pub async fn create_new_merchant_and_insert_in_db( &self, state: SessionState, ) -> UserResult<domain::MerchantAccount> { self.check_if_already_exists_in_db(state.clone()).await?; let merchant_account_create_request = self .create_merchant_account_request() .attach_printable("Unable to construct merchant account create request")?; let org_id = merchant_account_create_request .clone() .organization_id .ok_or(UserErrors::InternalServerError)?; let ApplicationResponse::Json(merchant_account_response) = Box::pin(admin::create_merchant_account( state.clone(), merchant_account_create_request, Some(AuthenticationDataWithOrg { organization_id: org_id, }), )) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error while creating merchant")? else { return Err(UserErrors::InternalServerError.into()); }; let key_manager_state = &(&state).into(); let merchant_key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_account_response.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to retrieve merchant key store by merchant_id")?; let merchant_account = state .store .find_merchant_account_by_merchant_id( key_manager_state, &merchant_account_response.merchant_id, &merchant_key_store, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to retrieve merchant account by merchant_id")?; Ok(merchant_account) } #[cfg(feature = "v2")] pub async fn create_new_merchant_and_insert_in_db( &self, state: SessionState, ) -> UserResult<domain::MerchantAccount> { self.check_if_already_exists_in_db(state.clone()).await?; let merchant_account_create_request = self .create_merchant_account_request() .attach_printable("unable to construct merchant account create request")?; let ApplicationResponse::Json(merchant_account_response) = Box::pin( admin::create_merchant_account(state.clone(), merchant_account_create_request, None), ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error while creating a merchant")? else { return Err(UserErrors::InternalServerError.into()); }; let profile_create_request = admin_api::ProfileCreate { profile_name: consts::user::DEFAULT_PROFILE_NAME.to_string(), ..Default::default() }; let key_manager_state = &(&state).into(); let merchant_key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_account_response.id, &state.store.get_master_key().to_vec().into(), ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to retrieve merchant key store by merchant_id")?; let merchant_account = state .store .find_merchant_account_by_merchant_id( key_manager_state, &merchant_account_response.id, &merchant_key_store, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to retrieve merchant account by merchant_id")?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), merchant_key_store, ))); Box::pin(admin::create_profile( state, profile_create_request, merchant_context, )) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error while creating a profile")?; Ok(merchant_account) } } impl TryFrom<user_api::SignUpRequest> for NewUserMerchant { type Error = error_stack::Report<UserErrors>; fn try_from(value: user_api::SignUpRequest) -> UserResult<Self> { let merchant_id = id_type::MerchantId::new_from_unix_timestamp(); let new_organization = NewUserOrganization::from(value); let product_type = Some(consts::user::DEFAULT_PRODUCT_TYPE); Ok(Self { company_name: None, merchant_id, new_organization, product_type, merchant_account_type: None, }) } } impl TryFrom<user_api::ConnectAccountRequest> for NewUserMerchant { type Error = error_stack::Report<UserErrors>; fn try_from(value: user_api::ConnectAccountRequest) -> UserResult<Self> { let merchant_id = id_type::MerchantId::new_from_unix_timestamp(); let new_organization = NewUserOrganization::from(value); let product_type = Some(consts::user::DEFAULT_PRODUCT_TYPE); Ok(Self { company_name: None, merchant_id, new_organization, product_type, merchant_account_type: None, }) } } impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUserMerchant { type Error = error_stack::Report<UserErrors>; fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult<Self> { let company_name = Some(UserCompanyName::new(value.company_name.clone())?); let merchant_id = MerchantId::new(value.company_name.clone())?; let new_organization = NewUserOrganization::try_from(value)?; let product_type = Some(consts::user::DEFAULT_PRODUCT_TYPE); Ok(Self { company_name, merchant_id: id_type::MerchantId::try_from(merchant_id)?, new_organization, product_type, merchant_account_type: None, }) } } impl TryFrom<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for NewUserMerchant { type Error = error_stack::Report<UserErrors>; fn try_from( value: (user_api::CreateInternalUserRequest, id_type::OrganizationId), ) -> UserResult<Self> { let merchant_id = id_type::MerchantId::get_internal_user_merchant_id( consts::user_role::INTERNAL_USER_MERCHANT_ID, ); let new_organization = NewUserOrganization::from(value); Ok(Self { company_name: None, merchant_id, new_organization, product_type: None, merchant_account_type: None, }) } } impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUserMerchant { type Error = error_stack::Report<UserErrors>; fn try_from(value: InviteeUserRequestWithInvitedUserToken) -> UserResult<Self> { let merchant_id = value.clone().1.merchant_id; let new_organization = NewUserOrganization::from(value); Ok(Self { company_name: None, merchant_id, new_organization, product_type: None, merchant_account_type: None, }) } } impl From<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)> for NewUserMerchant { fn from(value: (user_api::CreateTenantUserRequest, MerchantAccountIdentifier)) -> Self { let merchant_id = value.1.merchant_id.clone(); let new_organization = NewUserOrganization::from(value); Self { company_name: None, merchant_id, new_organization, product_type: None, merchant_account_type: None, } } } type UserMerchantCreateRequestWithToken = (UserFromStorage, user_api::UserMerchantCreate, UserFromToken); impl TryFrom<UserMerchantCreateRequestWithToken> for NewUserMerchant { type Error = error_stack::Report<UserErrors>; fn try_from(value: UserMerchantCreateRequestWithToken) -> UserResult<Self> { let merchant_id = utils::user::generate_env_specific_merchant_id(value.1.company_name.clone())?; let (user_from_storage, user_merchant_create, user_from_token) = value; Ok(Self { merchant_id, company_name: Some(UserCompanyName::new( user_merchant_create.company_name.clone(), )?), product_type: user_merchant_create.product_type, merchant_account_type: user_merchant_create.merchant_account_type, new_organization: NewUserOrganization::from(( user_from_storage, user_merchant_create, user_from_token, )), }) } } impl TryFrom<user_api::PlatformAccountCreateRequest> for NewUserMerchant { type Error = error_stack::Report<UserErrors>; fn try_from(value: user_api::PlatformAccountCreateRequest) -> UserResult<Self> { let merchant_id = utils::user::generate_env_specific_merchant_id( value.organization_name.clone().expose(), )?; let new_organization = NewUserOrganization::from(value); Ok(Self { company_name: None, merchant_id, new_organization, product_type: Some(consts::user::DEFAULT_PRODUCT_TYPE), merchant_account_type: None, }) } } #[derive(Debug, Clone)] pub struct MerchantAccountIdentifier { pub merchant_id: id_type::MerchantId, pub org_id: id_type::OrganizationId, } #[derive(Clone)] pub struct NewUser { user_id: String, name: UserName, email: UserEmail, password: Option<NewUserPassword>, new_merchant: NewUserMerchant, } #[derive(Clone)] pub struct NewUserPassword { password: UserPassword, is_temporary: bool, } impl Deref for NewUserPassword { type Target = UserPassword; fn deref(&self) -> &Self::Target { &self.password } } impl NewUser { pub fn get_user_id(&self) -> String { self.user_id.clone() } pub fn get_email(&self) -> UserEmail { self.email.clone() } pub fn get_name(&self) -> Secret<String> { self.name.clone().get_secret() } pub fn get_new_merchant(&self) -> NewUserMerchant { self.new_merchant.clone() } pub fn get_password(&self) -> Option<UserPassword> { self.password .as_ref() .map(|password| password.deref().clone()) } pub async fn insert_user_in_db( &self, db: &dyn GlobalStorageInterface, ) -> UserResult<UserFromStorage> { match db.insert_user(self.clone().try_into()?).await { Ok(user) => Ok(user.into()), Err(e) => { if e.current_context().is_db_unique_violation() { Err(e.change_context(UserErrors::UserExists)) } else { Err(e.change_context(UserErrors::InternalServerError)) } } } .attach_printable("Error while inserting user") } pub async fn check_if_already_exists_in_db(&self, state: SessionState) -> UserResult<()> { if state .global_store .find_user_by_email(&self.get_email()) .await .is_ok() { return Err(report!(UserErrors::UserExists)); } Ok(()) } pub async fn insert_user_and_merchant_in_db( &self, state: SessionState, ) -> UserResult<UserFromStorage> { self.check_if_already_exists_in_db(state.clone()).await?; let db = state.global_store.as_ref(); let merchant_id = self.get_new_merchant().get_merchant_id(); self.new_merchant .create_new_merchant_and_insert_in_db(state.clone()) .await?; let created_user = self.insert_user_in_db(db).await; if created_user.is_err() { let _ = admin::merchant_account_delete(state, merchant_id).await; }; created_user } pub fn get_no_level_user_role( self, role_id: String, user_status: UserStatus, ) -> NewUserRole<NoLevel> { let now = common_utils::date_time::now(); let user_id = self.get_user_id(); NewUserRole { status: user_status, created_by: user_id.clone(), last_modified_by: user_id.clone(), user_id, role_id, created_at: now, last_modified: now, entity: NoLevel, } } pub async fn insert_org_level_user_role_in_db( self, state: SessionState, role_id: String, user_status: UserStatus, ) -> UserResult<UserRole> { let org_id = self .get_new_merchant() .get_new_organization() .get_organization_id(); let org_user_role = self .get_no_level_user_role(role_id, user_status) .add_entity(OrganizationLevel { tenant_id: state.tenant.tenant_id.clone(), org_id, }); org_user_role.insert_in_v2(&state).await } } impl TryFrom<NewUser> for storage_user::UserNew { type Error = error_stack::Report<UserErrors>; fn try_from(value: NewUser) -> UserResult<Self> { let hashed_password = value .password .as_ref() .map(|password| password::generate_password_hash(password.get_secret())) .transpose()?; let now = common_utils::date_time::now(); Ok(Self { user_id: value.get_user_id(), name: value.get_name(), email: value.get_email().into_inner(), password: hashed_password, is_verified: false, created_at: Some(now), last_modified_at: Some(now), totp_status: TotpStatus::NotSet, totp_secret: None, totp_recovery_codes: None, last_password_modified_at: value .password .and_then(|password_inner| password_inner.is_temporary.not().then_some(now)), lineage_context: None, }) } } impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUser { type Error = error_stack::Report<UserErrors>; fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult<Self> { let email = value.email.clone().try_into()?; let name = UserName::new(value.name.clone())?; let password = NewUserPassword { password: UserPassword::new(value.password.clone())?, is_temporary: false, }; let user_id = uuid::Uuid::new_v4().to_string(); let new_merchant = NewUserMerchant::try_from(value)?; Ok(Self { name, email, password: Some(password), user_id, new_merchant, }) } } impl TryFrom<user_api::SignUpRequest> for NewUser { type Error = error_stack::Report<UserErrors>; fn try_from(value: user_api::SignUpRequest) -> UserResult<Self> { let user_id = uuid::Uuid::new_v4().to_string(); let email = value.email.clone().try_into()?; let name = UserName::try_from(value.email.clone())?; let password = NewUserPassword { password: UserPassword::new(value.password.clone())?, is_temporary: false, }; let new_merchant = NewUserMerchant::try_from(value)?; Ok(Self { user_id, name, email, password: Some(password), new_merchant, }) } } impl TryFrom<user_api::ConnectAccountRequest> for NewUser { type Error = error_stack::Report<UserErrors>; fn try_from(value: user_api::ConnectAccountRequest) -> UserResult<Self> { let user_id = uuid::Uuid::new_v4().to_string(); let email = value.email.clone().try_into()?; let name = UserName::try_from(value.email.clone())?; let new_merchant = NewUserMerchant::try_from(value)?; Ok(Self { user_id, name, email, password: None, new_merchant, }) } } impl TryFrom<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for NewUser { type Error = error_stack::Report<UserErrors>; fn try_from( (value, org_id): (user_api::CreateInternalUserRequest, id_type::OrganizationId), ) -> UserResult<Self> { let user_id = uuid::Uuid::new_v4().to_string(); let email = value.email.clone().try_into()?; let name = UserName::new(value.name.clone())?; let password = NewUserPassword { password: UserPassword::new(value.password.clone())?, is_temporary: false, }; let new_merchant = NewUserMerchant::try_from((value, org_id))?; Ok(Self { user_id, name, email, password: Some(password), new_merchant, }) } } impl TryFrom<UserMerchantCreateRequestWithToken> for NewUser { type Error = error_stack::Report<UserErrors>; fn try_from(value: UserMerchantCreateRequestWithToken) -> Result<Self, Self::Error> { let user = value.0.clone(); let new_merchant = NewUserMerchant::try_from(value)?; let password = user .0 .password .map(UserPassword::new_password_without_validation) .transpose()? .map(|password| NewUserPassword { password, is_temporary: false, }); Ok(Self { user_id: user.0.user_id, name: UserName::new(user.0.name)?, email: user.0.email.clone().try_into()?, password, new_merchant, }) } } impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUser { type Error = error_stack::Report<UserErrors>; fn try_from(value: InviteeUserRequestWithInvitedUserToken) -> UserResult<Self> { let user_id = uuid::Uuid::new_v4().to_string(); let email = value.0.email.clone().try_into()?; let name = UserName::new(value.0.name.clone())?; let password = cfg!(not(feature = "email")).then_some(NewUserPassword { password: UserPassword::new(password::get_temp_password())?, is_temporary: true, }); let new_merchant = NewUserMerchant::try_from(value)?; Ok(Self { user_id, name, email, password, new_merchant, }) } } impl TryFrom<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)> for NewUser { type Error = error_stack::Report<UserErrors>; fn try_from( (value, merchant_account_identifier): ( user_api::CreateTenantUserRequest, MerchantAccountIdentifier, ), ) -> UserResult<Self> { let user_id = uuid::Uuid::new_v4().to_string(); let email = value.email.clone().try_into()?; let name = UserName::new(value.name.clone())?; let password = NewUserPassword { password: UserPassword::new(value.password.clone())?, is_temporary: false, }; let new_merchant = NewUserMerchant::from((value, merchant_account_identifier)); Ok(Self { user_id, name, email, password: Some(password), new_merchant, }) } } #[derive(Clone)] pub struct UserFromStorage(pub storage_user::User); impl From<storage_user::User> for UserFromStorage { fn from(value: storage_user::User) -> Self { Self(value) } } impl UserFromStorage { pub fn get_user_id(&self) -> &str { self.0.user_id.as_str() } pub fn compare_password(&self, candidate: &Secret<String>) -> UserResult<()> { if let Some(password) = self.0.password.as_ref() { match password::is_correct_password(candidate, password) { Ok(true) => Ok(()), Ok(false) => Err(UserErrors::InvalidCredentials.into()), Err(e) => Err(e), } } else { Err(UserErrors::InvalidCredentials.into()) } } pub fn get_name(&self) -> Secret<String> { self.0.name.clone() } pub fn get_email(&self) -> pii::Email { self.0.email.clone() } #[cfg(feature = "email")] pub fn get_verification_days_left(&self, state: &SessionState) -> UserResult<Option<i64>> { if self.0.is_verified { return Ok(None); } let allowed_unverified_duration = time::Duration::days(state.conf.email.allowed_unverified_days); let user_created = self.0.created_at.date(); let last_date_for_verification = user_created .checked_add(allowed_unverified_duration) .ok_or(UserErrors::InternalServerError)?; let today = common_utils::date_time::now().date(); if today >= last_date_for_verification { return Err(UserErrors::UnverifiedUser.into()); } let days_left_for_verification = last_date_for_verification - today; Ok(Some(days_left_for_verification.whole_days())) } pub fn is_verified(&self) -> bool { self.0.is_verified } pub fn is_password_rotate_required(&self, state: &SessionState) -> UserResult<bool> { let last_password_modified_at = if let Some(last_password_modified_at) = self.0.last_password_modified_at { last_password_modified_at.date() } else { return Ok(true); }; let password_change_duration = time::Duration::days(state.conf.user.password_validity_in_days.into()); let last_date_for_password_rotate = last_password_modified_at .checked_add(password_change_duration) .ok_or(UserErrors::InternalServerError)?; let today = common_utils::date_time::now().date(); let days_left_for_password_rotate = last_date_for_password_rotate - today; Ok(days_left_for_password_rotate.whole_days() < 0) } pub async fn get_or_create_key_store(&self, state: &SessionState) -> UserResult<UserKeyStore> { let master_key = state.store.get_master_key(); let key_manager_state = &state.into(); let key_store_result = state .global_store .get_user_key_store_by_user_id( key_manager_state, self.get_user_id(), &master_key.to_vec().into(), ) .await; if let Ok(key_store) = key_store_result { Ok(key_store) } else if key_store_result .as_ref() .map_err(|e| e.current_context().is_db_not_found()) .err() .unwrap_or(false) { let key = services::generate_aes256_key() .change_context(UserErrors::InternalServerError) .attach_printable("Unable to generate aes 256 key")?; #[cfg(feature = "keymanager_create")] { common_utils::keymanager::transfer_key_to_key_manager( key_manager_state, EncryptionTransferRequest { identifier: Identifier::User(self.get_user_id().to_string()), key: consts::BASE64_ENGINE.encode(key), }, ) .await .change_context(UserErrors::InternalServerError)?; } let key_store = UserKeyStore { user_id: self.get_user_id().to_string(), key: domain_types::crypto_operation( key_manager_state, type_name!(UserKeyStore), domain_types::CryptoOperation::Encrypt(key.to_vec().into()), Identifier::User(self.get_user_id().to_string()), master_key, ) .await .and_then(|val| val.try_into_operation()) .change_context(UserErrors::InternalServerError)?, created_at: common_utils::date_time::now(), }; state .global_store .insert_user_key_store(key_manager_state, key_store, &master_key.to_vec().into()) .await .change_context(UserErrors::InternalServerError) } else { Err(key_store_result .err() .map(|e| e.change_context(UserErrors::InternalServerError)) .unwrap_or(UserErrors::InternalServerError.into())) } } pub fn get_totp_status(&self) -> TotpStatus { self.0.totp_status } pub fn get_recovery_codes(&self) -> Option<Vec<Secret<String>>> { self.0.totp_recovery_codes.clone() } pub async fn decrypt_and_get_totp_secret( &self, state: &SessionState, ) -> UserResult<Option<Secret<String>>> { if self.0.totp_secret.is_none() { return Ok(None); } let key_manager_state = &state.into(); let user_key_store = state .global_store .get_user_key_store_by_user_id( key_manager_state, self.get_user_id(), &state.store.get_master_key().to_vec().into(), ) .await .change_context(UserErrors::InternalServerError)?; Ok(domain_types::crypto_operation::<String, masking::WithType>( key_manager_state, type_name!(storage_user::User), domain_types::CryptoOperation::DecryptOptional(self.0.totp_secret.clone()), Identifier::User(user_key_store.user_id.clone()), user_key_store.key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) .change_context(UserErrors::InternalServerError)? .map(Encryptable::into_inner)) } } impl ForeignFrom<UserStatus> for user_role_api::UserStatus { fn foreign_from(value: UserStatus) -> Self { match value { UserStatus::Active => Self::Active, UserStatus::InvitationSent => Self::InvitationSent, } } } #[derive(Clone)] pub struct RoleName(String); impl RoleName { pub fn new(name: String) -> UserResult<Self> { let is_empty_or_whitespace = name.trim().is_empty(); let is_too_long = name.graphemes(true).count() > consts::user_role::MAX_ROLE_NAME_LENGTH; if is_empty_or_whitespace || is_too_long || name.contains(' ') { Err(UserErrors::RoleNameParsingError.into()) } else { Ok(Self(name.to_lowercase())) } } pub fn get_role_name(self) -> String { self.0 } } #[derive(serde::Serialize, serde::Deserialize, Debug)] pub struct RecoveryCodes(pub Vec<Secret<String>>); impl RecoveryCodes { pub fn generate_new() -> Self { let mut rand = rand::thread_rng(); let recovery_codes = (0..consts::user::RECOVERY_CODES_COUNT) .map(|_| { let code_part_1 = Alphanumeric.sample_string(&mut rand, consts::user::RECOVERY_CODE_LENGTH / 2); let code_part_2 = Alphanumeric.sample_string(&mut rand, consts::user::RECOVERY_CODE_LENGTH / 2); Secret::new(format!("{code_part_1}-{code_part_2}")) }) .collect::<Vec<_>>(); Self(recovery_codes) } pub fn get_hashed(&self) -> UserResult<Vec<Secret<String>>> { self.0 .iter() .cloned() .map(password::generate_password_hash) .collect::<Result<Vec<_>, _>>() } pub fn into_inner(self) -> Vec<Secret<String>> { self.0 } } // This is for easier construction #[derive(Clone)] pub struct NoLevel; #[derive(Clone)] pub struct TenantLevel { pub tenant_id: id_type::TenantId, } #[derive(Clone)] pub struct OrganizationLevel { pub tenant_id: id_type::TenantId, pub org_id: id_type::OrganizationId, } #[derive(Clone)] pub struct MerchantLevel { pub tenant_id: id_type::TenantId, pub org_id: id_type::OrganizationId, pub merchant_id: id_type::MerchantId, } #[derive(Clone)] pub struct ProfileLevel { pub tenant_id: id_type::TenantId, pub org_id: id_type::OrganizationId, pub merchant_id: id_type::MerchantId, pub profile_id: id_type::ProfileId, } #[derive(Clone)] pub struct NewUserRole<E: Clone> { pub user_id: String, pub role_id: String, pub status: UserStatus, pub created_by: String, pub last_modified_by: String, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub entity: E, } impl NewUserRole<NoLevel> { pub fn add_entity<T>(self, entity: T) -> NewUserRole<T> where T: Clone, { NewUserRole { entity, user_id: self.user_id, role_id: self.role_id, status: self.status, created_by: self.created_by, last_modified_by: self.last_modified_by, created_at: self.created_at, last_modified: self.last_modified, } } } pub struct EntityInfo { tenant_id: id_type::TenantId, org_id: Option<id_type::OrganizationId>, merchant_id: Option<id_type::MerchantId>, profile_id: Option<id_type::ProfileId>, entity_id: String, entity_type: EntityType, } impl From<TenantLevel> for EntityInfo { fn from(value: TenantLevel) -> Self { Self { entity_id: value.tenant_id.get_string_repr().to_owned(), entity_type: EntityType::Tenant, tenant_id: value.tenant_id, org_id: None, merchant_id: None, profile_id: None, } } } impl From<OrganizationLevel> for EntityInfo { fn from(value: OrganizationLevel) -> Self { Self { entity_id: value.org_id.get_string_repr().to_owned(), entity_type: EntityType::Organization, tenant_id: value.tenant_id, org_id: Some(value.org_id), merchant_id: None, profile_id: None, } } } impl From<MerchantLevel> for EntityInfo { fn from(value: MerchantLevel) -> Self { Self { entity_id: value.merchant_id.get_string_repr().to_owned(), entity_type: EntityType::Merchant, tenant_id: value.tenant_id, org_id: Some(value.org_id), merchant_id: Some(value.merchant_id), profile_id: None, } } } impl From<ProfileLevel> for EntityInfo { fn from(value: ProfileLevel) -> Self { Self { entity_id: value.profile_id.get_string_repr().to_owned(), entity_type: EntityType::Profile, tenant_id: value.tenant_id, org_id: Some(value.org_id), merchant_id: Some(value.merchant_id), profile_id: Some(value.profile_id), } } } impl<E> NewUserRole<E> where E: Clone + Into<EntityInfo>, { fn convert_to_new_v2_role(self, entity: EntityInfo) -> UserRoleNew { UserRoleNew { user_id: self.user_id, role_id: self.role_id, status: self.status, created_by: self.created_by, last_modified_by: self.last_modified_by, created_at: self.created_at, last_modified: self.last_modified, org_id: entity.org_id, merchant_id: entity.merchant_id, profile_id: entity.profile_id, entity_id: Some(entity.entity_id), entity_type: Some(entity.entity_type), version: UserRoleVersion::V2, tenant_id: entity.tenant_id, } } pub async fn insert_in_v2(self, state: &SessionState) -> UserResult<UserRole> { let entity = self.entity.clone(); let new_v2_role = self.convert_to_new_v2_role(entity.into()); state .global_store .insert_user_role(new_v2_role) .await .change_context(UserErrors::InternalServerError) } }
{ "crate": "router", "file": "crates/router/src/types/domain/user.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 19, "num_tables": null, "score": null, "total_crates": null }
file_router_7420107588106001866
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/domain/user_key_store.rs // Contains: 1 structs, 0 enums use common_utils::{ crypto::Encryptable, date_time, type_name, types::keymanager::{Identifier, KeyManagerState}, }; use error_stack::ResultExt; use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation}; use masking::{PeekInterface, Secret}; use time::PrimitiveDateTime; use crate::errors::{CustomResult, ValidationError}; #[derive(Clone, Debug, serde::Serialize)] pub struct UserKeyStore { pub user_id: String, pub key: Encryptable<Secret<Vec<u8>>>, pub created_at: PrimitiveDateTime, } #[async_trait::async_trait] impl super::behaviour::Conversion for UserKeyStore { type DstType = diesel_models::user_key_store::UserKeyStore; type NewDstType = diesel_models::user_key_store::UserKeyStoreNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::user_key_store::UserKeyStore { key: self.key.into(), user_id: self.user_id, created_at: self.created_at, }) } async fn convert_back( state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, _key_manager_identifier: Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { let identifier = Identifier::User(item.user_id.clone()); Ok(Self { key: crypto_operation( state, type_name!(Self::DstType), CryptoOperation::Decrypt(item.key), identifier, key.peek(), ) .await .and_then(|val| val.try_into_operation()) .change_context(ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), })?, user_id: item.user_id, created_at: item.created_at, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(diesel_models::user_key_store::UserKeyStoreNew { user_id: self.user_id, key: self.key.into(), created_at: date_time::now(), }) } }
{ "crate": "router", "file": "crates/router/src/types/domain/user_key_store.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-5617339404993874122
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/domain/user/dashboard_metadata.rs // Contains: 1 structs, 0 enums use api_models::user::dashboard_metadata as api; use diesel_models::enums::DashboardMetadata as DBEnum; use masking::Secret; use time::PrimitiveDateTime; pub enum MetaData { ProductionAgreement(ProductionAgreementValue), SetupProcessor(api::SetupProcessor), ConfigureEndpoint(bool), SetupComplete(bool), FirstProcessorConnected(api::ProcessorConnected), SecondProcessorConnected(api::ProcessorConnected), ConfiguredRouting(api::ConfiguredRouting), TestPayment(api::TestPayment), IntegrationMethod(api::IntegrationMethod), ConfigurationType(api::ConfigurationType), IntegrationCompleted(bool), StripeConnected(api::ProcessorConnected), PaypalConnected(api::ProcessorConnected), SPRoutingConfigured(api::ConfiguredRouting), Feedback(api::Feedback), ProdIntent(api::ProdIntent), SPTestPayment(bool), DownloadWoocom(bool), ConfigureWoocom(bool), SetupWoocomWebhook(bool), IsMultipleConfiguration(bool), IsChangePasswordRequired(bool), OnboardingSurvey(api::OnboardingSurvey), ReconStatus(api::ReconStatus), } impl From<&MetaData> for DBEnum { fn from(value: &MetaData) -> Self { match value { MetaData::ProductionAgreement(_) => Self::ProductionAgreement, MetaData::SetupProcessor(_) => Self::SetupProcessor, MetaData::ConfigureEndpoint(_) => Self::ConfigureEndpoint, MetaData::SetupComplete(_) => Self::SetupComplete, MetaData::FirstProcessorConnected(_) => Self::FirstProcessorConnected, MetaData::SecondProcessorConnected(_) => Self::SecondProcessorConnected, MetaData::ConfiguredRouting(_) => Self::ConfiguredRouting, MetaData::TestPayment(_) => Self::TestPayment, MetaData::IntegrationMethod(_) => Self::IntegrationMethod, MetaData::ConfigurationType(_) => Self::ConfigurationType, MetaData::IntegrationCompleted(_) => Self::IntegrationCompleted, MetaData::StripeConnected(_) => Self::StripeConnected, MetaData::PaypalConnected(_) => Self::PaypalConnected, MetaData::SPRoutingConfigured(_) => Self::SpRoutingConfigured, MetaData::Feedback(_) => Self::Feedback, MetaData::ProdIntent(_) => Self::ProdIntent, MetaData::SPTestPayment(_) => Self::SpTestPayment, MetaData::DownloadWoocom(_) => Self::DownloadWoocom, MetaData::ConfigureWoocom(_) => Self::ConfigureWoocom, MetaData::SetupWoocomWebhook(_) => Self::SetupWoocomWebhook, MetaData::IsMultipleConfiguration(_) => Self::IsMultipleConfiguration, MetaData::IsChangePasswordRequired(_) => Self::IsChangePasswordRequired, MetaData::OnboardingSurvey(_) => Self::OnboardingSurvey, MetaData::ReconStatus(_) => Self::ReconStatus, } } } #[derive(Debug, serde::Serialize)] pub struct ProductionAgreementValue { pub version: String, pub ip_address: Secret<String, common_utils::pii::IpAddress>, pub timestamp: PrimitiveDateTime, }
{ "crate": "router", "file": "crates/router/src/types/domain/user/dashboard_metadata.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_2716980986842296357
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payment_methods.rs // Contains: 1 structs, 0 enums pub mod cards; pub mod migration; pub mod network_tokenization; pub mod surcharge_decision_configs; #[cfg(feature = "v1")] pub mod tokenize; pub mod transformers; pub mod utils; mod validator; pub mod vault; use std::borrow::Cow; #[cfg(feature = "v1")] use std::collections::HashSet; #[cfg(feature = "v2")] use std::str::FromStr; #[cfg(feature = "v2")] pub use api_models::enums as api_enums; pub use api_models::enums::Connector; use api_models::payment_methods; #[cfg(feature = "payouts")] pub use api_models::{enums::PayoutConnectors, payouts as payout_types}; #[cfg(feature = "v1")] use common_utils::{consts::DEFAULT_LOCALE, ext_traits::OptionExt}; #[cfg(feature = "v2")] use common_utils::{ crypto::Encryptable, errors::CustomResult, ext_traits::{AsyncExt, ValueExt}, fp_utils::when, generate_id, types as util_types, }; use common_utils::{ext_traits::Encode, id_type}; use diesel_models::{ enums, GenericLinkNew, PaymentMethodCollectLink, PaymentMethodCollectLinkData, }; use error_stack::{report, ResultExt}; #[cfg(feature = "v2")] use futures::TryStreamExt; #[cfg(feature = "v1")] use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData}; use hyperswitch_domain_models::{ payments::{payment_attempt::PaymentAttempt, PaymentIntent, VaultData}, router_data_v2::flow_common_types::VaultConnectorFlowData, router_flow_types::ExternalVaultInsertFlow, types::VaultRouterData, }; use hyperswitch_interfaces::connector_integration_interface::RouterDataConversion; use masking::{PeekInterface, Secret}; use router_env::{instrument, tracing}; use time::Duration; #[cfg(feature = "v2")] use super::payments::tokenization; use super::{ errors::{RouterResponse, StorageErrorExt}, pm_auth, }; #[cfg(feature = "v2")] use crate::{ configs::settings, core::{payment_methods::transformers as pm_transforms, tokenization as tokenization_core}, headers, routes::{self, payment_methods as pm_routes}, services::encryption, types::{ api::PaymentMethodCreateExt, domain::types as domain_types, storage::{ephemeral_key, PaymentMethodListContext}, transformers::{ForeignFrom, ForeignTryFrom}, Tokenizable, }, utils::ext_traits::OptionExt, }; use crate::{ consts, core::{ errors::{ProcessTrackerError, RouterResult}, payments::{self as payments_core, helpers as payment_helpers}, utils as core_utils, }, db::errors::ConnectorErrorExt, errors, logger, routes::{app::StorageInterface, SessionState}, services, types::{ self, api, domain, payment_methods as pm_types, storage::{self, enums as storage_enums}, }, }; const PAYMENT_METHOD_STATUS_UPDATE_TASK: &str = "PAYMENT_METHOD_STATUS_UPDATE"; const PAYMENT_METHOD_STATUS_TAG: &str = "PAYMENT_METHOD_STATUS"; #[instrument(skip_all)] pub async fn retrieve_payment_method_core( pm_data: &Option<domain::PaymentMethodData>, state: &SessionState, payment_intent: &PaymentIntent, payment_attempt: &PaymentAttempt, merchant_key_store: &domain::MerchantKeyStore, business_profile: Option<&domain::Profile>, ) -> RouterResult<(Option<domain::PaymentMethodData>, Option<String>)> { match pm_data { pm_opt @ Some(pm @ domain::PaymentMethodData::Card(_)) => { let payment_token = payment_helpers::store_payment_method_data_in_vault( state, payment_attempt, payment_intent, enums::PaymentMethod::Card, pm, merchant_key_store, business_profile, ) .await?; Ok((pm_opt.to_owned(), payment_token)) } pm_opt @ Some(pm @ domain::PaymentMethodData::BankDebit(_)) => { let payment_token = payment_helpers::store_payment_method_data_in_vault( state, payment_attempt, payment_intent, enums::PaymentMethod::BankDebit, pm, merchant_key_store, business_profile, ) .await?; Ok((pm_opt.to_owned(), payment_token)) } pm @ Some(domain::PaymentMethodData::PayLater(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::Crypto(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::Upi(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::Voucher(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::Reward) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::RealTimePayment(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::CardRedirect(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::GiftCard(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::OpenBanking(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::MobilePayment(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::NetworkToken(_)) => Ok((pm.to_owned(), None)), pm_opt @ Some(pm @ domain::PaymentMethodData::BankTransfer(_)) => { let payment_token = payment_helpers::store_payment_method_data_in_vault( state, payment_attempt, payment_intent, enums::PaymentMethod::BankTransfer, pm, merchant_key_store, business_profile, ) .await?; Ok((pm_opt.to_owned(), payment_token)) } pm_opt @ Some(pm @ domain::PaymentMethodData::Wallet(_)) => { let payment_token = payment_helpers::store_payment_method_data_in_vault( state, payment_attempt, payment_intent, enums::PaymentMethod::Wallet, pm, merchant_key_store, business_profile, ) .await?; Ok((pm_opt.to_owned(), payment_token)) } pm_opt @ Some(pm @ domain::PaymentMethodData::BankRedirect(_)) => { let payment_token = payment_helpers::store_payment_method_data_in_vault( state, payment_attempt, payment_intent, enums::PaymentMethod::BankRedirect, pm, merchant_key_store, business_profile, ) .await?; Ok((pm_opt.to_owned(), payment_token)) } _ => Ok((None, None)), } } pub async fn initiate_pm_collect_link( state: SessionState, merchant_context: domain::MerchantContext, req: payment_methods::PaymentMethodCollectLinkRequest, ) -> RouterResponse<payment_methods::PaymentMethodCollectLinkResponse> { // Validate request and initiate flow let pm_collect_link_data = validator::validate_request_and_initiate_payment_method_collect_link( &state, &merchant_context, &req, ) .await?; // Create DB entry let pm_collect_link = create_pm_collect_db_entry( &state, &merchant_context, &pm_collect_link_data, req.return_url.clone(), ) .await?; let customer_id = id_type::CustomerId::try_from(Cow::from(pm_collect_link.primary_reference)) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "customer_id", })?; // Return response let url = pm_collect_link.url.peek(); let response = payment_methods::PaymentMethodCollectLinkResponse { pm_collect_link_id: pm_collect_link.link_id, customer_id, expiry: pm_collect_link.expiry, link: url::Url::parse(url) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("Failed to parse the payment method collect link - {url}") })? .into(), return_url: pm_collect_link.return_url, ui_config: pm_collect_link.link_data.ui_config, enabled_payment_methods: pm_collect_link.link_data.enabled_payment_methods, }; Ok(services::ApplicationResponse::Json(response)) } pub async fn create_pm_collect_db_entry( state: &SessionState, merchant_context: &domain::MerchantContext, pm_collect_link_data: &PaymentMethodCollectLinkData, return_url: Option<String>, ) -> RouterResult<PaymentMethodCollectLink> { let db: &dyn StorageInterface = &*state.store; let link_data = serde_json::to_value(pm_collect_link_data) .map_err(|_| report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable("Failed to convert PaymentMethodCollectLinkData to Value")?; let pm_collect_link = GenericLinkNew { link_id: pm_collect_link_data.pm_collect_link_id.to_string(), primary_reference: pm_collect_link_data .customer_id .get_string_repr() .to_string(), merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), link_type: common_enums::GenericLinkType::PaymentMethodCollect, link_data, url: pm_collect_link_data.link.clone(), return_url, expiry: common_utils::date_time::now() + Duration::seconds(pm_collect_link_data.session_expiry.into()), ..Default::default() }; db.insert_pm_collect_link(pm_collect_link) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: "payment method collect link already exists".to_string(), }) } #[cfg(feature = "v2")] pub async fn render_pm_collect_link( _state: SessionState, _merchant_context: domain::MerchantContext, _req: payment_methods::PaymentMethodCollectLinkRenderRequest, ) -> RouterResponse<services::GenericLinkFormData> { todo!() } #[cfg(feature = "v1")] pub async fn render_pm_collect_link( state: SessionState, merchant_context: domain::MerchantContext, req: payment_methods::PaymentMethodCollectLinkRenderRequest, ) -> RouterResponse<services::GenericLinkFormData> { let db: &dyn StorageInterface = &*state.store; // Fetch pm collect link let pm_collect_link = db .find_pm_collect_link_by_link_id(&req.pm_collect_link_id) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "payment method collect link not found".to_string(), })?; // Check status and return form data accordingly let has_expired = common_utils::date_time::now() > pm_collect_link.expiry; let status = pm_collect_link.link_status; let link_data = pm_collect_link.link_data; let default_config = &state.conf.generic_link.payment_method_collect; let default_ui_config = default_config.ui_config.clone(); let ui_config_data = common_utils::link_utils::GenericLinkUiConfigFormData { merchant_name: link_data .ui_config .merchant_name .unwrap_or(default_ui_config.merchant_name), logo: link_data.ui_config.logo.unwrap_or(default_ui_config.logo), theme: link_data .ui_config .theme .clone() .unwrap_or(default_ui_config.theme.clone()), }; match status { common_utils::link_utils::PaymentMethodCollectStatus::Initiated => { // if expired, send back expired status page if has_expired { let expired_link_data = services::GenericExpiredLinkData { title: "Payment collect link has expired".to_string(), message: "This payment collect link has expired.".to_string(), theme: link_data.ui_config.theme.unwrap_or(default_ui_config.theme), }; Ok(services::ApplicationResponse::GenericLinkForm(Box::new( GenericLinks { allowed_domains: HashSet::from([]), data: GenericLinksData::ExpiredLink(expired_link_data), locale: DEFAULT_LOCALE.to_string(), }, ))) // else, send back form link } else { let customer_id = id_type::CustomerId::try_from(Cow::from( pm_collect_link.primary_reference.clone(), )) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "customer_id", })?; // Fetch customer let customer = db .find_customer_by_customer_id_merchant_id( &(&state).into(), &customer_id, &req.merchant_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Customer [{}] not found for link_id - {}", pm_collect_link.primary_reference, pm_collect_link.link_id ), }) .attach_printable(format!( "customer [{}] not found", pm_collect_link.primary_reference ))?; let js_data = payment_methods::PaymentMethodCollectLinkDetails { publishable_key: Secret::new( merchant_context .get_merchant_account() .clone() .publishable_key, ), client_secret: link_data.client_secret.clone(), pm_collect_link_id: pm_collect_link.link_id, customer_id: customer.customer_id, session_expiry: pm_collect_link.expiry, return_url: pm_collect_link.return_url, ui_config: ui_config_data, enabled_payment_methods: link_data.enabled_payment_methods, }; let serialized_css_content = String::new(); let serialized_js_content = format!( "window.__PM_COLLECT_DETAILS = {}", js_data .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize PaymentMethodCollectLinkDetails")? ); let generic_form_data = services::GenericLinkFormData { js_data: serialized_js_content, css_data: serialized_css_content, sdk_url: default_config.sdk_url.clone(), html_meta_tags: String::new(), }; Ok(services::ApplicationResponse::GenericLinkForm(Box::new( GenericLinks { allowed_domains: HashSet::from([]), data: GenericLinksData::PaymentMethodCollect(generic_form_data), locale: DEFAULT_LOCALE.to_string(), }, ))) } } // Send back status page status => { let js_data = payment_methods::PaymentMethodCollectLinkStatusDetails { pm_collect_link_id: pm_collect_link.link_id, customer_id: link_data.customer_id, session_expiry: pm_collect_link.expiry, return_url: pm_collect_link .return_url .as_ref() .map(|url| url::Url::parse(url)) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to parse return URL for payment method collect's status link", )?, ui_config: ui_config_data, status, }; let serialized_css_content = String::new(); let serialized_js_content = format!( "window.__PM_COLLECT_DETAILS = {}", js_data .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to serialize PaymentMethodCollectLinkStatusDetails" )? ); let generic_status_data = services::GenericLinkStatusData { js_data: serialized_js_content, css_data: serialized_css_content, }; Ok(services::ApplicationResponse::GenericLinkForm(Box::new( GenericLinks { allowed_domains: HashSet::from([]), data: GenericLinksData::PaymentMethodCollectStatus(generic_status_data), locale: DEFAULT_LOCALE.to_string(), }, ))) } } } fn generate_task_id_for_payment_method_status_update_workflow( key_id: &str, runner: storage::ProcessTrackerRunner, task: &str, ) -> String { format!("{runner}_{task}_{key_id}") } #[cfg(feature = "v1")] pub async fn add_payment_method_status_update_task( db: &dyn StorageInterface, payment_method: &domain::PaymentMethod, prev_status: enums::PaymentMethodStatus, curr_status: enums::PaymentMethodStatus, merchant_id: &id_type::MerchantId, ) -> Result<(), ProcessTrackerError> { let created_at = payment_method.created_at; let schedule_time = created_at.saturating_add(Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)); let tracking_data = storage::PaymentMethodStatusTrackingData { payment_method_id: payment_method.get_id().clone(), prev_status, curr_status, merchant_id: merchant_id.to_owned(), }; let runner = storage::ProcessTrackerRunner::PaymentMethodStatusUpdateWorkflow; let task = PAYMENT_METHOD_STATUS_UPDATE_TASK; let tag = [PAYMENT_METHOD_STATUS_TAG]; let process_tracker_id = generate_task_id_for_payment_method_status_update_workflow( payment_method.get_id().as_str(), runner, task, ); let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, tracking_data, None, schedule_time, common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct PAYMENT_METHOD_STATUS_UPDATE process tracker task")?; db .insert_process(process_tracker_entry) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while inserting PAYMENT_METHOD_STATUS_UPDATE reminder to process_tracker for payment_method_id: {}", payment_method.get_id().clone() ) })?; Ok(()) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn retrieve_payment_method_with_token( _state: &SessionState, _merchant_key_store: &domain::MerchantKeyStore, _token_data: &storage::PaymentTokenData, _payment_intent: &PaymentIntent, _card_token_data: Option<&domain::CardToken>, _customer: &Option<domain::Customer>, _storage_scheme: common_enums::enums::MerchantStorageScheme, _mandate_id: Option<api_models::payments::MandateIds>, _payment_method_info: Option<domain::PaymentMethod>, _business_profile: &domain::Profile, ) -> RouterResult<storage::PaymentMethodDataWithId> { todo!() } #[cfg(feature = "v1")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn retrieve_payment_method_with_token( state: &SessionState, merchant_key_store: &domain::MerchantKeyStore, token_data: &storage::PaymentTokenData, payment_intent: &PaymentIntent, payment_attempt: &PaymentAttempt, card_token_data: Option<&domain::CardToken>, customer: &Option<domain::Customer>, storage_scheme: common_enums::enums::MerchantStorageScheme, mandate_id: Option<api_models::payments::MandateIds>, payment_method_info: Option<domain::PaymentMethod>, business_profile: &domain::Profile, should_retry_with_pan: bool, vault_data: Option<&VaultData>, ) -> RouterResult<storage::PaymentMethodDataWithId> { let token = match token_data { storage::PaymentTokenData::TemporaryGeneric(generic_token) => { payment_helpers::retrieve_payment_method_with_temporary_token( state, &generic_token.token, payment_intent, payment_attempt, merchant_key_store, card_token_data, ) .await? .map( |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId { payment_method_data: Some(payment_method_data), payment_method: Some(payment_method), payment_method_id: None, }, ) .unwrap_or_default() } storage::PaymentTokenData::Temporary(generic_token) => { payment_helpers::retrieve_payment_method_with_temporary_token( state, &generic_token.token, payment_intent, payment_attempt, merchant_key_store, card_token_data, ) .await? .map( |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId { payment_method_data: Some(payment_method_data), payment_method: Some(payment_method), payment_method_id: None, }, ) .unwrap_or_default() } storage::PaymentTokenData::Permanent(card_token) => { payment_helpers::retrieve_payment_method_data_with_permanent_token( state, card_token.locker_id.as_ref().unwrap_or(&card_token.token), card_token .payment_method_id .as_ref() .unwrap_or(&card_token.token), payment_intent, card_token_data, merchant_key_store, storage_scheme, mandate_id, payment_method_info .get_required_value("PaymentMethod") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("PaymentMethod not found")?, business_profile, payment_attempt.connector.clone(), should_retry_with_pan, vault_data, ) .await .map(|card| Some((card, enums::PaymentMethod::Card)))? .map( |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId { payment_method_data: Some(payment_method_data), payment_method: Some(payment_method), payment_method_id: Some( card_token .payment_method_id .as_ref() .unwrap_or(&card_token.token) .to_string(), ), }, ) .unwrap_or_default() } storage::PaymentTokenData::PermanentCard(card_token) => { payment_helpers::retrieve_payment_method_data_with_permanent_token( state, card_token.locker_id.as_ref().unwrap_or(&card_token.token), card_token .payment_method_id .as_ref() .unwrap_or(&card_token.token), payment_intent, card_token_data, merchant_key_store, storage_scheme, mandate_id, payment_method_info .get_required_value("PaymentMethod") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("PaymentMethod not found")?, business_profile, payment_attempt.connector.clone(), should_retry_with_pan, vault_data, ) .await .map(|card| Some((card, enums::PaymentMethod::Card)))? .map( |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId { payment_method_data: Some(payment_method_data), payment_method: Some(payment_method), payment_method_id: Some( card_token .payment_method_id .as_ref() .unwrap_or(&card_token.token) .to_string(), ), }, ) .unwrap_or_default() } storage::PaymentTokenData::AuthBankDebit(auth_token) => { pm_auth::retrieve_payment_method_from_auth_service( state, merchant_key_store, auth_token, payment_intent, customer, ) .await? .map( |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId { payment_method_data: Some(payment_method_data), payment_method: Some(payment_method), payment_method_id: None, }, ) .unwrap_or_default() } storage::PaymentTokenData::WalletToken(_) => storage::PaymentMethodDataWithId { payment_method: None, payment_method_data: None, payment_method_id: None, }, }; Ok(token) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub(crate) fn get_payment_method_create_request( payment_method_data: &api_models::payments::PaymentMethodData, payment_method_type: storage_enums::PaymentMethod, payment_method_subtype: storage_enums::PaymentMethodType, customer_id: id_type::GlobalCustomerId, billing_address: Option<&api_models::payments::Address>, payment_method_session: Option<&domain::payment_methods::PaymentMethodSession>, ) -> RouterResult<payment_methods::PaymentMethodCreate> { match payment_method_data { api_models::payments::PaymentMethodData::Card(card) => { let card_detail = payment_methods::CardDetail { card_number: card.card_number.clone(), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), card_holder_name: card.card_holder_name.clone(), nick_name: card.nick_name.clone(), card_issuing_country: card .card_issuing_country .as_ref() .map(|c| api_enums::CountryAlpha2::from_str(c)) .transpose() .ok() .flatten(), card_network: card.card_network.clone(), card_issuer: card.card_issuer.clone(), card_type: card .card_type .as_ref() .map(|c| payment_methods::CardType::from_str(c)) .transpose() .ok() .flatten(), card_cvc: Some(card.card_cvc.clone()), }; let payment_method_request = payment_methods::PaymentMethodCreate { payment_method_type, payment_method_subtype, metadata: None, customer_id: customer_id.clone(), payment_method_data: payment_methods::PaymentMethodCreateData::Card(card_detail), billing: billing_address.map(ToOwned::to_owned), psp_tokenization: payment_method_session .and_then(|pm_session| pm_session.psp_tokenization.clone()), network_tokenization: payment_method_session .and_then(|pm_session| pm_session.network_tokenization.clone()), }; Ok(payment_method_request) } _ => Err(report!(errors::ApiErrorResponse::UnprocessableEntity { message: "only card payment methods are supported for tokenization".to_string() }) .attach_printable("Payment method data is incorrect")), } } #[cfg(feature = "v1")] #[instrument(skip_all)] pub(crate) async fn get_payment_method_create_request( payment_method_data: Option<&domain::PaymentMethodData>, payment_method: Option<storage_enums::PaymentMethod>, payment_method_type: Option<storage_enums::PaymentMethodType>, customer_id: &Option<id_type::CustomerId>, billing_name: Option<Secret<String>>, payment_method_billing_address: Option<&hyperswitch_domain_models::address::Address>, ) -> RouterResult<payment_methods::PaymentMethodCreate> { match payment_method_data { 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(), card_exp_year: card.card_exp_year.clone(), card_holder_name: billing_name, nick_name: card.nick_name.clone(), card_issuing_country: card.card_issuing_country.clone(), card_network: card_network.clone(), card_issuer: card.card_issuer.clone(), card_type: card.card_type.clone(), }; let payment_method_request = payment_methods::PaymentMethodCreate { payment_method: Some(payment_method), payment_method_type, payment_method_issuer: card.card_issuer.clone(), payment_method_issuer_code: None, #[cfg(feature = "payouts")] bank_transfer: None, #[cfg(feature = "payouts")] wallet: None, card: Some(card_detail), metadata: None, customer_id: customer_id.clone(), card_network: card_network .clone() .as_ref() .map(|card_network| card_network.to_string()), client_secret: None, payment_method_data: None, //TODO: why are we using api model in router internally billing: payment_method_billing_address.cloned().map(From::from), connector_mandate_details: None, network_transaction_id: None, }; Ok(payment_method_request) } _ => { let payment_method_request = payment_methods::PaymentMethodCreate { payment_method: Some(payment_method), payment_method_type, payment_method_issuer: None, payment_method_issuer_code: None, #[cfg(feature = "payouts")] bank_transfer: None, #[cfg(feature = "payouts")] wallet: None, card: None, metadata: None, customer_id: customer_id.clone(), card_network: None, client_secret: None, payment_method_data: None, billing: None, connector_mandate_details: None, network_transaction_id: None, }; Ok(payment_method_request) } }, None => Err(report!(errors::ApiErrorResponse::MissingRequiredField { field_name: "payment_method_type" }) .attach_printable("PaymentMethodType Required")), }, None => Err(report!(errors::ApiErrorResponse::MissingRequiredField { field_name: "payment_method_data" }) .attach_printable("PaymentMethodData required Or Card is already saved")), } } /// 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> { if let Some(true) = card_network .as_ref() .map(|network| network.is_us_local_network()) { services::logger::debug!("Card network is a US local network, checking for global network in co-badged card data"); let info: Option<api_models::open_router::CoBadgedCardNetworksInfo> = co_badged_card_data .and_then(|data| { data.co_badged_card_networks_info .0 .iter() .find(|info| info.network.is_signature_network()) .cloned() }); info.map(|data| data.network) } else { card_network } } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn create_payment_method( state: &SessionState, request_state: &routes::app::ReqState, req: api::PaymentMethodCreate, merchant_context: &domain::MerchantContext, profile: &domain::Profile, ) -> RouterResponse<api::PaymentMethodResponse> { // payment_method is for internal use, can never be populated in response let (response, _payment_method) = Box::pin(create_payment_method_core( state, request_state, req, merchant_context, profile, )) .await?; Ok(services::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn create_payment_method_core( state: &SessionState, _request_state: &routes::app::ReqState, req: api::PaymentMethodCreate, merchant_context: &domain::MerchantContext, profile: &domain::Profile, ) -> RouterResult<(api::PaymentMethodResponse, domain::PaymentMethod)> { use common_utils::ext_traits::ValueExt; req.validate()?; let db = &*state.store; let merchant_id = merchant_context.get_merchant_account().get_id(); let customer_id = req.customer_id.to_owned(); let key_manager_state = &(state).into(); db.find_customer_by_global_id( key_manager_state, &customer_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound) .attach_printable("Customer not found for the payment method")?; let payment_method_billing_address = req .billing .clone() .async_map(|billing| { cards::create_encrypted_data( key_manager_state, merchant_context.get_merchant_key_store(), billing, ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt Payment method billing address")? .map(|encoded_address| { encoded_address.deserialize_inner_value(|value| value.parse_value("address")) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse Payment method billing address")?; let payment_method_id = id_type::GlobalPaymentMethodId::generate(&state.conf.cell_information.id) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate GlobalPaymentMethodId")?; match &req.payment_method_data { api::PaymentMethodCreateData::Card(_) => { Box::pin(create_payment_method_card_core( state, req, merchant_context, profile, merchant_id, &customer_id, payment_method_id, payment_method_billing_address, )) .await } api::PaymentMethodCreateData::ProxyCard(_) => { create_payment_method_proxy_card_core( state, req, merchant_context, profile, merchant_id, &customer_id, payment_method_id, payment_method_billing_address, ) .await } } } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn create_payment_method_card_core( state: &SessionState, req: api::PaymentMethodCreate, merchant_context: &domain::MerchantContext, profile: &domain::Profile, merchant_id: &id_type::MerchantId, customer_id: &id_type::GlobalCustomerId, payment_method_id: id_type::GlobalPaymentMethodId, payment_method_billing_address: Option< Encryptable<hyperswitch_domain_models::address::Address>, >, ) -> RouterResult<(api::PaymentMethodResponse, domain::PaymentMethod)> { let db = &*state.store; let payment_method = create_payment_method_for_intent( state, req.metadata.clone(), customer_id, payment_method_id, merchant_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, payment_method_billing_address, ) .await .attach_printable("failed to add payment method to db")?; let payment_method_data = domain::PaymentMethodVaultingData::try_from(req.payment_method_data)? .populate_bin_details_for_payment_method(state) .await; let vaulting_result = vault_payment_method( state, &payment_method_data, merchant_context, profile, None, customer_id, ) .await; let network_tokenization_resp = network_tokenize_and_vault_the_pmd( state, &payment_method_data, merchant_context, req.network_tokenization.clone(), profile.is_network_tokenization_enabled, customer_id, ) .await; let (response, payment_method) = match vaulting_result { Ok(( pm_types::AddVaultResponse { vault_id, fingerprint_id, .. }, external_vault_source, )) => { let pm_update = create_pm_additional_data_update( Some(&payment_method_data), state, merchant_context.get_merchant_key_store(), Some(vault_id.get_string_repr().clone()), fingerprint_id, &payment_method, None, network_tokenization_resp, Some(req.payment_method_type), Some(req.payment_method_subtype), external_vault_source, ) .await .attach_printable("unable to create payment method data")?; let payment_method = db .update_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), payment_method, pm_update, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; let resp = pm_transforms::generate_payment_method_response(&payment_method, &None)?; Ok((resp, payment_method)) } Err(e) => { let pm_update = storage::PaymentMethodUpdate::StatusUpdate { status: Some(enums::PaymentMethodStatus::Inactive), }; db.update_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), payment_method, pm_update, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; Err(e) } }?; Ok((response, payment_method)) } // network tokenization and vaulting to locker is not required for proxy card since the card is already tokenized #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn create_payment_method_proxy_card_core( state: &SessionState, req: api::PaymentMethodCreate, merchant_context: &domain::MerchantContext, profile: &domain::Profile, merchant_id: &id_type::MerchantId, customer_id: &id_type::GlobalCustomerId, payment_method_id: id_type::GlobalPaymentMethodId, payment_method_billing_address: Option< Encryptable<hyperswitch_domain_models::address::Address>, >, ) -> RouterResult<(api::PaymentMethodResponse, domain::PaymentMethod)> { use crate::core::payment_methods::vault::Vault; let key_manager_state = &(state).into(); let external_vault_source = profile .external_vault_connector_details .clone() .map(|details| details.vault_connector_id); let additional_payment_method_data = Some( req.payment_method_data .populate_bin_details_for_payment_method(state) .await .convert_to_additional_payment_method_data()?, ); let encrypted_payment_method_data = additional_payment_method_data .async_map(|payment_method_data| { cards::create_encrypted_data( key_manager_state, merchant_context.get_merchant_key_store(), payment_method_data, ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt Payment method data")? .map(|encoded_pmd| { encoded_pmd.deserialize_inner_value(|value| value.parse_value("PaymentMethodsData")) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse Payment method data")?; let external_vault_token_data = req.payment_method_data.get_external_vault_token_data(); let encrypted_external_vault_token_data = external_vault_token_data .async_map(|external_vault_token_data| { cards::create_encrypted_data( key_manager_state, merchant_context.get_merchant_key_store(), external_vault_token_data, ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt External vault token data")? .map(|encoded_data| { encoded_data .deserialize_inner_value(|value| value.parse_value("ExternalVaultTokenData")) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse External vault token data")?; let vault_type = external_vault_source .is_some() .then_some(common_enums::VaultType::External); let payment_method = create_payment_method_for_confirm( state, customer_id, payment_method_id, external_vault_source, merchant_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, req.payment_method_type, req.payment_method_subtype, payment_method_billing_address, encrypted_payment_method_data, encrypted_external_vault_token_data, vault_type, ) .await?; let payment_method_response = pm_transforms::generate_payment_method_response(&payment_method, &None)?; Ok((payment_method_response, payment_method)) } #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub struct NetworkTokenPaymentMethodDetails { network_token_requestor_reference_id: String, network_token_locker_id: String, network_token_pmd: Encryptable<Secret<serde_json::Value>>, } #[cfg(feature = "v2")] pub async fn network_tokenize_and_vault_the_pmd( state: &SessionState, payment_method_data: &domain::PaymentMethodVaultingData, merchant_context: &domain::MerchantContext, network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, network_tokenization_enabled_for_profile: bool, customer_id: &id_type::GlobalCustomerId, ) -> Option<NetworkTokenPaymentMethodDetails> { let network_token_pm_details_result: CustomResult< NetworkTokenPaymentMethodDetails, errors::NetworkTokenizationError, > = async { when(!network_tokenization_enabled_for_profile, || { Err(report!( errors::NetworkTokenizationError::NetworkTokenizationNotEnabledForProfile )) })?; let is_network_tokenization_enabled_for_pm = network_tokenization .as_ref() .map(|nt| matches!(nt.enable, common_enums::NetworkTokenizationToggle::Enable)) .unwrap_or(false); let card_data = payment_method_data .get_card() .and_then(|card| is_network_tokenization_enabled_for_pm.then_some(card)) .ok_or_else(|| { report!(errors::NetworkTokenizationError::NotSupported { message: "Payment method".to_string(), }) })?; let (resp, network_token_req_ref_id) = network_tokenization::make_card_network_tokenization_request( state, card_data, customer_id, ) .await?; let network_token_vaulting_data = domain::PaymentMethodVaultingData::NetworkToken(resp); let vaulting_resp = vault::add_payment_method_to_vault( state, merchant_context, &network_token_vaulting_data, None, customer_id, ) .await .change_context(errors::NetworkTokenizationError::SaveNetworkTokenFailed) .attach_printable("Failed to vault network token")?; let key_manager_state = &(state).into(); let network_token_pmd = cards::create_encrypted_data( key_manager_state, merchant_context.get_merchant_key_store(), network_token_vaulting_data.get_payment_methods_data(), ) .await .change_context(errors::NetworkTokenizationError::NetworkTokenDetailsEncryptionFailed) .attach_printable("Failed to encrypt PaymentMethodsData")?; Ok(NetworkTokenPaymentMethodDetails { network_token_requestor_reference_id: network_token_req_ref_id, network_token_locker_id: vaulting_resp.vault_id.get_string_repr().clone(), network_token_pmd, }) } .await; network_token_pm_details_result.ok() } #[cfg(feature = "v2")] pub async fn populate_bin_details_for_payment_method( state: &SessionState, payment_method_data: &domain::PaymentMethodVaultingData, ) -> domain::PaymentMethodVaultingData { match payment_method_data { domain::PaymentMethodVaultingData::Card(card) => { let card_isin = card.card_number.get_card_isin(); if card.card_issuer.is_some() && card.card_network.is_some() && card.card_type.is_some() && card.card_issuing_country.is_some() { domain::PaymentMethodVaultingData::Card(card.clone()) } else { let card_info = state .store .get_card_info(&card_isin) .await .map_err(|error| services::logger::error!(card_info_error=?error)) .ok() .flatten(); domain::PaymentMethodVaultingData::Card(payment_methods::CardDetail { card_number: card.card_number.clone(), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), card_holder_name: card.card_holder_name.clone(), nick_name: card.nick_name.clone(), card_issuing_country: card_info.as_ref().and_then(|val| { val.card_issuing_country .as_ref() .map(|c| api_enums::CountryAlpha2::from_str(c)) .transpose() .ok() .flatten() }), card_network: card_info.as_ref().and_then(|val| val.card_network.clone()), card_issuer: card_info.as_ref().and_then(|val| val.card_issuer.clone()), card_type: card_info.as_ref().and_then(|val| { val.card_type .as_ref() .map(|c| payment_methods::CardType::from_str(c)) .transpose() .ok() .flatten() }), card_cvc: card.card_cvc.clone(), }) } } _ => payment_method_data.clone(), } } #[cfg(feature = "v2")] #[async_trait::async_trait] pub trait PaymentMethodExt { async fn populate_bin_details_for_payment_method(&self, state: &SessionState) -> Self; // convert to data format compatible to save in payment method table fn convert_to_additional_payment_method_data( &self, ) -> RouterResult<payment_methods::PaymentMethodsData>; // get tokens generated from external vault fn get_external_vault_token_data(&self) -> Option<payment_methods::ExternalVaultTokenData>; } #[cfg(feature = "v2")] #[async_trait::async_trait] impl PaymentMethodExt for domain::PaymentMethodVaultingData { async fn populate_bin_details_for_payment_method(&self, state: &SessionState) -> Self { match self { Self::Card(card) => { let card_isin = card.card_number.get_card_isin(); if card.card_issuer.is_some() && card.card_network.is_some() && card.card_type.is_some() && card.card_issuing_country.is_some() { Self::Card(card.clone()) } else { let card_info = state .store .get_card_info(&card_isin) .await .map_err(|error| services::logger::error!(card_info_error=?error)) .ok() .flatten(); Self::Card(payment_methods::CardDetail { card_number: card.card_number.clone(), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), card_holder_name: card.card_holder_name.clone(), nick_name: card.nick_name.clone(), card_issuing_country: card_info.as_ref().and_then(|val| { val.card_issuing_country .as_ref() .map(|c| api_enums::CountryAlpha2::from_str(c)) .transpose() .ok() .flatten() }), card_network: card_info.as_ref().and_then(|val| val.card_network.clone()), card_issuer: card_info.as_ref().and_then(|val| val.card_issuer.clone()), card_type: card_info.as_ref().and_then(|val| { val.card_type .as_ref() .map(|c| payment_methods::CardType::from_str(c)) .transpose() .ok() .flatten() }), card_cvc: card.card_cvc.clone(), }) } } _ => self.clone(), } } // Not implement because it is saved in locker and not in payment method table fn convert_to_additional_payment_method_data( &self, ) -> RouterResult<payment_methods::PaymentMethodsData> { Err(report!(errors::ApiErrorResponse::UnprocessableEntity { message: "Payment method data is not supported".to_string() }) .attach_printable("Payment method data is not supported")) } fn get_external_vault_token_data(&self) -> Option<payment_methods::ExternalVaultTokenData> { None } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl PaymentMethodExt for payment_methods::PaymentMethodCreateData { async fn populate_bin_details_for_payment_method(&self, state: &SessionState) -> Self { match self { Self::ProxyCard(card) => { let card_isin = card.bin_number.clone(); if card.card_issuer.is_some() && card.card_network.is_some() && card.card_type.is_some() && card.card_issuing_country.is_some() { Self::ProxyCard(card.clone()) } else if let Some(card_isin) = card_isin { let card_info = state .store .get_card_info(&card_isin) .await .map_err(|error| services::logger::error!(card_info_error=?error)) .ok() .flatten(); Self::ProxyCard(payment_methods::ProxyCardDetails { card_number: card.card_number.clone(), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), card_holder_name: card.card_holder_name.clone(), bin_number: card.bin_number.clone(), last_four: card.last_four.clone(), nick_name: card.nick_name.clone(), card_issuing_country: card_info .as_ref() .and_then(|val| val.card_issuing_country.clone()), card_network: card_info.as_ref().and_then(|val| val.card_network.clone()), card_issuer: card_info.as_ref().and_then(|val| val.card_issuer.clone()), card_type: card_info.as_ref().and_then(|val| val.card_type.clone()), card_cvc: card.card_cvc.clone(), }) } else { Self::ProxyCard(card.clone()) } } _ => self.clone(), } } fn convert_to_additional_payment_method_data( &self, ) -> RouterResult<payment_methods::PaymentMethodsData> { match self.clone() { Self::ProxyCard(card_details) => Ok(payment_methods::PaymentMethodsData::Card( payment_methods::CardDetailsPaymentMethod { last4_digits: card_details.last_four, expiry_month: Some(card_details.card_exp_month), expiry_year: Some(card_details.card_exp_year), card_holder_name: card_details.card_holder_name, nick_name: card_details.nick_name, issuer_country: card_details.card_issuing_country, card_network: card_details.card_network, card_issuer: card_details.card_issuer, card_type: card_details.card_type, card_isin: card_details.bin_number, saved_to_locker: false, co_badged_card_data: None, }, )), Self::Card(card_details) => Ok(payment_methods::PaymentMethodsData::Card( payment_methods::CardDetailsPaymentMethod { expiry_month: Some(card_details.card_exp_month), expiry_year: Some(card_details.card_exp_year), card_holder_name: card_details.card_holder_name, nick_name: card_details.nick_name, issuer_country: card_details .card_issuing_country .map(|country| country.to_string()), card_network: card_details.card_network, card_issuer: card_details.card_issuer, card_type: card_details .card_type .map(|card_type| card_type.to_string()), saved_to_locker: false, card_isin: None, last4_digits: None, co_badged_card_data: None, }, )), } } fn get_external_vault_token_data(&self) -> Option<payment_methods::ExternalVaultTokenData> { match self.clone() { Self::ProxyCard(card_details) => Some(payment_methods::ExternalVaultTokenData { tokenized_card_number: card_details.card_number, }), Self::Card(_) => None, } } } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn payment_method_intent_create( state: &SessionState, req: api::PaymentMethodIntentCreate, merchant_context: &domain::MerchantContext, ) -> RouterResponse<api::PaymentMethodResponse> { let db = &*state.store; let merchant_id = merchant_context.get_merchant_account().get_id(); let customer_id = req.customer_id.to_owned(); let key_manager_state = &(state).into(); db.find_customer_by_global_id( key_manager_state, &customer_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound) .attach_printable("Customer not found for the payment method")?; let payment_method_billing_address = req .billing .clone() .async_map(|billing| { cards::create_encrypted_data( key_manager_state, merchant_context.get_merchant_key_store(), billing, ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt Payment method billing address")? .map(|encoded_address| { encoded_address.deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse Payment method billing address")?; // create pm entry let payment_method_id = id_type::GlobalPaymentMethodId::generate(&state.conf.cell_information.id) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate GlobalPaymentMethodId")?; let payment_method = create_payment_method_for_intent( state, req.metadata.clone(), &customer_id, payment_method_id, merchant_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, payment_method_billing_address, ) .await .attach_printable("Failed to add Payment method to DB")?; let resp = pm_transforms::generate_payment_method_response(&payment_method, &None)?; Ok(services::ApplicationResponse::Json(resp)) } #[cfg(feature = "v2")] trait PerformFilteringOnEnabledPaymentMethods { fn perform_filtering(self) -> FilteredPaymentMethodsEnabled; } #[cfg(feature = "v2")] impl PerformFilteringOnEnabledPaymentMethods for hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled { fn perform_filtering(self) -> FilteredPaymentMethodsEnabled { FilteredPaymentMethodsEnabled(self.payment_methods_enabled) } } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn list_payment_methods_for_session( state: SessionState, merchant_context: domain::MerchantContext, profile: domain::Profile, payment_method_session_id: id_type::GlobalPaymentMethodSessionId, ) -> RouterResponse<api::PaymentMethodListResponseForSession> { let key_manager_state = &(&state).into(); let db = &*state.store; let payment_method_session = db .get_payment_methods_session( key_manager_state, merchant_context.get_merchant_key_store(), &payment_method_session_id, ) .await .change_context(errors::ApiErrorResponse::PaymentMethodNotFound) .attach_printable("Unable to find payment method")?; let payment_connector_accounts = db .list_enabled_connector_accounts_by_profile_id( key_manager_state, profile.get_id(), merchant_context.get_merchant_key_store(), common_enums::ConnectorType::PaymentProcessor, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error when fetching merchant connector accounts")?; let customer_payment_methods = list_customer_payment_methods_core( &state, &merchant_context, &payment_method_session.customer_id, ) .await?; let response = 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_for_session(customer_payment_methods); Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] pub async fn list_saved_payment_methods_for_customer( state: SessionState, merchant_context: domain::MerchantContext, customer_id: id_type::GlobalCustomerId, ) -> RouterResponse<payment_methods::CustomerPaymentMethodsListResponse> { let customer_payment_methods = list_payment_methods_core(&state, &merchant_context, &customer_id).await?; Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( customer_payment_methods, )) } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] pub async fn get_token_data_for_payment_method( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, profile: domain::Profile, request: payment_methods::GetTokenDataRequest, payment_method_id: id_type::GlobalPaymentMethodId, ) -> RouterResponse<api::TokenDataResponse> { let key_manager_state = &(&state).into(); let db = &*state.store; let payment_method = db .find_payment_method( key_manager_state, &key_store, &payment_method_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; let token_data_response = generate_token_data_response(&state, request, profile, &payment_method).await?; Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( token_data_response, )) } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] pub async fn generate_token_data_response( state: &SessionState, request: payment_methods::GetTokenDataRequest, profile: domain::Profile, payment_method: &domain::PaymentMethod, ) -> RouterResult<api::TokenDataResponse> { let token_details = match request.token_type { common_enums::TokenDataType::NetworkToken => { let is_network_tokenization_enabled = profile.is_network_tokenization_enabled; if !is_network_tokenization_enabled { return Err(errors::ApiErrorResponse::UnprocessableEntity { message: "Network tokenization is not enabled for this profile".to_string(), } .into()); } let network_token_requestor_ref_id = payment_method .network_token_requestor_reference_id .clone() .ok_or(errors::ApiErrorResponse::GenericNotFoundError { message: "NetworkTokenRequestorReferenceId is not present".to_string(), })?; let network_token = network_tokenization::get_token_from_tokenization_service( state, network_token_requestor_ref_id, payment_method, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch network token data from tokenization service")?; api::TokenDetailsResponse::NetworkTokenDetails(api::NetworkTokenDetailsResponse { network_token: network_token.network_token, network_token_exp_month: network_token.network_token_exp_month, network_token_exp_year: network_token.network_token_exp_year, cryptogram: network_token.cryptogram, card_issuer: network_token.card_issuer, card_network: network_token.card_network, card_type: network_token.card_type, card_issuing_country: network_token.card_issuing_country, bank_code: network_token.bank_code, card_holder_name: network_token.card_holder_name, nick_name: network_token.nick_name, eci: network_token.eci, }) } common_enums::TokenDataType::SingleUseToken | common_enums::TokenDataType::MultiUseToken => { return Err(errors::ApiErrorResponse::UnprocessableEntity { message: "Token type not supported".to_string(), } .into()); } }; Ok(api::TokenDataResponse { payment_method_id: payment_method.id.clone(), token_type: request.token_type, token_details, }) } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] pub async fn get_total_saved_payment_methods_for_merchant( state: SessionState, merchant_context: domain::MerchantContext, ) -> RouterResponse<api::TotalPaymentMethodCountResponse> { let total_payment_method_count = get_total_payment_method_count_core(&state, &merchant_context).await?; Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( total_payment_method_count, )) } #[cfg(feature = "v2")] /// Container for the inputs required for the required fields struct RequiredFieldsInput { required_fields_config: settings::RequiredFields, } #[cfg(feature = "v2")] impl RequiredFieldsInput { fn new(required_fields_config: settings::RequiredFields) -> Self { Self { required_fields_config, } } } #[cfg(feature = "v2")] /// Container for the filtered payment methods struct FilteredPaymentMethodsEnabled( Vec<hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector>, ); #[cfg(feature = "v2")] trait GetRequiredFields { fn get_required_fields( &self, payment_method_enabled: &hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector, ) -> Option<&settings::RequiredFieldFinal>; } #[cfg(feature = "v2")] impl GetRequiredFields for settings::RequiredFields { fn get_required_fields( &self, payment_method_enabled: &hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector, ) -> Option<&settings::RequiredFieldFinal> { self.0 .get(&payment_method_enabled.payment_method) .and_then(|required_fields_for_payment_method| { required_fields_for_payment_method.0.get( &payment_method_enabled .payment_methods_enabled .payment_method_subtype, ) }) .map(|connector_fields| &connector_fields.fields) .and_then(|connector_hashmap| connector_hashmap.get(&payment_method_enabled.connector)) } } #[cfg(feature = "v2")] impl FilteredPaymentMethodsEnabled { fn get_required_fields( self, input: RequiredFieldsInput, ) -> RequiredFieldsForEnabledPaymentMethodTypes { let required_fields_config = input.required_fields_config; let required_fields_info = self .0 .into_iter() .map(|payment_methods_enabled| { let required_fields = required_fields_config.get_required_fields(&payment_methods_enabled); let required_fields = required_fields .map(|required_fields| { let common_required_fields = required_fields .common .iter() .flatten() .map(ToOwned::to_owned); // Collect mandate required fields because this is for zero auth mandates only let mandate_required_fields = required_fields .mandate .iter() .flatten() .map(ToOwned::to_owned); // Combine both common and mandate required fields common_required_fields .chain(mandate_required_fields) .collect::<Vec<_>>() }) .unwrap_or_default(); RequiredFieldsForEnabledPaymentMethod { required_fields, payment_method_type: payment_methods_enabled.payment_method, payment_method_subtype: payment_methods_enabled .payment_methods_enabled .payment_method_subtype, } }) .collect(); RequiredFieldsForEnabledPaymentMethodTypes(required_fields_info) } } #[cfg(feature = "v2")] /// Element container to hold the filtered payment methods with required fields struct RequiredFieldsForEnabledPaymentMethod { required_fields: Vec<payment_methods::RequiredFieldInfo>, payment_method_subtype: common_enums::PaymentMethodType, payment_method_type: common_enums::PaymentMethod, } #[cfg(feature = "v2")] /// Container to hold the filtered payment methods enabled with required fields struct RequiredFieldsForEnabledPaymentMethodTypes(Vec<RequiredFieldsForEnabledPaymentMethod>); #[cfg(feature = "v2")] impl RequiredFieldsForEnabledPaymentMethodTypes { fn generate_response_for_session( self, customer_payment_methods: Vec<payment_methods::CustomerPaymentMethodResponseItem>, ) -> payment_methods::PaymentMethodListResponseForSession { let response_payment_methods = self .0 .into_iter() .map( |payment_methods_enabled| payment_methods::ResponsePaymentMethodTypes { payment_method_type: payment_methods_enabled.payment_method_type, payment_method_subtype: payment_methods_enabled.payment_method_subtype, required_fields: payment_methods_enabled.required_fields, extra_information: None, }, ) .collect(); payment_methods::PaymentMethodListResponseForSession { payment_methods_enabled: response_payment_methods, customer_payment_methods, } } } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn create_payment_method_for_intent( state: &SessionState, metadata: Option<common_utils::pii::SecretSerdeValue>, customer_id: &id_type::GlobalCustomerId, payment_method_id: id_type::GlobalPaymentMethodId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, payment_method_billing_address: Option< Encryptable<hyperswitch_domain_models::address::Address>, >, ) -> CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> { use josekit::jwe::zip::deflate::DeflateJweCompression::Def; let db = &*state.store; let current_time = common_utils::date_time::now(); let response = db .insert_payment_method( &state.into(), key_store, domain::PaymentMethod { customer_id: customer_id.to_owned(), merchant_id: merchant_id.to_owned(), id: payment_method_id, locker_id: None, payment_method_type: None, payment_method_subtype: None, payment_method_data: None, connector_mandate_details: None, customer_acceptance: None, client_secret: None, status: enums::PaymentMethodStatus::AwaitingData, network_transaction_id: None, created_at: current_time, last_modified: current_time, last_used_at: current_time, payment_method_billing_address, updated_by: None, version: common_types::consts::API_VERSION, locker_fingerprint_id: None, network_token_locker_id: None, network_token_payment_method_data: None, network_token_requestor_reference_id: None, external_vault_source: None, external_vault_token_data: None, vault_type: None, }, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; Ok(response) } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn create_payment_method_for_confirm( state: &SessionState, customer_id: &id_type::GlobalCustomerId, payment_method_id: id_type::GlobalPaymentMethodId, external_vault_source: Option<id_type::MerchantConnectorAccountId>, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, payment_method_type: storage_enums::PaymentMethod, payment_method_subtype: storage_enums::PaymentMethodType, encrypted_payment_method_billing_address: Option< Encryptable<hyperswitch_domain_models::address::Address>, >, encrypted_payment_method_data: Option<Encryptable<payment_methods::PaymentMethodsData>>, encrypted_external_vault_token_data: Option< Encryptable<payment_methods::ExternalVaultTokenData>, >, vault_type: Option<common_enums::VaultType>, ) -> CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> { let db = &*state.store; let key_manager_state = &state.into(); let current_time = common_utils::date_time::now(); let response = db .insert_payment_method( key_manager_state, key_store, domain::PaymentMethod { customer_id: customer_id.to_owned(), merchant_id: merchant_id.to_owned(), id: payment_method_id, locker_id: None, payment_method_type: Some(payment_method_type), payment_method_subtype: Some(payment_method_subtype), payment_method_data: encrypted_payment_method_data, connector_mandate_details: None, customer_acceptance: None, client_secret: None, status: enums::PaymentMethodStatus::Inactive, network_transaction_id: None, created_at: current_time, last_modified: current_time, last_used_at: current_time, payment_method_billing_address: encrypted_payment_method_billing_address, updated_by: None, version: common_types::consts::API_VERSION, locker_fingerprint_id: None, network_token_locker_id: None, network_token_payment_method_data: None, network_token_requestor_reference_id: None, external_vault_source, external_vault_token_data: encrypted_external_vault_token_data, vault_type, }, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; Ok(response) } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn get_external_vault_token( state: &SessionState, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, payment_token: String, vault_token: domain::VaultToken, payment_method_type: &storage_enums::PaymentMethod, ) -> CustomResult<domain::ExternalVaultPaymentMethodData, errors::ApiErrorResponse> { let db = &*state.store; let pm_token_data = utils::retrieve_payment_token_data(state, payment_token, 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 payment_method = db .find_payment_method(&state.into(), key_store, &payment_method_id, storage_scheme) .await .change_context(errors::ApiErrorResponse::PaymentMethodNotFound) .attach_printable("Payment method not found")?; let external_vault_token_data = payment_method .external_vault_token_data .clone() .map(Encryptable::into_inner) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Missing vault token data")?; let decrypted_addtional_payment_method_data = payment_method .payment_method_data .clone() .map(Encryptable::into_inner) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert payment method data")?; convert_from_saved_payment_method_data( decrypted_addtional_payment_method_data, external_vault_token_data, vault_token, ) .attach_printable("Failed to convert payment method data") } #[cfg(feature = "v2")] fn convert_from_saved_payment_method_data( vault_additional_data: payment_methods::PaymentMethodsData, external_vault_token_data: payment_methods::ExternalVaultTokenData, vault_token: domain::VaultToken, ) -> RouterResult<domain::ExternalVaultPaymentMethodData> { match vault_additional_data { payment_methods::PaymentMethodsData::Card(card_details) => { Ok(domain::ExternalVaultPaymentMethodData::Card(Box::new( domain::ExternalVaultCard { card_number: external_vault_token_data.tokenized_card_number, card_exp_month: card_details.expiry_month.ok_or( errors::ApiErrorResponse::MissingRequiredField { field_name: "card_details.expiry_month", }, )?, card_exp_year: card_details.expiry_year.ok_or( errors::ApiErrorResponse::MissingRequiredField { field_name: "card_details.expiry_year", }, )?, card_holder_name: card_details.card_holder_name, bin_number: card_details.card_isin, last_four: card_details.last4_digits, nick_name: card_details.nick_name, card_issuing_country: card_details.issuer_country, card_network: card_details.card_network, card_issuer: card_details.card_issuer, card_type: card_details.card_type, card_cvc: vault_token.card_cvc, co_badged_card_data: None, // Co-badged data is not supported in external vault bank_code: None, // Bank code is not stored in external vault }, ))) } payment_methods::PaymentMethodsData::BankDetails(_) | payment_methods::PaymentMethodsData::WalletDetails(_) => { Err(errors::ApiErrorResponse::UnprocessableEntity { message: "External vaulting is not supported for this payment method type" .to_string(), } .into()) } } } #[cfg(feature = "v2")] /// Update the connector_mandate_details of the payment method with /// new token details for the payment fn create_connector_token_details_update( token_details: payment_methods::ConnectorTokenDetails, payment_method: &domain::PaymentMethod, ) -> hyperswitch_domain_models::mandates::CommonMandateReference { let connector_id = token_details.connector_id.clone(); let reference_record = hyperswitch_domain_models::mandates::ConnectorTokenReferenceRecord::foreign_from( token_details, ); let connector_token_details = payment_method.connector_mandate_details.clone(); match connector_token_details { Some(mut connector_mandate_reference) => { connector_mandate_reference .insert_payment_token_reference_record(&connector_id, reference_record); connector_mandate_reference } None => { let reference_record_hash_map = std::collections::HashMap::from([(connector_id, reference_record)]); let payments_mandate_reference = hyperswitch_domain_models::mandates::PaymentsTokenReference( reference_record_hash_map, ); hyperswitch_domain_models::mandates::CommonMandateReference { payments: Some(payments_mandate_reference), payouts: None, } } } } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn create_pm_additional_data_update( pmd: Option<&domain::PaymentMethodVaultingData>, state: &SessionState, key_store: &domain::MerchantKeyStore, vault_id: Option<String>, vault_fingerprint_id: Option<String>, payment_method: &domain::PaymentMethod, connector_token_details: Option<payment_methods::ConnectorTokenDetails>, nt_data: Option<NetworkTokenPaymentMethodDetails>, payment_method_type: Option<common_enums::PaymentMethod>, payment_method_subtype: Option<common_enums::PaymentMethodType>, external_vault_source: Option<id_type::MerchantConnectorAccountId>, ) -> RouterResult<storage::PaymentMethodUpdate> { let encrypted_payment_method_data = pmd .map(|payment_method_vaulting_data| payment_method_vaulting_data.get_payment_methods_data()) .async_map(|payment_method_details| async { let key_manager_state = &(state).into(); cards::create_encrypted_data(key_manager_state, key_store, payment_method_details) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt Payment method data") }) .await .transpose()? .map(From::from); let connector_mandate_details_update = connector_token_details .map(|connector_token| { create_connector_token_details_update(connector_token, payment_method) }) .map(From::from); let pm_update = storage::PaymentMethodUpdate::GenericUpdate { // 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, payment_method_data: encrypted_payment_method_data, network_token_requestor_reference_id: nt_data .clone() .map(|data| data.network_token_requestor_reference_id), network_token_locker_id: nt_data.clone().map(|data| data.network_token_locker_id), network_token_payment_method_data: nt_data.map(|data| data.network_token_pmd.into()), connector_mandate_details: connector_mandate_details_update, locker_fingerprint_id: vault_fingerprint_id, external_vault_source, }; Ok(pm_update) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn vault_payment_method_internal( state: &SessionState, pmd: &domain::PaymentMethodVaultingData, merchant_context: &domain::MerchantContext, existing_vault_id: Option<domain::VaultId>, customer_id: &id_type::GlobalCustomerId, ) -> RouterResult<pm_types::AddVaultResponse> { let db = &*state.store; // get fingerprint_id from vault let fingerprint_id_from_vault = vault::get_fingerprint_id_from_vault(state, pmd, customer_id.get_string_repr().to_owned()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get fingerprint_id from vault")?; // throw back error if payment method is duplicated when( db.find_payment_method_by_fingerprint_id( &(state.into()), merchant_context.get_merchant_key_store(), &fingerprint_id_from_vault, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to find payment method by fingerprint_id") .inspect_err(|e| logger::error!("Vault Fingerprint_id error: {:?}", e)) .is_ok(), || { Err(report!(errors::ApiErrorResponse::DuplicatePaymentMethod) .attach_printable("Cannot vault duplicate payment method")) }, )?; let mut resp_from_vault = vault::add_payment_method_to_vault( state, merchant_context, pmd, existing_vault_id, customer_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in vault")?; // add fingerprint_id to the response resp_from_vault.fingerprint_id = Some(fingerprint_id_from_vault); Ok(resp_from_vault) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn vault_payment_method_external( state: &SessionState, pmd: &domain::PaymentMethodVaultingData, merchant_account: &domain::MerchantAccount, merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, ) -> RouterResult<pm_types::AddVaultResponse> { let merchant_connector_account = match &merchant_connector_account { domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(mca) => { Ok(mca.as_ref()) } domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => { Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("MerchantConnectorDetails not supported for vault operations")) } }?; let router_data = core_utils::construct_vault_router_data( state, merchant_account.get_id(), merchant_connector_account, Some(pmd.clone()), None, None, ) .await?; let mut old_router_data = VaultConnectorFlowData::to_old_router_data(router_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Cannot construct router data for making the external vault insert api call", )?; let connector_name = merchant_connector_account.get_connector_name_as_string(); // always get the connector name from this call let connector_data = api::ConnectorData::get_external_vault_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, Some(merchant_connector_account.get_id()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector data")?; let connector_integration: services::BoxedVaultConnectorIntegrationInterface< ExternalVaultInsertFlow, types::VaultRequestData, types::VaultResponseData, > = connector_data.connector.get_connector_integration(); let router_data_resp = services::execute_connector_processing_step( state, connector_integration, &old_router_data, payments_core::CallConnectorAction::Trigger, None, None, ) .await .to_vault_failed_response()?; get_vault_response_for_insert_payment_method_data(router_data_resp) } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn vault_payment_method_external_v1( state: &SessionState, pmd: &hyperswitch_domain_models::vault::PaymentMethodVaultingData, merchant_account: &domain::MerchantAccount, merchant_connector_account: hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, ) -> RouterResult<pm_types::AddVaultResponse> { let router_data = core_utils::construct_vault_router_data( state, merchant_account.get_id(), &merchant_connector_account, Some(pmd.clone()), None, None, ) .await?; let old_router_data = VaultConnectorFlowData::to_old_router_data(router_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Cannot construct router data for making the external vault insert api call", )?; let connector_name = merchant_connector_account.get_connector_name_as_string(); let connector_data = api::ConnectorData::get_external_vault_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, Some(merchant_connector_account.get_id()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector data")?; let connector_integration: services::BoxedVaultConnectorIntegrationInterface< ExternalVaultInsertFlow, types::VaultRequestData, types::VaultResponseData, > = connector_data.connector.get_connector_integration(); let router_data_resp = services::execute_connector_processing_step( state, connector_integration, &old_router_data, payments_core::CallConnectorAction::Trigger, None, None, ) .await .to_vault_failed_response()?; get_vault_response_for_insert_payment_method_data(router_data_resp) } pub fn get_vault_response_for_insert_payment_method_data<F>( router_data: VaultRouterData<F>, ) -> RouterResult<pm_types::AddVaultResponse> { match router_data.response { Ok(response) => match response { types::VaultResponseData::ExternalVaultInsertResponse { connector_vault_id, fingerprint_id, } => { #[cfg(feature = "v2")] let vault_id = domain::VaultId::generate(connector_vault_id); #[cfg(not(feature = "v2"))] let vault_id = connector_vault_id; Ok(pm_types::AddVaultResponse { vault_id, fingerprint_id: Some(fingerprint_id), entity_id: None, }) } types::VaultResponseData::ExternalVaultRetrieveResponse { .. } | types::VaultResponseData::ExternalVaultDeleteResponse { .. } | types::VaultResponseData::ExternalVaultCreateResponse { .. } => { Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid Vault Response")) } }, Err(err) => { logger::error!("Error vaulting payment method: {:?}", err); Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to vault payment method")) } } } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn vault_payment_method( state: &SessionState, pmd: &domain::PaymentMethodVaultingData, merchant_context: &domain::MerchantContext, profile: &domain::Profile, existing_vault_id: Option<domain::VaultId>, customer_id: &id_type::GlobalCustomerId, ) -> RouterResult<( pm_types::AddVaultResponse, Option<id_type::MerchantConnectorAccountId>, )> { let is_external_vault_enabled = profile.is_external_vault_enabled(); match is_external_vault_enabled { true => { let external_vault_source: id_type::MerchantConnectorAccountId = profile .external_vault_connector_details .clone() .map(|connector_details| connector_details.vault_connector_id.clone()) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("mca_id not present for external vault")?; let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new( payments_core::helpers::get_merchant_connector_account_v2( state, merchant_context.get_merchant_key_store(), Some(&external_vault_source), ) .await .attach_printable( "failed to fetch merchant connector account for external vault insert", )?, )); vault_payment_method_external( state, pmd, merchant_context.get_merchant_account(), merchant_connector_account, ) .await .map(|value| (value, Some(external_vault_source))) } false => vault_payment_method_internal( state, pmd, merchant_context, existing_vault_id, customer_id, ) .await .map(|value| (value, None)), } } #[cfg(feature = "v2")] fn get_pm_list_context( payment_method_type: enums::PaymentMethod, payment_method: &domain::PaymentMethod, is_payment_associated: bool, ) -> Result<Option<PaymentMethodListContext>, error_stack::Report<errors::ApiErrorResponse>> { let payment_method_data = payment_method .payment_method_data .clone() .map(|payment_method_data| payment_method_data.into_inner()); let payment_method_retrieval_context = match payment_method_data { Some(payment_methods::PaymentMethodsData::Card(card)) => { Some(PaymentMethodListContext::Card { card_details: api::CardDetailFromLocker::from(card), token_data: is_payment_associated.then_some( storage::PaymentTokenData::permanent_card( payment_method.get_id().clone(), payment_method .locker_id .as_ref() .map(|id| id.get_string_repr().to_owned()) .or_else(|| Some(payment_method.get_id().get_string_repr().to_owned())), payment_method .locker_id .as_ref() .map(|id| id.get_string_repr().to_owned()) .unwrap_or_else(|| { payment_method.get_id().get_string_repr().to_owned() }), ), ), }) } Some(payment_methods::PaymentMethodsData::BankDetails(bank_details)) => { let get_bank_account_token_data = || -> CustomResult<payment_methods::BankAccountTokenData,errors::ApiErrorResponse> { let connector_details = bank_details .connector_details .first() .cloned() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to obtain bank account connector details")?; let payment_method_subtype = payment_method .get_payment_method_subtype() .get_required_value("payment_method_subtype") .attach_printable("PaymentMethodType not found")?; Ok(payment_methods::BankAccountTokenData { payment_method_type: payment_method_subtype, payment_method: payment_method_type, connector_details, }) }; // Retrieve the pm_auth connector details so that it can be tokenized let bank_account_token_data = get_bank_account_token_data() .inspect_err(|error| logger::error!(?error)) .ok(); bank_account_token_data.map(|data| { let token_data = storage::PaymentTokenData::AuthBankDebit(data); PaymentMethodListContext::Bank { token_data: is_payment_associated.then_some(token_data), } }) } Some(payment_methods::PaymentMethodsData::WalletDetails(_)) | None => { Some(PaymentMethodListContext::TemporaryToken { token_data: is_payment_associated.then_some( storage::PaymentTokenData::temporary_generic(generate_id( consts::ID_LENGTH, "token", )), ), }) } }; Ok(payment_method_retrieval_context) } #[cfg(feature = "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_payment_methods_core( state: &SessionState, merchant_context: &domain::MerchantContext, customer_id: &id_type::GlobalCustomerId, ) -> RouterResult<payment_methods::CustomerPaymentMethodsListResponse> { 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 customer_payment_methods = saved_payment_methods .into_iter() .map(ForeignTryFrom::foreign_try_from) .collect::<Result<Vec<payment_methods::PaymentMethodResponseItem>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError)?; 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, merchant_context: &domain::MerchantContext, ) -> RouterResult<api::TotalPaymentMethodCountResponse> { let db = &*state.store; let total_count = db .get_payment_method_count_by_merchant_id_status( merchant_context.get_merchant_account().get_id(), common_enums::PaymentMethodStatus::Active, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to get total payment method count")?; let response = api::TotalPaymentMethodCountResponse { total_count }; Ok(response) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn retrieve_payment_method( state: SessionState, pm: api::PaymentMethodId, merchant_context: domain::MerchantContext, ) -> RouterResponse<api::PaymentMethodResponse> { let db = state.store.as_ref(); let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(pm.payment_method_id) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate GlobalPaymentMethodId")?; let payment_method = db .find_payment_method( &((&state).into()), merchant_context.get_merchant_key_store(), &pm_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; let single_use_token_in_cache = get_single_use_token_from_store( &state.clone(), domain::SingleUseTokenKey::store_key(&pm_id.clone()), ) .await .unwrap_or_default(); transformers::generate_payment_method_response(&payment_method, &single_use_token_in_cache) .map(services::ApplicationResponse::Json) } // TODO: When we separate out microservices, this function will be an endpoint in payment_methods #[cfg(feature = "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(feature = "v2")] #[instrument(skip_all)] pub async fn update_payment_method( state: SessionState, merchant_context: domain::MerchantContext, profile: domain::Profile, req: api::PaymentMethodUpdate, payment_method_id: &id_type::GlobalPaymentMethodId, ) -> RouterResponse<api::PaymentMethodResponse> { let response = update_payment_method_core(&state, &merchant_context, &profile, req, payment_method_id) .await?; Ok(services::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn update_payment_method_core( state: &SessionState, merchant_context: &domain::MerchantContext, profile: &domain::Profile, request: api::PaymentMethodUpdate, payment_method_id: &id_type::GlobalPaymentMethodId, ) -> RouterResult<api::PaymentMethodResponse> { let db = state.store.as_ref(); let payment_method = db .find_payment_method( &((state).into()), merchant_context.get_merchant_key_store(), payment_method_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; let current_vault_id = payment_method.locker_id.clone(); when( payment_method.status == enums::PaymentMethodStatus::AwaitingData, || { Err(errors::ApiErrorResponse::InvalidRequestData { message: "This Payment method is awaiting data and hence cannot be updated" .to_string(), }) }, )?; let pmd: domain::PaymentMethodVaultingData = vault::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; let vault_request_data = request.payment_method_data.map(|payment_method_data| { pm_transforms::generate_pm_vaulting_req_from_update_request(pmd, payment_method_data) }); let vaulting_response = match vault_request_data { // cannot use async map because of problems related to lifetimes // to overcome this, we will have to use a move closure and add some clones Some(ref vault_request_data) => { let (vault_response, _) = vault_payment_method( state, vault_request_data, merchant_context, profile, // using current vault_id for now, // will have to refactor this to generate new one on each vaulting later on current_vault_id, &payment_method.customer_id, ) .await .attach_printable("Failed to add payment method in vault")?; Some(vault_response) } None => None, }; let (vault_id, fingerprint_id) = match vaulting_response { Some(vaulting_response) => { let vault_id = vaulting_response.vault_id.get_string_repr().to_owned(); (Some(vault_id), vaulting_response.fingerprint_id) } None => (None, None), }; let pm_update = create_pm_additional_data_update( vault_request_data.as_ref(), state, merchant_context.get_merchant_key_store(), vault_id, fingerprint_id, &payment_method, request.connector_token_details, None, None, None, None, ) .await .attach_printable("Unable to create Payment method data")?; let payment_method = db .update_payment_method( &((state).into()), merchant_context.get_merchant_key_store(), payment_method, pm_update, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; let response = pm_transforms::generate_payment_method_response(&payment_method, &None)?; // Add a PT task to handle payment_method delete from vault Ok(response) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn delete_payment_method( state: SessionState, pm_id: api::PaymentMethodId, merchant_context: domain::MerchantContext, profile: domain::Profile, ) -> RouterResponse<api::PaymentMethodDeleteResponse> { let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(pm_id.payment_method_id) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate GlobalPaymentMethodId")?; let response = delete_payment_method_core(&state, pm_id, &merchant_context, &profile).await?; Ok(services::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn delete_payment_method_core( state: &SessionState, pm_id: id_type::GlobalPaymentMethodId, merchant_context: &domain::MerchantContext, profile: &domain::Profile, ) -> RouterResult<api::PaymentMethodDeleteResponse> { let db = state.store.as_ref(); let key_manager_state = &(state).into(); let payment_method = db .find_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), &pm_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; when( payment_method.status == enums::PaymentMethodStatus::Inactive, || Err(errors::ApiErrorResponse::PaymentMethodNotFound), )?; let _customer = db .find_customer_by_global_id( key_manager_state, &payment_method.customer_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable("Customer not found for the payment method")?; // Soft delete let pm_update = storage::PaymentMethodUpdate::StatusUpdate { status: Some(enums::PaymentMethodStatus::Inactive), }; db.update_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), payment_method.clone(), pm_update, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; vault::delete_payment_method_data_from_vault(state, merchant_context, profile, &payment_method) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to delete payment method from vault")?; let response = api::PaymentMethodDeleteResponse { id: pm_id }; Ok(response) } #[cfg(feature = "v2")] #[async_trait::async_trait] trait EncryptableData { type Output; async fn encrypt_data( &self, key_manager_state: &common_utils::types::keymanager::KeyManagerState, key_store: &domain::MerchantKeyStore, ) -> RouterResult<Self::Output>; } #[cfg(feature = "v2")] #[async_trait::async_trait] impl EncryptableData for payment_methods::PaymentMethodSessionRequest { type Output = hyperswitch_domain_models::payment_methods::DecryptedPaymentMethodSession; async fn encrypt_data( &self, key_manager_state: &common_utils::types::keymanager::KeyManagerState, key_store: &domain::MerchantKeyStore, ) -> RouterResult<Self::Output> { use common_utils::types::keymanager::ToEncryptable; let encrypted_billing_address = self .billing .clone() .map(|address| address.encode_to_value()) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode billing address")? .map(Secret::new); let batch_encrypted_data = domain_types::crypto_operation( key_manager_state, common_utils::type_name!(hyperswitch_domain_models::payment_methods::PaymentMethodSession), domain_types::CryptoOperation::BatchEncrypt( hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession::to_encryptable( hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession { billing: encrypted_billing_address, }, ), ), common_utils::types::keymanager::Identifier::Merchant(key_store.merchant_id.clone()), key_store.key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting payment methods session details".to_string())?; let encrypted_data = hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession::from_encryptable( batch_encrypted_data, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting payment methods session detailss")?; Ok(encrypted_data) } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl EncryptableData for payment_methods::PaymentMethodsSessionUpdateRequest { type Output = hyperswitch_domain_models::payment_methods::DecryptedPaymentMethodSession; async fn encrypt_data( &self, key_manager_state: &common_utils::types::keymanager::KeyManagerState, key_store: &domain::MerchantKeyStore, ) -> RouterResult<Self::Output> { use common_utils::types::keymanager::ToEncryptable; let encrypted_billing_address = self .billing .clone() .map(|address| address.encode_to_value()) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode billing address")? .map(Secret::new); let batch_encrypted_data = domain_types::crypto_operation( key_manager_state, common_utils::type_name!(hyperswitch_domain_models::payment_methods::PaymentMethodSession), domain_types::CryptoOperation::BatchEncrypt( hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession::to_encryptable( hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession { billing: encrypted_billing_address, }, ), ), common_utils::types::keymanager::Identifier::Merchant(key_store.merchant_id.clone()), key_store.key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting payment methods session details".to_string())?; let encrypted_data = hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession::from_encryptable( batch_encrypted_data, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting payment methods session detailss")?; Ok(encrypted_data) } } #[cfg(feature = "v2")] pub async fn payment_methods_session_create( state: SessionState, merchant_context: domain::MerchantContext, request: payment_methods::PaymentMethodSessionRequest, ) -> RouterResponse<payment_methods::PaymentMethodSessionResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); db.find_customer_by_global_id( key_manager_state, &request.customer_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; let payment_methods_session_id = id_type::GlobalPaymentMethodSessionId::generate(&state.conf.cell_information.id) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate GlobalPaymentMethodSessionId")?; let encrypted_data = request .encrypt_data(key_manager_state, merchant_context.get_merchant_key_store()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encrypt payment methods session data")?; let billing = encrypted_data .billing .as_ref() .map(|data| { data.clone() .deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to decode billing address")?; // If not passed in the request, use the default value from constants let expires_in = request .expires_in .unwrap_or(consts::DEFAULT_PAYMENT_METHOD_SESSION_EXPIRY) .into(); let expires_at = common_utils::date_time::now().saturating_add(Duration::seconds(expires_in)); let client_secret = payment_helpers::create_client_secret( &state, merchant_context.get_merchant_account().get_id(), util_types::authentication::ResourceId::PaymentMethodSession( payment_methods_session_id.clone(), ), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to create client secret")?; let payment_method_session_domain_model = hyperswitch_domain_models::payment_methods::PaymentMethodSession { id: payment_methods_session_id, customer_id: request.customer_id, billing, psp_tokenization: request.psp_tokenization, network_tokenization: request.network_tokenization, tokenization_data: request.tokenization_data, expires_at, return_url: request.return_url, associated_payment_methods: None, associated_payment: None, associated_token_id: None, }; db.insert_payment_methods_session( key_manager_state, merchant_context.get_merchant_key_store(), payment_method_session_domain_model.clone(), expires_in, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to insert payment methods session in db")?; let response = transformers::generate_payment_method_session_response( payment_method_session_domain_model, client_secret.secret, None, None, ); Ok(services::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] pub async fn payment_methods_session_update( state: SessionState, merchant_context: domain::MerchantContext, payment_method_session_id: id_type::GlobalPaymentMethodSessionId, request: payment_methods::PaymentMethodsSessionUpdateRequest, ) -> RouterResponse<payment_methods::PaymentMethodSessionResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let existing_payment_method_session_state = db .get_payment_methods_session( key_manager_state, merchant_context.get_merchant_key_store(), &payment_method_session_id, ) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "payment methods session does not exist or has expired".to_string(), }) .attach_printable("Failed to retrieve payment methods session from db")?; let encrypted_data = request .encrypt_data(key_manager_state, merchant_context.get_merchant_key_store()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encrypt payment methods session data")?; let billing = encrypted_data .billing .as_ref() .map(|data| { data.clone() .deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to decode billing address")?; let payment_method_session_domain_model = hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum::GeneralUpdate{ billing: Box::new(billing), psp_tokenization: request.psp_tokenization, network_tokenization: request.network_tokenization, tokenization_data: request.tokenization_data, }; let update_state_change = db .update_payment_method_session( key_manager_state, merchant_context.get_merchant_key_store(), &payment_method_session_id, payment_method_session_domain_model, existing_payment_method_session_state.clone(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment methods session in db")?; let response = transformers::generate_payment_method_session_response( update_state_change, Secret::new("CLIENT_SECRET_REDACTED".to_string()), None, // TODO: send associated payments response based on the expandable param None, ); Ok(services::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] pub async fn payment_methods_session_retrieve( state: SessionState, merchant_context: domain::MerchantContext, payment_method_session_id: id_type::GlobalPaymentMethodSessionId, ) -> RouterResponse<payment_methods::PaymentMethodSessionResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let payment_method_session_domain_model = db .get_payment_methods_session( key_manager_state, merchant_context.get_merchant_key_store(), &payment_method_session_id, ) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "payment methods session does not exist or has expired".to_string(), }) .attach_printable("Failed to retrieve payment methods session from db")?; let response = transformers::generate_payment_method_session_response( payment_method_session_domain_model, Secret::new("CLIENT_SECRET_REDACTED".to_string()), None, // TODO: send associated payments response based on the expandable param None, ); Ok(services::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] pub async fn payment_methods_session_update_payment_method( state: SessionState, merchant_context: domain::MerchantContext, profile: domain::Profile, payment_method_session_id: id_type::GlobalPaymentMethodSessionId, request: payment_methods::PaymentMethodSessionUpdateSavedPaymentMethod, ) -> RouterResponse<payment_methods::PaymentMethodResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); // Validate if the session still exists db.get_payment_methods_session( key_manager_state, merchant_context.get_merchant_key_store(), &payment_method_session_id, ) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "payment methods session does not exist or has expired".to_string(), }) .attach_printable("Failed to retrieve payment methods session from db")?; let payment_method_update_request = request.payment_method_update_request; let updated_payment_method = update_payment_method_core( &state, &merchant_context, &profile, payment_method_update_request, &request.payment_method_id, ) .await .attach_printable("Failed to update saved payment method")?; Ok(services::ApplicationResponse::Json(updated_payment_method)) } #[cfg(feature = "v2")] pub async fn payment_methods_session_delete_payment_method( state: SessionState, merchant_context: domain::MerchantContext, profile: domain::Profile, pm_id: id_type::GlobalPaymentMethodId, payment_method_session_id: id_type::GlobalPaymentMethodSessionId, ) -> RouterResponse<api::PaymentMethodDeleteResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); // Validate if the session still exists db.get_payment_methods_session( key_manager_state, merchant_context.get_merchant_key_store(), &payment_method_session_id, ) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "payment methods session does not exist or has expired".to_string(), }) .attach_printable("Failed to retrieve payment methods session from db")?; let response = delete_payment_method_core(&state, pm_id, &merchant_context, &profile) .await .attach_printable("Failed to delete saved payment method")?; Ok(services::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] fn construct_zero_auth_payments_request( confirm_request: &payment_methods::PaymentMethodSessionConfirmRequest, payment_method_session: &hyperswitch_domain_models::payment_methods::PaymentMethodSession, payment_method: &payment_methods::PaymentMethodResponse, ) -> RouterResult<api_models::payments::PaymentsRequest> { use api_models::payments; Ok(payments::PaymentsRequest { amount_details: payments::AmountDetails::new_for_zero_auth_payment( common_enums::Currency::USD, ), payment_method_data: confirm_request.payment_method_data.clone(), payment_method_type: confirm_request.payment_method_type, payment_method_subtype: confirm_request.payment_method_subtype, customer_id: Some(payment_method_session.customer_id.clone()), customer_present: Some(enums::PresenceOfCustomerDuringPayment::Present), setup_future_usage: Some(common_enums::FutureUsage::OffSession), payment_method_id: Some(payment_method.id.clone()), merchant_reference_id: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, // We have already passed payment method billing address billing: None, shipping: None, description: None, return_url: payment_method_session.return_url.clone(), apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, feature_metadata: None, payment_link_enabled: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, customer_acceptance: None, browser_info: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, merchant_connector_details: None, return_raw_connector_response: None, enable_partial_authorization: None, webhook_url: None, }) } #[cfg(feature = "v2")] async fn create_zero_auth_payment( state: SessionState, req_state: routes::app::ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, request: api_models::payments::PaymentsRequest, ) -> RouterResult<api_models::payments::PaymentsResponse> { let response = Box::pin(payments_core::payments_create_and_confirm_intent( state, req_state, merchant_context, profile, request, hyperswitch_domain_models::payments::HeaderPayload::default(), )) .await?; logger::info!(associated_payments_response=?response); response .get_json_body() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unexpected response from payments core") } #[cfg(feature = "v2")] pub async fn payment_methods_session_confirm( state: SessionState, req_state: routes::app::ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, payment_method_session_id: id_type::GlobalPaymentMethodSessionId, request: payment_methods::PaymentMethodSessionConfirmRequest, ) -> RouterResponse<payment_methods::PaymentMethodSessionResponse> { let db: &dyn StorageInterface = state.store.as_ref(); let key_manager_state = &(&state).into(); // Validate if the session still exists let payment_method_session = db .get_payment_methods_session( key_manager_state, merchant_context.get_merchant_key_store(), &payment_method_session_id, ) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "payment methods session does not exist or has expired".to_string(), }) .attach_printable("Failed to retrieve payment methods session from db")?; let payment_method_session_billing = payment_method_session .billing .clone() .map(|billing| billing.into_inner()) .map(From::from); // Unify the billing address that we receive from the session and from the confirm request let unified_billing_address = request .payment_method_data .billing .clone() .map(|payment_method_billing| { payment_method_billing.unify_address(payment_method_session_billing.as_ref()) }) .or_else(|| payment_method_session_billing.clone()); let customer_id = payment_method_session.customer_id.clone(); let create_payment_method_request = get_payment_method_create_request( request .payment_method_data .payment_method_data .as_ref() .get_required_value("payment_method_data")?, request.payment_method_type, request.payment_method_subtype, customer_id.clone(), unified_billing_address.as_ref(), Some(&payment_method_session), ) .attach_printable("Failed to create payment method request")?; let (payment_method_response, payment_method) = Box::pin(create_payment_method_core( &state, &req_state, create_payment_method_request.clone(), &merchant_context, &profile, )) .await?; let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token"); let token_data = get_pm_list_token_data(request.payment_method_type, &payment_method)?; let intent_fulfillment_time = common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME; // insert the token data into redis if let Some(token_data) = token_data { pm_routes::ParentPaymentMethodToken::create_key_for_token(( &parent_payment_method_token, request.payment_method_type, )) .insert(intent_fulfillment_time, token_data, &state) .await?; }; let update_payment_method_session = hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum::UpdateAssociatedPaymentMethods { associated_payment_methods: Some(vec![parent_payment_method_token.clone()]) }; vault::insert_cvc_using_payment_token( &state, &parent_payment_method_token, create_payment_method_request.payment_method_data.clone(), request.payment_method_type, intent_fulfillment_time, merchant_context.get_merchant_key_store().key.get_inner(), ) .await?; let payment_method_session = db .update_payment_method_session( key_manager_state, merchant_context.get_merchant_key_store(), &payment_method_session_id, update_payment_method_session, payment_method_session, ) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "payment methods session does not exist or has expired".to_string(), }) .attach_printable("Failed to update payment methods session from db")?; let payments_response = match &payment_method_session.psp_tokenization { Some(common_types::payment_methods::PspTokenization { tokenization_type: common_enums::TokenizationType::MultiUse, .. }) => { let zero_auth_request = construct_zero_auth_payments_request( &request, &payment_method_session, &payment_method_response, )?; let payments_response = Box::pin(create_zero_auth_payment( state.clone(), req_state, merchant_context.clone(), profile.clone(), zero_auth_request, )) .await?; Some(payments_response) } Some(common_types::payment_methods::PspTokenization { tokenization_type: common_enums::TokenizationType::SingleUse, .. }) => { Box::pin(create_single_use_tokenization_flow( state.clone(), req_state.clone(), merchant_context.clone(), profile.clone(), &create_payment_method_request.clone(), &payment_method_response, &payment_method_session, )) .await?; None } None => None, }; let tokenization_response = match payment_method_session.tokenization_data.clone() { Some(tokenization_data) => { let tokenization_response = tokenization_core::create_vault_token_core( state.clone(), &merchant_context.get_merchant_account().clone(), &merchant_context.get_merchant_key_store().clone(), api_models::tokenization::GenericTokenizationRequest { customer_id: customer_id.clone(), token_request: tokenization_data, }, ) .await?; let token = match tokenization_response { services::ApplicationResponse::Json(response) => Some(response), _ => None, }; Some(token) } None => None, }; logger::debug!(?tokenization_response, "Tokenization response"); //TODO: update the payment method session with the payment id and payment method id let payment_method_session_response = transformers::generate_payment_method_session_response( payment_method_session, Secret::new("CLIENT_SECRET_REDACTED".to_string()), payments_response, (tokenization_response.flatten()), ); Ok(services::ApplicationResponse::Json( payment_method_session_response, )) } #[cfg(feature = "v2")] impl pm_types::SavedPMLPaymentsInfo { pub async fn form_payments_info( payment_intent: PaymentIntent, merchant_context: &domain::MerchantContext, profile: domain::Profile, db: &dyn StorageInterface, key_manager_state: &util_types::keymanager::KeyManagerState, ) -> RouterResult<Self> { let collect_cvv_during_payment = profile.should_collect_cvv_during_payment; let off_session_payment_flag = matches!( payment_intent.setup_future_usage, common_enums::FutureUsage::OffSession ); let is_connector_agnostic_mit_enabled = profile.is_connector_agnostic_mit_enabled.unwrap_or(false); Ok(Self { payment_intent, profile, collect_cvv_during_payment, off_session_payment_flag, is_connector_agnostic_mit_enabled, }) } pub async fn perform_payment_ops( &self, state: &SessionState, parent_payment_method_token: Option<String>, pma: &api::CustomerPaymentMethodResponseItem, pm_list_context: PaymentMethodListContext, ) -> RouterResult<()> { let token = parent_payment_method_token .as_ref() .get_required_value("parent_payment_method_token")?; let token_data = pm_list_context .get_token_data() .get_required_value("PaymentTokenData")?; let intent_fulfillment_time = self .profile .get_order_fulfillment_time() .unwrap_or(common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME); pm_routes::ParentPaymentMethodToken::create_key_for_token((token, pma.payment_method_type)) .insert(intent_fulfillment_time, token_data, state) .await?; Ok(()) } } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn create_single_use_tokenization_flow( state: SessionState, req_state: routes::app::ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, payment_method_create_request: &payment_methods::PaymentMethodCreate, payment_method: &api::PaymentMethodResponse, payment_method_session: &domain::payment_methods::PaymentMethodSession, ) -> RouterResult<()> { let customer_id = payment_method_create_request.customer_id.to_owned(); let connector_id = payment_method_create_request .get_tokenize_connector_id() .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "psp_tokenization.connector_id", }) .attach_printable("Failed to get tokenize connector id")?; let db = &state.store; let merchant_connector_account_details = db .find_merchant_connector_account_by_id( &(&state).into(), &connector_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: connector_id.get_string_repr().to_owned(), }) .attach_printable("error while fetching merchant_connector_account from connector_id")?; let auth_type = merchant_connector_account_details .get_connector_account_details() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; let payment_method_data_request = types::PaymentMethodTokenizationData { payment_method_data: domain::PaymentMethodData::try_from( payment_method_create_request.payment_method_data.clone(), ) .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "card_cvc", }) .attach_printable( "Failed to convert type from Payment Method Create Data to Payment Method Data", )?, browser_info: None, currency: api_models::enums::Currency::default(), amount: None, split_payments: None, mandate_id: None, setup_future_usage: None, customer_acceptance: None, setup_mandate_details: None, }; let payment_method_session_address = types::PaymentAddress::new( None, payment_method_session .billing .clone() .map(|address| address.into_inner()), None, None, ); let mut router_data = types::RouterData::<api::PaymentMethodToken, _, types::PaymentsResponseData> { flow: std::marker::PhantomData, merchant_id: merchant_context.get_merchant_account().get_id().clone(), customer_id: None, connector_customer: None, connector: merchant_connector_account_details .connector_name .to_string(), payment_id: consts::IRRELEVANT_PAYMENT_INTENT_ID.to_string(), //Static attempt_id: consts::IRRELEVANT_PAYMENT_ATTEMPT_ID.to_string(), //Static tenant_id: state.tenant.tenant_id.clone(), status: common_enums::enums::AttemptStatus::default(), payment_method: common_enums::enums::PaymentMethod::Card, payment_method_type: None, connector_auth_type: auth_type, description: None, address: payment_method_session_address, auth_type: common_enums::enums::AuthenticationType::default(), connector_meta_data: None, connector_wallets_details: None, amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_token: None, recurring_mandate_payment_data: None, preprocessing_id: None, payment_method_balance: None, connector_api_version: None, request: payment_method_data_request.clone(), response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), connector_request_reference_id: payment_method_session.id.get_string_repr().to_string(), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, dispute_id: None, refund_id: None, connector_response: None, payment_method_status: None, minor_amount_captured: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, }; let payment_method_token_response = Box::pin(tokenization::add_token_for_payment_method( &mut router_data, payment_method_data_request.clone(), state.clone(), &merchant_connector_account_details.clone(), )) .await?; let token_response = payment_method_token_response.token.map_err(|err| { errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: (merchant_connector_account_details.clone()) .connector_name .to_string(), status_code: err.status_code, reason: err.reason, } })?; let value = domain::SingleUsePaymentMethodToken::get_single_use_token_from_payment_method_token( token_response.clone().into(), connector_id.clone(), ); let key = domain::SingleUseTokenKey::store_key(&payment_method.id); add_single_use_token_to_store(&state, key, value) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to store single use token")?; Ok(()) } #[cfg(feature = "v2")] async fn add_single_use_token_to_store( state: &SessionState, key: domain::SingleUseTokenKey, value: domain::SingleUsePaymentMethodToken, ) -> CustomResult<(), errors::StorageError> { let redis_connection = state .store .get_redis_conn() .map_err(Into::<errors::StorageError>::into)?; redis_connection .serialize_and_set_key_with_expiry( &domain::SingleUseTokenKey::get_store_key(&key).into(), value, consts::DEFAULT_PAYMENT_METHOD_STORE_TTL, ) .await .change_context(errors::StorageError::KVError) .attach_printable("Failed to insert payment method token to redis")?; Ok(()) } #[cfg(feature = "v2")] async fn get_single_use_token_from_store( state: &SessionState, key: domain::SingleUseTokenKey, ) -> CustomResult<Option<domain::SingleUsePaymentMethodToken>, errors::StorageError> { let redis_connection = state .store .get_redis_conn() .map_err(Into::<errors::StorageError>::into)?; redis_connection .get_and_deserialize_key::<Option<domain::SingleUsePaymentMethodToken>>( &domain::SingleUseTokenKey::get_store_key(&key).into(), "SingleUsePaymentMethodToken", ) .await .change_context(errors::StorageError::KVError) .attach_printable("Failed to get payment method token from redis") } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn fetch_payment_method( state: &SessionState, merchant_context: &domain::MerchantContext, payment_method_id: &id_type::GlobalPaymentMethodId, ) -> RouterResult<domain::PaymentMethod> { let db = &state.store; let key_manager_state = &state.into(); let merchant_account = merchant_context.get_merchant_account(); let key_store = merchant_context.get_merchant_key_store(); db.find_payment_method( key_manager_state, key_store, payment_method_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) .attach_printable("Payment method not found for network token status check") } #[cfg(feature = "v2")] pub async fn check_network_token_status( state: SessionState, merchant_context: domain::MerchantContext, payment_method_id: id_type::GlobalPaymentMethodId, ) -> RouterResponse<payment_methods::NetworkTokenStatusCheckResponse> { // Retrieve the payment method from the database let payment_method = fetch_payment_method(&state, &merchant_context, &payment_method_id).await?; // Call the network token status check function let network_token_status_check_response = if payment_method.status == common_enums::PaymentMethodStatus::Active { // Check if the payment method has network token data when( payment_method .network_token_requestor_reference_id .is_none(), || { Err(errors::ApiErrorResponse::InvalidDataValue { field_name: "payment_method_id", }) }, )?; match network_tokenization::do_status_check_for_network_token(&state, &payment_method).await { Ok(network_token_details) => { let status = match network_token_details.token_status { pm_types::TokenStatus::Active => api_enums::TokenStatus::Active, pm_types::TokenStatus::Suspended => api_enums::TokenStatus::Suspended, pm_types::TokenStatus::Deactivated => api_enums::TokenStatus::Deactivated, }; payment_methods::NetworkTokenStatusCheckResponse::SuccessResponse( payment_methods::NetworkTokenStatusCheckSuccessResponse { status, token_expiry_month: network_token_details.token_expiry_month, token_expiry_year: network_token_details.token_expiry_year, card_last_four: network_token_details.card_last_4, card_expiry: network_token_details.card_expiry, token_last_four: network_token_details.token_last_4, payment_method_id, customer_id: payment_method.customer_id, }, ) } Err(e) => { let err_message = e.current_context().to_string(); logger::debug!("Network token status check failed: {:?}", e); payment_methods::NetworkTokenStatusCheckResponse::FailureResponse( payment_methods::NetworkTokenStatusCheckFailureResponse { error_message: err_message, }, ) } } } else { let err_message = "Payment Method is not active".to_string(); logger::debug!("Payment Method is not active"); payment_methods::NetworkTokenStatusCheckResponse::FailureResponse( payment_methods::NetworkTokenStatusCheckFailureResponse { error_message: err_message, }, ) }; Ok(services::ApplicationResponse::Json( network_token_status_check_response, )) }
{ "crate": "router", "file": "crates/router/src/core/payment_methods.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_1513438890666931082
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payouts.rs // Contains: 1 structs, 0 enums pub mod access_token; pub mod helpers; #[cfg(feature = "payout_retry")] pub mod retry; pub mod transformers; pub mod validator; use std::{ collections::{HashMap, HashSet}, vec::IntoIter, }; #[cfg(feature = "olap")] use api_models::payments as payment_enums; use api_models::{self, enums as api_enums, payouts::PayoutLinkResponse}; #[cfg(feature = "payout_retry")] use common_enums::PayoutRetryType; use common_utils::{ consts, ext_traits::{AsyncExt, ValueExt}, id_type::{self, GenerateId}, link_utils::{GenericLinkStatus, GenericLinkUiConfig, PayoutLinkData, PayoutLinkStatus}, types::{MinorUnit, UnifiedCode, UnifiedMessage}, }; use diesel_models::{ enums as storage_enums, generic_link::{GenericLinkNew, PayoutLink}, CommonMandateReference, PayoutsMandateReference, PayoutsMandateReferenceRecord, }; use error_stack::{report, ResultExt}; #[cfg(feature = "olap")] use futures::future::join_all; use hyperswitch_domain_models::{self as domain_models, payment_methods::PaymentMethod}; use masking::{PeekInterface, Secret}; #[cfg(feature = "payout_retry")] use retry::GsmValidation; use router_env::{instrument, logger, tracing, Env}; use scheduler::utils as pt_utils; use serde_json; use time::Duration; #[cfg(feature = "olap")] use crate::types::domain::behaviour::Conversion; #[cfg(feature = "olap")] use crate::types::PayoutActionData; use crate::{ core::{ errors::{ self, ConnectorErrorExt, CustomResult, RouterResponse, RouterResult, StorageErrorExt, }, payments::{self, customers, helpers as payment_helpers}, utils as core_utils, }, db::StorageInterface, routes::SessionState, services, types::{ self, api::{self, payments as payment_api_types, payouts}, domain, storage::{self, PaymentRoutingInfo}, transformers::{ForeignFrom, ForeignTryFrom}, }, utils::{self, OptionExt}, }; // ********************************************** TYPES ********************************************** #[derive(Clone)] pub struct PayoutData { pub billing_address: Option<domain_models::address::Address>, pub business_profile: domain::Profile, pub customer_details: Option<domain::Customer>, pub merchant_connector_account: Option<payment_helpers::MerchantConnectorAccountType>, pub payouts: storage::Payouts, pub payout_attempt: storage::PayoutAttempt, pub payout_method_data: Option<payouts::PayoutMethodData>, pub profile_id: id_type::ProfileId, pub should_terminate: bool, pub payout_link: Option<PayoutLink>, pub current_locale: String, pub payment_method: Option<PaymentMethod>, pub connector_transfer_method_id: Option<String>, pub browser_info: Option<domain_models::router_request_types::BrowserInformation>, } // ********************************************** CORE FLOWS ********************************************** pub fn get_next_connector( connectors: &mut IntoIter<api::ConnectorRoutingData>, ) -> RouterResult<api::ConnectorRoutingData> { connectors .next() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Connector not found in connectors iterator") } #[cfg(all(feature = "payouts", feature = "v1"))] pub async fn get_connector_choice( state: &SessionState, merchant_context: &domain::MerchantContext, connector: Option<String>, routing_algorithm: Option<serde_json::Value>, payout_data: &mut PayoutData, eligible_connectors: Option<Vec<api_enums::PayoutConnectors>>, ) -> RouterResult<api::ConnectorCallType> { let eligible_routable_connectors = eligible_connectors.map(|connectors| { connectors .into_iter() .map(api::enums::RoutableConnectors::from) .collect() }); let connector_choice = helpers::get_default_payout_connector(state, routing_algorithm).await?; match connector_choice { api::ConnectorChoice::SessionMultiple(_) => { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector choice - SessionMultiple")? } api::ConnectorChoice::StraightThrough(straight_through) => { let request_straight_through: api::routing::StraightThroughAlgorithm = straight_through .clone() .parse_value("StraightThroughAlgorithm") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid straight through routing rules format")?; payout_data.payout_attempt.routing_info = Some(straight_through); let mut routing_data = storage::RoutingData { routed_through: connector, merchant_connector_id: None, algorithm: Some(request_straight_through.clone()), routing_info: PaymentRoutingInfo { algorithm: None, pre_routing_results: None, }, }; helpers::decide_payout_connector( state, merchant_context, Some(request_straight_through), &mut routing_data, payout_data, eligible_routable_connectors, ) .await } api::ConnectorChoice::Decide => { let mut routing_data = storage::RoutingData { routed_through: connector, merchant_connector_id: None, algorithm: None, routing_info: PaymentRoutingInfo { algorithm: None, pre_routing_results: None, }, }; helpers::decide_payout_connector( state, merchant_context, None, &mut routing_data, payout_data, eligible_routable_connectors, ) .await } } } #[instrument(skip_all)] pub async fn make_connector_decision( state: &SessionState, merchant_context: &domain::MerchantContext, connector_call_type: api::ConnectorCallType, payout_data: &mut PayoutData, ) -> RouterResult<()> { match connector_call_type { api::ConnectorCallType::PreDetermined(routing_data) => { Box::pin(call_connector_payout( state, merchant_context, &routing_data.connector_data, payout_data, )) .await?; #[cfg(feature = "payout_retry")] { let config_bool = retry::config_should_call_gsm_payout( &*state.store, merchant_context.get_merchant_account().get_id(), PayoutRetryType::SingleConnector, ) .await; if config_bool && payout_data.should_call_gsm() { Box::pin(retry::do_gsm_single_connector_actions( state, routing_data.connector_data, payout_data, merchant_context, )) .await?; } } Ok(()) } api::ConnectorCallType::Retryable(routing_data) => { let mut routing_data = routing_data.into_iter(); let connector_data = get_next_connector(&mut routing_data)?.connector_data; Box::pin(call_connector_payout( state, merchant_context, &connector_data, payout_data, )) .await?; #[cfg(feature = "payout_retry")] { let config_multiple_connector_bool = retry::config_should_call_gsm_payout( &*state.store, merchant_context.get_merchant_account().get_id(), PayoutRetryType::MultiConnector, ) .await; if config_multiple_connector_bool && payout_data.should_call_gsm() { Box::pin(retry::do_gsm_multiple_connector_actions( state, routing_data, connector_data.clone(), payout_data, merchant_context, )) .await?; } let config_single_connector_bool = retry::config_should_call_gsm_payout( &*state.store, merchant_context.get_merchant_account().get_id(), PayoutRetryType::SingleConnector, ) .await; if config_single_connector_bool && payout_data.should_call_gsm() { Box::pin(retry::do_gsm_single_connector_actions( state, connector_data, payout_data, merchant_context, )) .await?; } } Ok(()) } _ => Err(errors::ApiErrorResponse::InternalServerError).attach_printable({ "only PreDetermined and Retryable ConnectorCallTypes are supported".to_string() })?, } } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn payouts_core( state: &SessionState, merchant_context: &domain::MerchantContext, payout_data: &mut PayoutData, routing_algorithm: Option<serde_json::Value>, eligible_connectors: Option<Vec<api_enums::PayoutConnectors>>, ) -> RouterResult<()> { let payout_attempt = &payout_data.payout_attempt; // Form connector data let connector_call_type = get_connector_choice( state, merchant_context, payout_attempt.connector.clone(), routing_algorithm, payout_data, eligible_connectors, ) .await?; // Call connector steps Box::pin(make_connector_decision( state, merchant_context, connector_call_type, payout_data, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn payouts_core( state: &SessionState, merchant_context: &domain::MerchantContext, payout_data: &mut PayoutData, routing_algorithm: Option<serde_json::Value>, eligible_connectors: Option<Vec<api_enums::PayoutConnectors>>, ) -> RouterResult<()> { todo!() } #[instrument(skip_all)] pub async fn payouts_create_core( state: SessionState, merchant_context: domain::MerchantContext, req: payouts::PayoutCreateRequest, ) -> RouterResponse<payouts::PayoutCreateResponse> { // Validate create request let (payout_id, payout_method_data, profile_id, customer, payment_method) = validator::validate_create_request(&state, &merchant_context, &req).await?; // Create DB entries let mut payout_data = payout_create_db_entries( &state, &merchant_context, &req, &payout_id, &profile_id, payout_method_data.as_ref(), &state.locale, customer.as_ref(), payment_method.clone(), ) .await?; let payout_attempt = payout_data.payout_attempt.to_owned(); let payout_type = payout_data.payouts.payout_type.to_owned(); // Persist payout method data in temp locker if req.payout_method_data.is_some() { let customer_id = payout_data .payouts .customer_id .clone() .get_required_value("customer_id when payout_method_data is provided")?; payout_data.payout_method_data = helpers::make_payout_method_data( &state, req.payout_method_data.as_ref(), payout_attempt.payout_token.as_deref(), &customer_id, &payout_attempt.merchant_id, payout_type, merchant_context.get_merchant_key_store(), Some(&mut payout_data), merchant_context.get_merchant_account().storage_scheme, ) .await?; } if let Some(true) = payout_data.payouts.confirm { payouts_core( &state, &merchant_context, &mut payout_data, req.routing.clone(), req.connector.clone(), ) .await? }; trigger_webhook_and_handle_response(&state, &merchant_context, &payout_data).await } #[instrument(skip_all)] pub async fn payouts_confirm_core( state: SessionState, merchant_context: domain::MerchantContext, req: payouts::PayoutCreateRequest, ) -> RouterResponse<payouts::PayoutCreateResponse> { let mut payout_data = Box::pin(make_payout_data( &state, &merchant_context, None, &payouts::PayoutRequest::PayoutCreateRequest(Box::new(req.to_owned())), &state.locale, )) .await?; let payout_attempt = payout_data.payout_attempt.to_owned(); let status = payout_attempt.status; helpers::validate_payout_status_against_not_allowed_statuses( status, &[ storage_enums::PayoutStatus::Cancelled, storage_enums::PayoutStatus::Success, storage_enums::PayoutStatus::Failed, storage_enums::PayoutStatus::Pending, storage_enums::PayoutStatus::Ineligible, storage_enums::PayoutStatus::RequiresFulfillment, storage_enums::PayoutStatus::RequiresVendorAccountCreation, ], "confirm", )?; helpers::update_payouts_and_payout_attempt(&mut payout_data, &merchant_context, &req, &state) .await?; let db = &*state.store; payout_data.payout_link = payout_data .payout_link .clone() .async_map(|pl| async move { let payout_link_update = storage::PayoutLinkUpdate::StatusUpdate { link_status: PayoutLinkStatus::Submitted, }; db.update_payout_link(pl, payout_link_update) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout links in db") }) .await .transpose()?; payouts_core( &state, &merchant_context, &mut payout_data, req.routing.clone(), req.connector.clone(), ) .await?; trigger_webhook_and_handle_response(&state, &merchant_context, &payout_data).await } pub async fn payouts_update_core( state: SessionState, merchant_context: domain::MerchantContext, req: payouts::PayoutCreateRequest, ) -> RouterResponse<payouts::PayoutCreateResponse> { let payout_id = req.payout_id.clone().get_required_value("payout_id")?; let mut payout_data = Box::pin(make_payout_data( &state, &merchant_context, None, &payouts::PayoutRequest::PayoutCreateRequest(Box::new(req.to_owned())), &state.locale, )) .await?; let payout_attempt = payout_data.payout_attempt.to_owned(); let status = payout_attempt.status; // Verify update feasibility if helpers::is_payout_terminal_state(status) || helpers::is_payout_initiated(status) { return Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Payout {} cannot be updated for status {status}", payout_id.get_string_repr() ), })); } helpers::update_payouts_and_payout_attempt(&mut payout_data, &merchant_context, &req, &state) .await?; let payout_attempt = payout_data.payout_attempt.to_owned(); if (req.connector.is_none(), payout_attempt.connector.is_some()) != (true, true) { // if the connector is not updated but was provided during payout create payout_data.payout_attempt.connector = None; payout_data.payout_attempt.routing_info = None; }; // Update payout method data in temp locker if req.payout_method_data.is_some() { let customer_id = payout_data .payouts .customer_id .clone() .get_required_value("customer_id when payout_method_data is provided")?; payout_data.payout_method_data = helpers::make_payout_method_data( &state, req.payout_method_data.as_ref(), payout_attempt.payout_token.as_deref(), &customer_id, &payout_attempt.merchant_id, payout_data.payouts.payout_type, merchant_context.get_merchant_key_store(), Some(&mut payout_data), merchant_context.get_merchant_account().storage_scheme, ) .await?; } if let Some(true) = payout_data.payouts.confirm { payouts_core( &state, &merchant_context, &mut payout_data, req.routing.clone(), req.connector.clone(), ) .await?; } trigger_webhook_and_handle_response(&state, &merchant_context, &payout_data).await } #[cfg(all(feature = "payouts", feature = "v1"))] #[instrument(skip_all)] pub async fn payouts_retrieve_core( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<id_type::ProfileId>, req: payouts::PayoutRetrieveRequest, ) -> RouterResponse<payouts::PayoutCreateResponse> { let mut payout_data = Box::pin(make_payout_data( &state, &merchant_context, profile_id, &payouts::PayoutRequest::PayoutRetrieveRequest(req.to_owned()), &state.locale, )) .await?; let payout_attempt = payout_data.payout_attempt.to_owned(); let status = payout_attempt.status; if matches!(req.force_sync, Some(true)) && helpers::should_call_retrieve(status) { // Form connector data let connector_call_type = get_connector_choice( &state, &merchant_context, payout_attempt.connector.clone(), None, &mut payout_data, None, ) .await?; Box::pin(complete_payout_retrieve( &state, &merchant_context, connector_call_type, &mut payout_data, )) .await?; } Ok(services::ApplicationResponse::Json( response_handler(&state, &merchant_context, &payout_data).await?, )) } #[instrument(skip_all)] pub async fn payouts_cancel_core( state: SessionState, merchant_context: domain::MerchantContext, req: payouts::PayoutActionRequest, ) -> RouterResponse<payouts::PayoutCreateResponse> { let mut payout_data = Box::pin(make_payout_data( &state, &merchant_context, None, &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()), &state.locale, )) .await?; let payout_attempt = payout_data.payout_attempt.to_owned(); let status = payout_attempt.status; // Verify if cancellation can be triggered if helpers::is_payout_terminal_state(status) { return Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Payout {:?} cannot be cancelled for status {}", payout_attempt.payout_id, status ), })); // Make local cancellation } else if helpers::is_eligible_for_local_payout_cancellation(status) { let status = storage_enums::PayoutStatus::Cancelled; let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_attempt.connector_payout_id.to_owned(), status, error_message: Some("Cancelled by user".to_string()), error_code: None, is_eligible: None, unified_code: None, unified_message: None, payout_connector_metadata: None, }; payout_data.payout_attempt = state .store .update_payout_attempt( &payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; payout_data.payouts = state .store .update_payout( &payout_data.payouts, storage::PayoutsUpdate::StatusUpdate { status }, &payout_data.payout_attempt, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; // Trigger connector's cancellation } else { // Form connector data let connector_data = match &payout_attempt.connector { Some(connector) => api::ConnectorData::get_payout_connector_by_name( &state.conf.connectors, connector, api::GetToken::Connector, payout_attempt.merchant_connector_id.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector data")?, _ => Err(errors::ApplicationError::InvalidConfigurationValueError( "Connector not found in payout_attempt - should not reach here".to_string(), )) .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "connector", }) .attach_printable("Connector not found for payout cancellation")?, }; Box::pin(cancel_payout( &state, &merchant_context, &connector_data, &mut payout_data, )) .await .attach_printable("Payout cancellation failed for given Payout request")?; } Ok(services::ApplicationResponse::Json( response_handler(&state, &merchant_context, &payout_data).await?, )) } #[instrument(skip_all)] pub async fn payouts_fulfill_core( state: SessionState, merchant_context: domain::MerchantContext, req: payouts::PayoutActionRequest, ) -> RouterResponse<payouts::PayoutCreateResponse> { let mut payout_data = Box::pin(make_payout_data( &state, &merchant_context, None, &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()), &state.locale, )) .await?; let payout_attempt = payout_data.payout_attempt.to_owned(); let status = payout_attempt.status; // Verify if fulfillment can be triggered if helpers::is_payout_terminal_state(status) || status != api_enums::PayoutStatus::RequiresFulfillment { return Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Payout {:?} cannot be fulfilled for status {}", payout_attempt.payout_id, status ), })); } // Form connector data let connector_data = match &payout_attempt.connector { Some(connector) => api::ConnectorData::get_payout_connector_by_name( &state.conf.connectors, connector, api::GetToken::Connector, payout_attempt.merchant_connector_id.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector data")?, _ => Err(errors::ApplicationError::InvalidConfigurationValueError( "Connector not found in payout_attempt - should not reach here.".to_string(), )) .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "connector", }) .attach_printable("Connector not found for payout fulfillment")?, }; helpers::fetch_payout_method_data(&state, &mut payout_data, &connector_data, &merchant_context) .await?; Box::pin(fulfill_payout( &state, &merchant_context, &connector_data, &mut payout_data, )) .await .attach_printable("Payout fulfillment failed for given Payout request")?; trigger_webhook_and_handle_response(&state, &merchant_context, &payout_data).await } #[cfg(all(feature = "olap", feature = "v2"))] pub async fn payouts_list_core( _state: SessionState, _merchant_context: domain::MerchantContext, _profile_id_list: Option<Vec<id_type::ProfileId>>, _constraints: payouts::PayoutListConstraints, ) -> RouterResponse<payouts::PayoutListResponse> { todo!() } #[cfg(all(feature = "olap", feature = "v1"))] pub async fn payouts_list_core( state: SessionState, merchant_context: domain::MerchantContext, profile_id_list: Option<Vec<id_type::ProfileId>>, constraints: payouts::PayoutListConstraints, ) -> RouterResponse<payouts::PayoutListResponse> { validator::validate_payout_list_request(&constraints)?; let merchant_id = merchant_context.get_merchant_account().get_id(); let db = state.store.as_ref(); let payouts = helpers::filter_by_constraints( db, &constraints, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; let payouts = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, payouts); let mut pi_pa_tuple_vec = PayoutActionData::new(); for payout in payouts { match db .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_id, &utils::get_payout_attempt_id( payout.payout_id.get_string_repr(), payout.attempt_count, ), storage_enums::MerchantStorageScheme::PostgresOnly, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) { Ok(payout_attempt) => { let domain_customer = match payout.customer_id.clone() { #[cfg(feature = "v1")] Some(customer_id) => db .find_customer_by_customer_id_merchant_id( &(&state).into(), &customer_id, merchant_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .map_err(|err| { let err_msg = format!( "failed while fetching customer for customer_id - {customer_id:?}", ); logger::warn!(?err, err_msg); }) .ok(), _ => None, }; let payout_id_as_payment_id_type = id_type::PaymentId::wrap(payout.payout_id.get_string_repr().to_string()) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "payout_id contains invalid data".to_string(), }) .attach_printable("Error converting payout_id to PaymentId type")?; let payment_addr = payment_helpers::create_or_find_address_for_payment_by_request( &state, None, payout.address_id.as_deref(), merchant_id, payout.customer_id.as_ref(), merchant_context.get_merchant_key_store(), &payout_id_as_payment_id_type, merchant_context.get_merchant_account().storage_scheme, ) .await .transpose() .and_then(|addr| { addr.map_err(|err| { let err_msg = format!( "billing_address missing for address_id : {:?}", payout.address_id ); logger::warn!(?err, err_msg); }) .ok() .as_ref() .map(domain_models::address::Address::from) .map(payment_enums::Address::from) }); pi_pa_tuple_vec.push(( payout.to_owned(), payout_attempt.to_owned(), domain_customer, payment_addr, )); } Err(err) => { let err_msg = format!( "failed while fetching payout_attempt for payout_id - {:?}", payout.payout_id ); logger::warn!(?err, err_msg); } } } let data: Vec<api::PayoutCreateResponse> = pi_pa_tuple_vec .into_iter() .map(ForeignFrom::foreign_from) .collect(); Ok(services::ApplicationResponse::Json( api::PayoutListResponse { size: data.len(), data, total_count: None, }, )) } #[cfg(feature = "olap")] pub async fn payouts_filtered_list_core( state: SessionState, merchant_context: domain::MerchantContext, profile_id_list: Option<Vec<id_type::ProfileId>>, filters: payouts::PayoutListFilterConstraints, ) -> RouterResponse<payouts::PayoutListResponse> { let limit = &filters.limit; validator::validate_payout_list_request_for_joins(*limit)?; let db = state.store.as_ref(); let constraints = filters.clone().into(); let list: Vec<( storage::Payouts, storage::PayoutAttempt, Option<diesel_models::Customer>, Option<diesel_models::Address>, )> = db .filter_payouts_and_attempts( merchant_context.get_merchant_account().get_id(), &constraints, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; let list = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, list); let data: Vec<api::PayoutCreateResponse> = join_all(list.into_iter().map(|(p, pa, customer, address)| async { let customer: Option<domain::Customer> = customer .async_and_then(|cust| async { domain::Customer::convert_back( &(&state).into(), cust, &(merchant_context.get_merchant_key_store().clone()).key, merchant_context .get_merchant_key_store() .merchant_id .clone() .into(), ) .await .map_err(|err| { let msg = format!("failed to convert customer for id: {:?}", p.customer_id); logger::warn!(?err, msg); }) .ok() }) .await; let payout_addr: Option<payment_enums::Address> = address .async_and_then(|addr| async { domain::Address::convert_back( &(&state).into(), addr, &(merchant_context.get_merchant_key_store().clone()).key, merchant_context .get_merchant_key_store() .merchant_id .clone() .into(), ) .await .map(ForeignFrom::foreign_from) .map_err(|err| { let msg = format!("failed to convert address for id: {:?}", p.address_id); logger::warn!(?err, msg); }) .ok() }) .await; Some((p, pa, customer, payout_addr)) })) .await .into_iter() .flatten() .map(ForeignFrom::foreign_from) .collect(); let active_payout_ids = db .filter_active_payout_ids_by_constraints( merchant_context.get_merchant_account().get_id(), &constraints, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to filter active payout ids based on the constraints")?; let total_count = db .get_total_count_of_filtered_payouts( merchant_context.get_merchant_account().get_id(), &active_payout_ids, filters.connector.clone(), filters.currency.clone(), filters.status.clone(), filters.payout_method.clone(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed to fetch total count of filtered payouts for the given constraints - {filters:?}", ) })?; Ok(services::ApplicationResponse::Json( api::PayoutListResponse { size: data.len(), data, total_count: Some(total_count), }, )) } #[cfg(feature = "olap")] pub async fn payouts_list_available_filters_core( state: SessionState, merchant_context: domain::MerchantContext, profile_id_list: Option<Vec<id_type::ProfileId>>, time_range: common_utils::types::TimeRange, ) -> RouterResponse<api::PayoutListFilters> { let db = state.store.as_ref(); let payouts = db .filter_payouts_by_time_range_constraints( merchant_context.get_merchant_account().get_id(), &time_range, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payouts = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, payouts); let filters = db .get_filters_for_payouts( payouts.as_slice(), merchant_context.get_merchant_account().get_id(), storage_enums::MerchantStorageScheme::PostgresOnly, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; Ok(services::ApplicationResponse::Json( api::PayoutListFilters { connector: filters.connector, currency: filters.currency, status: filters.status, payout_method: filters.payout_method, }, )) } // ********************************************** HELPERS ********************************************** pub async fn call_connector_payout( state: &SessionState, merchant_context: &domain::MerchantContext, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { let payout_attempt = &payout_data.payout_attempt.to_owned(); let payouts = &payout_data.payouts.to_owned(); // fetch merchant connector account if not present if payout_data.merchant_connector_account.is_none() || payout_data.payout_attempt.merchant_connector_id.is_none() { let merchant_connector_account = get_mca_from_profile_id( state, merchant_context, &payout_data.profile_id, &connector_data.connector_name.to_string(), payout_attempt .merchant_connector_id .clone() .or(connector_data.merchant_connector_id.clone()) .as_ref(), ) .await?; payout_data.payout_attempt.merchant_connector_id = merchant_connector_account.get_mca_id(); payout_data.merchant_connector_account = Some(merchant_connector_account); } // update connector_name if payout_data.payout_attempt.connector.is_none() || payout_data.payout_attempt.connector != Some(connector_data.connector_name.to_string()) { payout_data.payout_attempt.connector = Some(connector_data.connector_name.to_string()); let updated_payout_attempt = storage::PayoutAttemptUpdate::UpdateRouting { connector: connector_data.connector_name.to_string(), routing_info: payout_data.payout_attempt.routing_info.clone(), merchant_connector_id: payout_data.payout_attempt.merchant_connector_id.clone(), }; let db = &*state.store; payout_data.payout_attempt = db .update_payout_attempt( &payout_data.payout_attempt, updated_payout_attempt, payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating routing info in payout_attempt")?; }; // Fetch / store payout_method_data if payout_data.payout_method_data.is_none() || payout_attempt.payout_token.is_none() { helpers::fetch_payout_method_data(state, payout_data, connector_data, merchant_context) .await?; } // Eligibility flow Box::pin(complete_payout_eligibility( state, merchant_context, connector_data, payout_data, )) .await?; // Create customer flow Box::pin(complete_create_recipient( state, merchant_context, connector_data, payout_data, )) .await?; // Create customer's disbursement account flow Box::pin(complete_create_recipient_disburse_account( state, merchant_context, connector_data, payout_data, )) .await?; // Payout creation flow Box::pin(complete_create_payout( state, merchant_context, connector_data, payout_data, )) .await?; // Auto fulfillment flow let status = payout_data.payout_attempt.status; if payouts.auto_fulfill && status == storage_enums::PayoutStatus::RequiresFulfillment { Box::pin(fulfill_payout( state, merchant_context, connector_data, payout_data, )) .await .attach_printable("Payout fulfillment failed for given Payout request")?; } Ok(()) } pub async fn complete_create_recipient( state: &SessionState, merchant_context: &domain::MerchantContext, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { if !payout_data.should_terminate && matches!( payout_data.payout_attempt.status, common_enums::PayoutStatus::RequiresCreation | common_enums::PayoutStatus::RequiresConfirmation | common_enums::PayoutStatus::RequiresPayoutMethodData ) && connector_data .connector_name .supports_create_recipient(payout_data.payouts.payout_type) { Box::pin(create_recipient( state, merchant_context, connector_data, payout_data, )) .await .attach_printable("Creation of customer failed")?; } Ok(()) } #[cfg(feature = "v1")] pub async fn create_recipient( state: &SessionState, merchant_context: &domain::MerchantContext, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { let customer_details = payout_data.customer_details.to_owned(); let connector_name = connector_data.connector_name.to_string(); // Create the connector label using {profile_id}_{connector_name} let connector_label = format!( "{}_{}", payout_data.profile_id.get_string_repr(), connector_name ); let (should_call_connector, _connector_customer_id) = helpers::should_call_payout_connector_create_customer( state, connector_data, &customer_details, &connector_label, ); if should_call_connector { // 1. Form router data let router_data = core_utils::construct_payout_router_data( state, connector_data, merchant_context, payout_data, ) .await?; // 2. Fetch connector integration details let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< api::PoRecipient, types::PayoutsData, types::PayoutsResponseData, > = connector_data.connector.get_connector_integration(); // 3. Call connector service let router_resp = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_payout_failed_response()?; match router_resp.response { Ok(recipient_create_data) => { let db = &*state.store; if let Some(customer) = customer_details { if let Some(updated_customer) = customers::update_connector_customer_in_customers( &connector_label, Some(&customer), recipient_create_data.connector_payout_id.clone(), ) .await { #[cfg(feature = "v1")] { let customer_id = customer.customer_id.to_owned(); payout_data.customer_details = Some( db.update_customer_by_customer_id_merchant_id( &state.into(), customer_id, merchant_context.get_merchant_account().get_id().to_owned(), customer, updated_customer, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating customers in db")?, ); } #[cfg(feature = "v2")] { let customer_id = customer.get_id().clone(); payout_data.customer_details = Some( db.update_customer_by_global_id( &state.into(), &customer_id, customer, updated_customer, key_store, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating customers in db")?, ); } } } // Add next step to ProcessTracker if recipient_create_data.should_add_next_step_to_process_tracker { add_external_account_addition_task( &*state.store, payout_data, common_utils::date_time::now().saturating_add(Duration::seconds(consts::STRIPE_ACCOUNT_ONBOARDING_DELAY_IN_SECONDS)), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while adding attach_payout_account_workflow workflow to process tracker")?; // Update payout status in DB let status = recipient_create_data .status .unwrap_or(api_enums::PayoutStatus::RequiresVendorAccountCreation); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_data .payout_attempt .connector_payout_id .to_owned(), status, error_code: None, error_message: None, is_eligible: recipient_create_data.payout_eligible, unified_code: None, unified_message: None, payout_connector_metadata: payout_data .payout_attempt .payout_connector_metadata .to_owned(), }; payout_data.payout_attempt = db .update_payout_attempt( &payout_data.payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; payout_data.payouts = db .update_payout( &payout_data.payouts, storage::PayoutsUpdate::StatusUpdate { status }, &payout_data.payout_attempt, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; // Helps callee functions skip the execution payout_data.should_terminate = true; } else if let Some(status) = recipient_create_data.status { let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_data .payout_attempt .connector_payout_id .to_owned(), status, error_code: None, error_message: None, is_eligible: recipient_create_data.payout_eligible, unified_code: None, unified_message: None, payout_connector_metadata: payout_data .payout_attempt .payout_connector_metadata .to_owned(), }; payout_data.payout_attempt = db .update_payout_attempt( &payout_data.payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; payout_data.payouts = db .update_payout( &payout_data.payouts, storage::PayoutsUpdate::StatusUpdate { status }, &payout_data.payout_attempt, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; } } Err(err) => { let status = storage_enums::PayoutStatus::Failed; let (error_code, error_message) = (Some(err.code), Some(err.message)); let (unified_code, unified_message) = helpers::get_gsm_record( state, error_code.clone(), error_message.clone(), payout_data.payout_attempt.connector.clone(), consts::PAYOUT_FLOW_STR, ) .await .map_or( ( Some(crate::consts::DEFAULT_UNIFIED_ERROR_CODE.to_string()), Some(crate::consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_string()), ), |gsm| (gsm.unified_code, gsm.unified_message), ); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(), status, error_code, error_message, is_eligible: None, unified_code: unified_code .map(UnifiedCode::try_from) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "unified_code", })?, unified_message: unified_message .map(UnifiedMessage::try_from) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "unified_message", })?, payout_connector_metadata: payout_data .payout_attempt .payout_connector_metadata .to_owned(), }; let db = &*state.store; payout_data.payout_attempt = db .update_payout_attempt( &payout_data.payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; payout_data.payouts = db .update_payout( &payout_data.payouts, storage::PayoutsUpdate::StatusUpdate { status }, &payout_data.payout_attempt, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; } } } Ok(()) } #[cfg(feature = "v2")] pub async fn create_recipient( state: &SessionState, merchant_context: &domain::MerchantContext, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { todo!() } pub async fn complete_payout_eligibility( state: &SessionState, merchant_context: &domain::MerchantContext, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { let payout_attempt = &payout_data.payout_attempt.to_owned(); if !payout_data.should_terminate && payout_attempt.is_eligible.is_none() && connector_data .connector_name .supports_payout_eligibility(payout_data.payouts.payout_type) { Box::pin(check_payout_eligibility( state, merchant_context, connector_data, payout_data, )) .await .attach_printable("Eligibility failed for given Payout request")?; } utils::when( !payout_attempt .is_eligible .unwrap_or(state.conf.payouts.payout_eligibility), || { Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Payout method data is invalid".to_string(), }) .attach_printable("Payout data provided is invalid")) }, )?; Ok(()) } pub async fn check_payout_eligibility( state: &SessionState, merchant_context: &domain::MerchantContext, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { // 1. Form Router data let router_data = core_utils::construct_payout_router_data( state, connector_data, merchant_context, payout_data, ) .await?; // 2. Fetch connector integration details let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< api::PoEligibility, types::PayoutsData, types::PayoutsResponseData, > = connector_data.connector.get_connector_integration(); // 3. Call connector service let router_data_resp = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_payout_failed_response()?; // 4. Process data returned by the connector let db = &*state.store; match router_data_resp.response { Ok(payout_response_data) => { let payout_attempt = &payout_data.payout_attempt; let status = payout_response_data .status .unwrap_or(payout_attempt.status.to_owned()); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_response_data.connector_payout_id, status, error_code: payout_response_data.error_code, error_message: payout_response_data.error_message, is_eligible: payout_response_data.payout_eligible, unified_code: None, unified_message: None, payout_connector_metadata: payout_response_data.payout_connector_metadata, }; payout_data.payout_attempt = db .update_payout_attempt( payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; payout_data.payouts = db .update_payout( &payout_data.payouts, storage::PayoutsUpdate::StatusUpdate { status }, &payout_data.payout_attempt, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; } Err(err) => { let status = storage_enums::PayoutStatus::Failed; let (error_code, error_message) = (Some(err.code), Some(err.message)); let (unified_code, unified_message) = helpers::get_gsm_record( state, error_code.clone(), error_message.clone(), payout_data.payout_attempt.connector.clone(), consts::PAYOUT_FLOW_STR, ) .await .map_or( ( Some(crate::consts::DEFAULT_UNIFIED_ERROR_CODE.to_string()), Some(crate::consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_string()), ), |gsm| (gsm.unified_code, gsm.unified_message), ); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(), status, error_code, error_message, is_eligible: Some(false), unified_code: unified_code .map(UnifiedCode::try_from) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "unified_code", })?, unified_message: unified_message .map(UnifiedMessage::try_from) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "unified_message", })?, payout_connector_metadata: payout_data .payout_attempt .payout_connector_metadata .to_owned(), }; payout_data.payout_attempt = db .update_payout_attempt( &payout_data.payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; payout_data.payouts = db .update_payout( &payout_data.payouts, storage::PayoutsUpdate::StatusUpdate { status }, &payout_data.payout_attempt, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; } }; Ok(()) } pub async fn complete_create_payout( state: &SessionState, merchant_context: &domain::MerchantContext, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { if !payout_data.should_terminate && matches!( payout_data.payout_attempt.status, storage_enums::PayoutStatus::RequiresCreation | storage_enums::PayoutStatus::RequiresConfirmation | storage_enums::PayoutStatus::RequiresPayoutMethodData ) { if connector_data .connector_name .supports_instant_payout(payout_data.payouts.payout_type) { // create payout_object only in router let db = &*state.store; let payout_attempt = &payout_data.payout_attempt; let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_data.payout_attempt.connector_payout_id.clone(), status: storage::enums::PayoutStatus::RequiresFulfillment, error_code: None, error_message: None, is_eligible: None, unified_code: None, unified_message: None, payout_connector_metadata: payout_data .payout_attempt .payout_connector_metadata .to_owned(), }; payout_data.payout_attempt = db .update_payout_attempt( payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; payout_data.payouts = db .update_payout( &payout_data.payouts, storage::PayoutsUpdate::StatusUpdate { status: storage::enums::PayoutStatus::RequiresFulfillment, }, &payout_data.payout_attempt, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; } else { // create payout_object in connector as well as router Box::pin(create_payout( state, merchant_context, connector_data, payout_data, )) .await .attach_printable("Payout creation failed for given Payout request")?; } } Ok(()) } pub async fn create_payout( state: &SessionState, merchant_context: &domain::MerchantContext, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { // 1. Form Router data let mut router_data = core_utils::construct_payout_router_data( state, connector_data, merchant_context, payout_data, ) .await?; // 2. Get/Create access token access_token::create_access_token( state, connector_data, merchant_context, &mut router_data, payout_data.payouts.payout_type.to_owned(), ) .await?; // 3. Execute pretasks if helpers::should_continue_payout(&router_data) { complete_payout_quote_steps_if_required(state, connector_data, &mut router_data).await?; }; let connector_meta_data = router_data.connector_meta_data.clone(); // 4. Call connector service let router_data_resp = match helpers::should_continue_payout(&router_data) { true => { let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< api::PoCreate, types::PayoutsData, types::PayoutsResponseData, > = connector_data.connector.get_connector_integration(); services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_payout_failed_response()? } false => router_data, }; // 5. Process data returned by the connector let db = &*state.store; match router_data_resp.response { Ok(payout_response_data) => { let payout_attempt = &payout_data.payout_attempt; let status = payout_response_data .status .unwrap_or(payout_attempt.status.to_owned()); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_response_data.connector_payout_id, status, error_code: payout_response_data.error_code, error_message: payout_response_data.error_message, is_eligible: payout_response_data.payout_eligible, unified_code: None, unified_message: None, payout_connector_metadata: connector_meta_data.clone(), }; payout_data.payout_attempt = db .update_payout_attempt( payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; payout_data.payouts = db .update_payout( &payout_data.payouts, storage::PayoutsUpdate::StatusUpdate { status }, &payout_data.payout_attempt, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; } Err(err) => { let status = storage_enums::PayoutStatus::Failed; let (error_code, error_message) = (Some(err.code), Some(err.message)); let (unified_code, unified_message) = helpers::get_gsm_record( state, error_code.clone(), error_message.clone(), payout_data.payout_attempt.connector.clone(), consts::PAYOUT_FLOW_STR, ) .await .map_or( ( Some(crate::consts::DEFAULT_UNIFIED_ERROR_CODE.to_string()), Some(crate::consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_string()), ), |gsm| (gsm.unified_code, gsm.unified_message), ); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(), status, error_code, error_message, is_eligible: None, unified_code: unified_code .map(UnifiedCode::try_from) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "unified_code", })?, unified_message: unified_message .map(UnifiedMessage::try_from) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "unified_message", })?, payout_connector_metadata: connector_meta_data, }; payout_data.payout_attempt = db .update_payout_attempt( &payout_data.payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; payout_data.payouts = db .update_payout( &payout_data.payouts, storage::PayoutsUpdate::StatusUpdate { status }, &payout_data.payout_attempt, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; } }; Ok(()) } async fn complete_payout_quote_steps_if_required<F>( state: &SessionState, connector_data: &api::ConnectorData, router_data: &mut types::RouterData<F, types::PayoutsData, types::PayoutsResponseData>, ) -> RouterResult<()> { if connector_data .connector_name .is_payout_quote_call_required() { let quote_router_data = types::PayoutsRouterData::foreign_from((router_data, router_data.request.clone())); let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< api::PoQuote, types::PayoutsData, types::PayoutsResponseData, > = connector_data.connector.get_connector_integration(); let router_data_resp = services::execute_connector_processing_step( state, connector_integration, &quote_router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_payout_failed_response()?; match router_data_resp.response.to_owned() { Ok(resp) => { router_data.quote_id = resp.connector_payout_id; router_data.connector_meta_data = resp.payout_connector_metadata; } Err(_err) => { router_data.response = router_data_resp.response; } }; } Ok(()) } #[cfg(feature = "v1")] pub async fn complete_payout_retrieve( state: &SessionState, merchant_context: &domain::MerchantContext, connector_call_type: api::ConnectorCallType, payout_data: &mut PayoutData, ) -> RouterResult<()> { match connector_call_type { api::ConnectorCallType::PreDetermined(routing_data) => { Box::pin(create_payout_retrieve( state, merchant_context, &routing_data.connector_data, payout_data, )) .await .attach_printable("Payout retrieval failed for given Payout request")?; } api::ConnectorCallType::Retryable(_) | api::ConnectorCallType::SessionMultiple(_) => { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Payout retrieval not supported for given ConnectorCallType")? } } Ok(()) } #[cfg(feature = "v2")] pub async fn complete_payout_retrieve( state: &SessionState, merchant_context: &domain::MerchantContext, connector_call_type: api::ConnectorCallType, payout_data: &mut PayoutData, ) -> RouterResult<()> { todo!() } pub async fn create_payout_retrieve( state: &SessionState, merchant_context: &domain::MerchantContext, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { // 1. Form Router data let mut router_data = core_utils::construct_payout_router_data( state, connector_data, merchant_context, payout_data, ) .await?; // 2. Get/Create access token access_token::create_access_token( state, connector_data, merchant_context, &mut router_data, payout_data.payouts.payout_type.to_owned(), ) .await?; // 3. Call connector service let router_data_resp = match helpers::should_continue_payout(&router_data) { true => { let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< api::PoSync, types::PayoutsData, types::PayoutsResponseData, > = connector_data.connector.get_connector_integration(); services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_payout_failed_response()? } false => router_data, }; // 4. Process data returned by the connector update_retrieve_payout_tracker(state, merchant_context, payout_data, &router_data_resp).await?; Ok(()) } pub async fn update_retrieve_payout_tracker<F, T>( state: &SessionState, merchant_context: &domain::MerchantContext, payout_data: &mut PayoutData, payout_router_data: &types::RouterData<F, T, types::PayoutsResponseData>, ) -> RouterResult<()> { let db = &*state.store; match payout_router_data.response.as_ref() { Ok(payout_response_data) => { let payout_attempt = &payout_data.payout_attempt; let status = payout_response_data .status .unwrap_or(payout_attempt.status.to_owned()); let updated_payout_attempt = if helpers::is_payout_err_state(status) { let (error_code, error_message) = ( payout_response_data.error_code.clone(), payout_response_data.error_message.clone(), ); let (unified_code, unified_message) = helpers::get_gsm_record( state, error_code.clone(), error_message.clone(), payout_data.payout_attempt.connector.clone(), consts::PAYOUT_FLOW_STR, ) .await .map_or( ( Some(crate::consts::DEFAULT_UNIFIED_ERROR_CODE.to_string()), Some(crate::consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_string()), ), |gsm| (gsm.unified_code, gsm.unified_message), ); storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_response_data.connector_payout_id.clone(), status, error_code, error_message, is_eligible: payout_response_data.payout_eligible, unified_code: unified_code .map(UnifiedCode::try_from) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "unified_code", })?, unified_message: unified_message .map(UnifiedMessage::try_from) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "unified_message", })?, payout_connector_metadata: payout_response_data .payout_connector_metadata .clone(), } } else { storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_response_data.connector_payout_id.clone(), status, error_code: None, error_message: None, is_eligible: payout_response_data.payout_eligible, unified_code: None, unified_message: None, payout_connector_metadata: payout_response_data .payout_connector_metadata .clone(), } }; payout_data.payout_attempt = db .update_payout_attempt( payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; payout_data.payouts = db .update_payout( &payout_data.payouts, storage::PayoutsUpdate::StatusUpdate { status }, &payout_data.payout_attempt, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; } Err(err) => { // log in case of error in retrieval logger::error!("Error in payout retrieval"); // show error in the response of sync payout_data.payout_attempt.error_code = Some(err.code.to_owned()); payout_data.payout_attempt.error_message = Some(err.message.to_owned()); } }; Ok(()) } pub async fn complete_create_recipient_disburse_account( state: &SessionState, merchant_context: &domain::MerchantContext, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { if !payout_data.should_terminate && matches!( payout_data.payout_attempt.status, storage_enums::PayoutStatus::RequiresVendorAccountCreation | storage_enums::PayoutStatus::RequiresCreation ) && connector_data .connector_name .supports_vendor_disburse_account_create_for_payout() && helpers::should_create_connector_transfer_method(payout_data, connector_data)?.is_none() { Box::pin(create_recipient_disburse_account( state, merchant_context, connector_data, payout_data, )) .await .attach_printable("Creation of customer failed")?; } Ok(()) } pub async fn create_recipient_disburse_account( state: &SessionState, merchant_context: &domain::MerchantContext, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { // 1. Form Router data let router_data = core_utils::construct_payout_router_data( state, connector_data, merchant_context, payout_data, ) .await?; // 2. Fetch connector integration details let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< api::PoRecipientAccount, types::PayoutsData, types::PayoutsResponseData, > = connector_data.connector.get_connector_integration(); // 3. Call connector service let router_data_resp = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_payout_failed_response()?; // 4. Process data returned by the connector let db = &*state.store; match router_data_resp.response { Ok(payout_response_data) => { let payout_attempt = &payout_data.payout_attempt; let status = payout_response_data .status .unwrap_or(payout_attempt.status.to_owned()); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_response_data.connector_payout_id.clone(), status, error_code: payout_response_data.error_code, error_message: payout_response_data.error_message, is_eligible: payout_response_data.payout_eligible, unified_code: None, unified_message: None, payout_connector_metadata: payout_response_data.payout_connector_metadata, }; payout_data.payout_attempt = db .update_payout_attempt( payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; if let ( true, Some(ref payout_method_data), Some(connector_payout_id), Some(customer_details), Some(merchant_connector_id), ) = ( payout_data.payouts.recurring, payout_data.payout_method_data.clone(), payout_response_data.connector_payout_id.clone(), payout_data.customer_details.clone(), connector_data.merchant_connector_id.clone(), ) { let connector_mandate_details = HashMap::from([( merchant_connector_id.clone(), PayoutsMandateReferenceRecord { transfer_method_id: Some(connector_payout_id), }, )]); let common_connector_mandate = CommonMandateReference { payments: None, payouts: Some(PayoutsMandateReference(connector_mandate_details)), }; let connector_mandate_details_value = common_connector_mandate .get_mandate_details_value() .map_err(|err| { router_env::logger::error!( "Failed to get get_mandate_details_value : {:?}", err ); errors::ApiErrorResponse::MandateUpdateFailed })?; if let Some(pm_method) = payout_data.payment_method.clone() { let pm_update = diesel_models::PaymentMethodUpdate::ConnectorMandateDetailsUpdate { #[cfg(feature = "v1")] connector_mandate_details: Some(connector_mandate_details_value), #[cfg(feature = "v2")] connector_mandate_details: Some(common_connector_mandate), }; payout_data.payment_method = Some( db.update_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), pm_method, pm_update, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentMethodNotFound) .attach_printable("Unable to find payment method")?, ); } else { #[cfg(feature = "v1")] let customer_id = Some(customer_details.customer_id); #[cfg(feature = "v2")] let customer_id = customer_details.merchant_reference_id; if let Some(customer_id) = customer_id { helpers::save_payout_data_to_locker( state, payout_data, &customer_id, payout_method_data, Some(connector_mandate_details_value), merchant_context, ) .await .attach_printable("Failed to save payout data to locker")?; } }; } } Err(err) => { let (error_code, error_message) = (Some(err.code), Some(err.message)); let (unified_code, unified_message) = helpers::get_gsm_record( state, error_code.clone(), error_message.clone(), payout_data.payout_attempt.connector.clone(), consts::PAYOUT_FLOW_STR, ) .await .map_or( ( Some(crate::consts::DEFAULT_UNIFIED_ERROR_CODE.to_string()), Some(crate::consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_string()), ), |gsm| (gsm.unified_code, gsm.unified_message), ); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(), status: storage_enums::PayoutStatus::Failed, error_code, error_message, is_eligible: None, unified_code: unified_code .map(UnifiedCode::try_from) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "unified_code", })?, unified_message: unified_message .map(UnifiedMessage::try_from) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "unified_message", })?, payout_connector_metadata: payout_data .payout_attempt .payout_connector_metadata .to_owned(), }; payout_data.payout_attempt = db .update_payout_attempt( &payout_data.payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; } }; Ok(()) } pub async fn cancel_payout( state: &SessionState, merchant_context: &domain::MerchantContext, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { // 1. Form Router data let router_data = core_utils::construct_payout_router_data( state, connector_data, merchant_context, payout_data, ) .await?; // 2. Fetch connector integration details let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< api::PoCancel, types::PayoutsData, types::PayoutsResponseData, > = connector_data.connector.get_connector_integration(); // 3. Call connector service let router_data_resp = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_payout_failed_response()?; // 4. Process data returned by the connector let db = &*state.store; match router_data_resp.response { Ok(payout_response_data) => { let status = payout_response_data .status .unwrap_or(payout_data.payout_attempt.status.to_owned()); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_response_data.connector_payout_id, status, error_code: None, error_message: None, is_eligible: payout_response_data.payout_eligible, unified_code: None, unified_message: None, payout_connector_metadata: payout_response_data.payout_connector_metadata, }; payout_data.payout_attempt = db .update_payout_attempt( &payout_data.payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; payout_data.payouts = db .update_payout( &payout_data.payouts, storage::PayoutsUpdate::StatusUpdate { status }, &payout_data.payout_attempt, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; } Err(err) => { let status = storage_enums::PayoutStatus::Failed; let (error_code, error_message) = (Some(err.code), Some(err.message)); let (unified_code, unified_message) = helpers::get_gsm_record( state, error_code.clone(), error_message.clone(), payout_data.payout_attempt.connector.clone(), consts::PAYOUT_FLOW_STR, ) .await .map_or( ( Some(crate::consts::DEFAULT_UNIFIED_ERROR_CODE.to_string()), Some(crate::consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_string()), ), |gsm| (gsm.unified_code, gsm.unified_message), ); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(), status, error_code, error_message, is_eligible: None, unified_code: unified_code .map(UnifiedCode::try_from) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "unified_code", })?, unified_message: unified_message .map(UnifiedMessage::try_from) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "unified_message", })?, payout_connector_metadata: payout_data .payout_attempt .payout_connector_metadata .to_owned(), }; payout_data.payout_attempt = db .update_payout_attempt( &payout_data.payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; payout_data.payouts = db .update_payout( &payout_data.payouts, storage::PayoutsUpdate::StatusUpdate { status }, &payout_data.payout_attempt, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; } }; Ok(()) } pub async fn fulfill_payout( state: &SessionState, merchant_context: &domain::MerchantContext, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { // 1. Form Router data let mut router_data = core_utils::construct_payout_router_data( state, connector_data, merchant_context, payout_data, ) .await?; // 2. Get/Create access token access_token::create_access_token( state, connector_data, merchant_context, &mut router_data, payout_data.payouts.payout_type.to_owned(), ) .await?; // 3. Call connector service let router_data_resp = match helpers::should_continue_payout(&router_data) { true => { let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< api::PoFulfill, types::PayoutsData, types::PayoutsResponseData, > = connector_data.connector.get_connector_integration(); services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_payout_failed_response()? } false => router_data, }; // 4. Process data returned by the connector let db = &*state.store; match router_data_resp.response { Ok(payout_response_data) => { let status = payout_response_data .status .unwrap_or(payout_data.payout_attempt.status.to_owned()); payout_data.payouts.status = status; let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_response_data.connector_payout_id, status, error_code: payout_response_data.error_code, error_message: payout_response_data.error_message, is_eligible: payout_response_data.payout_eligible, unified_code: None, unified_message: None, payout_connector_metadata: payout_response_data.payout_connector_metadata, }; payout_data.payout_attempt = db .update_payout_attempt( &payout_data.payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; payout_data.payouts = db .update_payout( &payout_data.payouts, storage::PayoutsUpdate::StatusUpdate { status }, &payout_data.payout_attempt, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; if payout_data.payouts.recurring && payout_data.payouts.payout_method_id.clone().is_none() { let payout_method_data = payout_data .payout_method_data .clone() .get_required_value("payout_method_data")?; payout_data .payouts .customer_id .clone() .async_map(|customer_id| async move { helpers::save_payout_data_to_locker( state, payout_data, &customer_id, &payout_method_data, None, merchant_context, ) .await }) .await .transpose() .attach_printable("Failed to save payout data to locker")?; } } Err(err) => { let status = storage_enums::PayoutStatus::Failed; let (error_code, error_message) = (Some(err.code), Some(err.message)); let (unified_code, unified_message) = helpers::get_gsm_record( state, error_code.clone(), error_message.clone(), payout_data.payout_attempt.connector.clone(), consts::PAYOUT_FLOW_STR, ) .await .map_or( ( Some(crate::consts::DEFAULT_UNIFIED_ERROR_CODE.to_string()), Some(crate::consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_string()), ), |gsm| (gsm.unified_code, gsm.unified_message), ); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(), status, error_code, error_message, is_eligible: None, unified_code: unified_code .map(UnifiedCode::try_from) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "unified_code", })?, unified_message: unified_message .map(UnifiedMessage::try_from) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "unified_message", })?, payout_connector_metadata: payout_data .payout_attempt .payout_connector_metadata .to_owned(), }; payout_data.payout_attempt = db .update_payout_attempt( &payout_data.payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; payout_data.payouts = db .update_payout( &payout_data.payouts, storage::PayoutsUpdate::StatusUpdate { status }, &payout_data.payout_attempt, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; } }; Ok(()) } 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(); let payout_method_id: Option<String> = payout_data.payment_method.as_ref().map(|pm| { #[cfg(feature = "v1")] { pm.payment_method_id.clone() } #[cfg(feature = "v2")] { pm.id.clone().get_string_repr().to_string() } }); let payout_link = payout_data.payout_link.to_owned(); let billing_address = payout_data.billing_address.to_owned(); let customer_details = payout_data.customer_details.to_owned(); let customer_id = payouts.customer_id; let billing = billing_address.map(From::from); let translated_unified_message = helpers::get_translated_unified_code_and_message( state, payout_attempt.unified_code.as_ref(), payout_attempt.unified_message.as_ref(), &payout_data.current_locale, ) .await?; let additional_payout_method_data = payout_attempt.additional_payout_method_data.clone(); let payout_method_data = additional_payout_method_data.map(payouts::PayoutMethodDataResponse::from); let response = api::PayoutCreateResponse { payout_id: payouts.payout_id.to_owned(), merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), merchant_order_reference_id: payout_attempt.merchant_order_reference_id.clone(), amount: payouts.amount, currency: payouts.destination_currency.to_owned(), connector: payout_attempt.connector, payout_type: payouts.payout_type.to_owned(), payout_method_data, billing, auto_fulfill: payouts.auto_fulfill, customer_id, email: customer_details.as_ref().and_then(|c| c.email.clone()), name: customer_details.as_ref().and_then(|c| c.name.clone()), phone: customer_details.as_ref().and_then(|c| c.phone.clone()), phone_country_code: customer_details .as_ref() .and_then(|c| c.phone_country_code.clone()), customer: customer_details .as_ref() .map(payment_api_types::CustomerDetailsResponse::foreign_from), client_secret: payouts.client_secret.to_owned(), return_url: payouts.return_url.to_owned(), business_country: payout_attempt.business_country, business_label: payout_attempt.business_label, description: payouts.description.to_owned(), entity_type: payouts.entity_type.to_owned(), recurring: payouts.recurring, metadata: payouts.metadata, merchant_connector_id: payout_attempt.merchant_connector_id.to_owned(), status: payout_attempt.status.to_owned(), error_message: payout_attempt.error_message.to_owned(), error_code: payout_attempt.error_code, profile_id: payout_attempt.profile_id, created: Some(payouts.created_at), connector_transaction_id: payout_attempt.connector_payout_id, priority: payouts.priority, attempts: None, unified_code: payout_attempt.unified_code, unified_message: translated_unified_message, payout_link: payout_link .map(|payout_link| { url::Url::parse(payout_link.url.peek()).map(|link| PayoutLinkResponse { payout_link_id: payout_link.link_id, link: link.into(), }) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse payout link's URL")?, payout_method_id, }; Ok(response) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn payout_create_db_entries( _state: &SessionState, _merchant_context: &domain::MerchantContext, _req: &payouts::PayoutCreateRequest, _payout_id: &str, _profile_id: &str, _stored_payout_method_data: Option<&payouts::PayoutMethodData>, _locale: &str, _customer: Option<&domain::Customer>, _payment_method: Option<PaymentMethod>, ) -> RouterResult<PayoutData> { todo!() } // DB entries #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn payout_create_db_entries( state: &SessionState, merchant_context: &domain::MerchantContext, req: &payouts::PayoutCreateRequest, payout_id: &id_type::PayoutId, profile_id: &id_type::ProfileId, stored_payout_method_data: Option<&payouts::PayoutMethodData>, locale: &str, customer: Option<&domain::Customer>, payment_method: Option<PaymentMethod>, ) -> RouterResult<PayoutData> { let db = &*state.store; let merchant_id = merchant_context.get_merchant_account().get_id(); let customer_id = customer.map(|cust| cust.customer_id.clone()); // Validate whether profile_id passed in request is valid and is linked to the merchant let business_profile = validate_and_get_business_profile( state, merchant_context.get_merchant_key_store(), profile_id, merchant_id, ) .await?; let payout_link = match req.payout_link { Some(true) => Some( create_payout_link( state, &business_profile, &customer_id .clone() .get_required_value("customer.id when payout_link is true")?, merchant_id, req, payout_id, locale, ) .await?, ), _ => None, }; // Get or create billing address let (billing_address, address_id) = helpers::resolve_billing_address_for_payout( state, req.billing.as_ref(), None, payment_method.as_ref(), merchant_context, customer_id.as_ref(), payout_id, ) .await?; // Make payouts entry let currency = req.currency.to_owned().get_required_value("currency")?; let (payout_method_id, payout_type) = match stored_payout_method_data { Some(payout_method_data) => ( payment_method .as_ref() .map(|pm| pm.payment_method_id.clone()), Some(api_enums::PayoutType::foreign_from(payout_method_data)), ), None => { ( payment_method .as_ref() .map(|pm| pm.payment_method_id.clone()), match req.payout_type { None => payment_method .as_ref() .and_then(|pm| pm.payment_method) .map(|payment_method_enum| { api_enums::PayoutType::foreign_try_from(payment_method_enum) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: format!( "PaymentMethod {payment_method_enum:?} is not supported for payouts" ), }) .attach_printable("Failed to convert PaymentMethod to PayoutType") }) .transpose()?, payout_type => payout_type, }, ) } }; let client_secret = utils::generate_id( consts::ID_LENGTH, format!("payout_{}_secret", payout_id.get_string_repr()).as_str(), ); let amount = MinorUnit::from(req.amount.unwrap_or(api::Amount::Zero)); let status = if req.payout_method_data.is_some() || req.payout_token.is_some() || stored_payout_method_data.is_some() { match req.confirm { Some(true) => storage_enums::PayoutStatus::RequiresCreation, _ => storage_enums::PayoutStatus::RequiresConfirmation, } } else { storage_enums::PayoutStatus::RequiresPayoutMethodData }; let payouts_req = storage::PayoutsNew { payout_id: payout_id.clone(), merchant_id: merchant_id.to_owned(), customer_id: customer_id.to_owned(), address_id: address_id.to_owned(), payout_type, amount, destination_currency: currency, source_currency: currency, description: req.description.to_owned(), recurring: req.recurring.unwrap_or(false), auto_fulfill: req.auto_fulfill.unwrap_or(false), return_url: req.return_url.to_owned(), entity_type: req.entity_type.unwrap_or_default(), payout_method_id, profile_id: profile_id.to_owned(), attempt_count: 1, metadata: req.metadata.clone(), confirm: req.confirm, payout_link_id: payout_link .clone() .map(|link_data| link_data.link_id.clone()), client_secret: Some(client_secret), priority: req.priority, status, created_at: common_utils::date_time::now(), last_modified_at: common_utils::date_time::now(), }; let payouts = db .insert_payout( payouts_req, merchant_context.get_merchant_account().storage_scheme, ) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayout { payout_id: payout_id.clone(), }) .attach_printable("Error inserting payouts in db")?; // Make payout_attempt entry let payout_attempt_id = utils::get_payout_attempt_id(payout_id.get_string_repr(), 1); let additional_pm_data_value = req .payout_method_data .clone() .or(stored_payout_method_data.cloned()) .async_and_then(|payout_method_data| async move { helpers::get_additional_payout_data(&payout_method_data, &*state.store, profile_id) .await }) .await // If no payout method data in request but we have a stored payment method, populate from it .or_else(|| { payment_method.as_ref().and_then(|payment_method| { payment_method .get_payment_methods_data() .and_then(|pmd| pmd.get_additional_payout_method_data()) }) }); let payout_attempt_req = storage::PayoutAttemptNew { payout_attempt_id: payout_attempt_id.to_string(), payout_id: payout_id.clone(), additional_payout_method_data: additional_pm_data_value, merchant_id: merchant_id.to_owned(), merchant_order_reference_id: req.merchant_order_reference_id.clone(), status, business_country: req.business_country.to_owned(), business_label: req.business_label.to_owned(), payout_token: req.payout_token.to_owned(), profile_id: profile_id.to_owned(), customer_id, address_id, connector: None, connector_payout_id: None, is_eligible: None, error_message: None, error_code: None, created_at: common_utils::date_time::now(), last_modified_at: common_utils::date_time::now(), merchant_connector_id: None, routing_info: None, unified_code: None, unified_message: None, payout_connector_metadata: None, }; let payout_attempt = db .insert_payout_attempt( payout_attempt_req, &payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayout { payout_id: payout_id.clone(), }) .attach_printable("Error inserting payout_attempt in db")?; // Make PayoutData Ok(PayoutData { billing_address, business_profile, customer_details: customer.map(ToOwned::to_owned), merchant_connector_account: None, payouts, payout_attempt, payout_method_data: req .payout_method_data .as_ref() .cloned() .or(stored_payout_method_data.cloned()), should_terminate: false, profile_id: profile_id.to_owned(), payout_link, current_locale: locale.to_string(), payment_method, connector_transfer_method_id: None, browser_info: req.browser_info.clone().map(Into::into), }) } #[cfg(feature = "v2")] pub async fn make_payout_data( _state: &SessionState, _merchant_context: &domain::MerchantContext, _auth_profile_id: Option<id_type::ProfileId>, _req: &payouts::PayoutRequest, locale: &str, ) -> RouterResult<PayoutData> { todo!() } #[cfg(feature = "v1")] pub async fn make_payout_data( state: &SessionState, merchant_context: &domain::MerchantContext, auth_profile_id: Option<id_type::ProfileId>, req: &payouts::PayoutRequest, locale: &str, ) -> RouterResult<PayoutData> { let db = &*state.store; let merchant_id = merchant_context.get_merchant_account().get_id(); let payout_id = match req { payouts::PayoutRequest::PayoutActionRequest(r) => r.payout_id.clone(), payouts::PayoutRequest::PayoutCreateRequest(r) => { r.payout_id.clone().unwrap_or(id_type::PayoutId::generate()) } payouts::PayoutRequest::PayoutRetrieveRequest(r) => r.payout_id.clone(), }; let browser_info = match req { payouts::PayoutRequest::PayoutActionRequest(_) => None, payouts::PayoutRequest::PayoutCreateRequest(r) => r.browser_info.clone().map(Into::into), payouts::PayoutRequest::PayoutRetrieveRequest(_) => None, }; let payouts = db .find_payout_by_merchant_id_payout_id( merchant_id, &payout_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; core_utils::validate_profile_id_from_auth_layer(auth_profile_id, &payouts)?; let payout_attempt_id = utils::get_payout_attempt_id(payouts.payout_id.get_string_repr(), payouts.attempt_count); let mut payout_attempt = db .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_id, &payout_attempt_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; let customer_id = payouts.customer_id.as_ref(); // We have to do this because the function that is being used to create / get address is from payments // which expects a payment_id let payout_id_as_payment_id_type = id_type::PaymentId::try_from(std::borrow::Cow::Owned( payouts.payout_id.get_string_repr().to_string(), )) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "payout_id contains invalid data".to_string(), }) .attach_printable("Error converting payout_id to PaymentId type")?; let billing_address = payment_helpers::create_or_find_address_for_payment_by_request( state, None, payouts.address_id.as_deref(), merchant_id, customer_id, merchant_context.get_merchant_key_store(), &payout_id_as_payment_id_type, merchant_context.get_merchant_account().storage_scheme, ) .await? .map(|addr| domain_models::address::Address::from(&addr)); let payout_id = &payouts.payout_id; let customer_details = customer_id .async_map(|customer_id| async move { db.find_customer_optional_by_customer_id_merchant_id( &state.into(), customer_id, merchant_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .map_err(|err| err.change_context(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| { format!( "Failed while fetching optional customer [id - {customer_id:?}] for payout [id - {}]", payout_id.get_string_repr() ) }) }) .await .transpose()? .and_then(|c| c); let profile_id = payout_attempt.profile_id.clone(); // Validate whether profile_id passed in request is valid and is linked to the merchant let business_profile = validate_and_get_business_profile( state, merchant_context.get_merchant_key_store(), &profile_id, merchant_id, ) .await?; let payout_method_data_req = match req { payouts::PayoutRequest::PayoutCreateRequest(r) => r.payout_method_data.to_owned(), payouts::PayoutRequest::PayoutActionRequest(_) => { match payout_attempt.payout_token.to_owned() { Some(payout_token) => { let customer_id = customer_details .as_ref() .map(|cd| cd.customer_id.to_owned()) .get_required_value("customer_id when payout_token is sent")?; helpers::make_payout_method_data( state, None, Some(&payout_token), &customer_id, merchant_context.get_merchant_account().get_id(), payouts.payout_type, merchant_context.get_merchant_key_store(), None, merchant_context.get_merchant_account().storage_scheme, ) .await? } None => None, } } payouts::PayoutRequest::PayoutRetrieveRequest(_) => None, }; if let Some(payout_method_data) = payout_method_data_req.clone() { let additional_payout_method_data = helpers::get_additional_payout_data(&payout_method_data, &*state.store, &profile_id) .await; let update_additional_payout_method_data = storage::PayoutAttemptUpdate::AdditionalPayoutMethodDataUpdate { additional_payout_method_data, }; payout_attempt = db .update_payout_attempt( &payout_attempt, update_additional_payout_method_data, &payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating additional payout method data in payout_attempt")?; }; let merchant_connector_account = if payout_attempt.connector.is_some() && payout_attempt.merchant_connector_id.is_some() { let connector_name = payout_attempt .connector .clone() .get_required_value("connector_name")?; Some( payment_helpers::get_merchant_connector_account( state, merchant_context.get_merchant_account().get_id(), None, merchant_context.get_merchant_key_store(), &profile_id, connector_name.as_str(), payout_attempt.merchant_connector_id.as_ref(), ) .await?, ) } else { None }; let payout_link = payouts .payout_link_id .clone() .async_map(|link_id| async move { db.find_payout_link_by_link_id(&link_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error fetching payout links from db") }) .await .transpose()?; let payment_method = payouts .payout_method_id .clone() .async_map(|pm_id| async move { db.find_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), &pm_id, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentMethodNotFound) .attach_printable("Unable to find payment method") }) .await .transpose()?; Ok(PayoutData { billing_address, business_profile, customer_details, payouts, payout_attempt, payout_method_data: payout_method_data_req.to_owned(), merchant_connector_account, should_terminate: false, profile_id, payout_link, current_locale: locale.to_string(), payment_method, connector_transfer_method_id: None, browser_info, }) } pub async fn add_external_account_addition_task( db: &dyn StorageInterface, payout_data: &PayoutData, schedule_time: time::PrimitiveDateTime, ) -> CustomResult<(), errors::StorageError> { let runner = storage::ProcessTrackerRunner::AttachPayoutAccountWorkflow; let task = "STRPE_ATTACH_EXTERNAL_ACCOUNT"; let tag = ["PAYOUTS", "STRIPE", "ACCOUNT", "CREATE"]; let process_tracker_id = pt_utils::get_process_tracker_id( runner, task, &payout_data.payout_attempt.payout_attempt_id, &payout_data.payout_attempt.merchant_id, ); let tracking_data = api::PayoutRetrieveRequest { payout_id: payout_data.payouts.payout_id.to_owned(), force_sync: None, merchant_id: Some(payout_data.payouts.merchant_id.to_owned()), }; let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, tracking_data, None, schedule_time, common_types::consts::API_VERSION, ) .map_err(errors::StorageError::from)?; db.insert_process(process_tracker_entry).await?; Ok(()) } async fn validate_and_get_business_profile( state: &SessionState, merchant_key_store: &domain::MerchantKeyStore, profile_id: &id_type::ProfileId, merchant_id: &id_type::MerchantId, ) -> RouterResult<domain::Profile> { let db = &*state.store; let key_manager_state = &state.into(); if let Some(business_profile) = core_utils::validate_and_get_business_profile( db, key_manager_state, merchant_key_store, Some(profile_id), merchant_id, ) .await? { Ok(business_profile) } else { db.find_business_profile_by_profile_id(key_manager_state, merchant_key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), }) } } #[allow(clippy::too_many_arguments)] pub async fn create_payout_link( state: &SessionState, business_profile: &domain::Profile, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, req: &payouts::PayoutCreateRequest, payout_id: &id_type::PayoutId, locale: &str, ) -> RouterResult<PayoutLink> { let payout_link_config_req = req.payout_link_config.to_owned(); // Fetch all configs let default_config = &state.conf.generic_link.payout_link; let profile_config = &business_profile.payout_link_config; let profile_ui_config = profile_config.as_ref().map(|c| c.config.ui_config.clone()); let ui_config = payout_link_config_req .as_ref() .and_then(|config| config.ui_config.clone()) .or(profile_ui_config); let test_mode_in_config = payout_link_config_req .as_ref() .and_then(|config| config.test_mode) .or_else(|| profile_config.as_ref().and_then(|c| c.payout_test_mode)); let is_test_mode_enabled = test_mode_in_config.unwrap_or(false); let allowed_domains = match (router_env::which(), is_test_mode_enabled) { // Throw error in case test_mode was enabled in production (Env::Production, true) => Err(report!(errors::ApiErrorResponse::LinkConfigurationError { message: "test_mode cannot be true for creating payout_links in production".to_string() })), // Send empty set of whitelisted domains (_, true) => { Ok(HashSet::new()) }, // Otherwise, fetch and use allowed domains from profile config (_, false) => { profile_config .as_ref() .map(|config| config.config.allowed_domains.to_owned()) .get_required_value("allowed_domains") .change_context(errors::ApiErrorResponse::LinkConfigurationError { message: "Payout links cannot be used without setting allowed_domains in profile. If you're using a non-production environment, you can set test_mode to true while in payout_link_config" .to_string(), }) } }?; // Form data to be injected in the link let (logo, merchant_name, theme) = match ui_config { Some(config) => (config.logo, config.merchant_name, config.theme), _ => (None, None, None), }; let payout_link_config = GenericLinkUiConfig { logo, merchant_name, theme, }; let client_secret = utils::generate_id(consts::ID_LENGTH, "payout_link_secret"); let base_url = profile_config .as_ref() .and_then(|c| c.config.domain_name.as_ref()) .map(|domain| format!("https://{domain}")) .unwrap_or(state.base_url.clone()); let session_expiry = req .session_expiry .as_ref() .map_or(default_config.expiry, |expiry| *expiry); let url = format!( "{base_url}/payout_link/{}/{}?locale={}", merchant_id.get_string_repr(), payout_id.get_string_repr(), locale ); let link = url::Url::parse(&url) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("Failed to form payout link URL - {url}"))?; let req_enabled_payment_methods = payout_link_config_req .as_ref() .and_then(|req| req.enabled_payment_methods.to_owned()); let amount = req .amount .as_ref() .get_required_value("amount") .attach_printable("amount is a required value when creating payout links")?; let currency = req .currency .as_ref() .get_required_value("currency") .attach_printable("currency is a required value when creating payout links")?; let payout_link_id = core_utils::get_or_generate_id( "payout_link_id", &payout_link_config_req .as_ref() .and_then(|config| config.payout_link_id.clone()), "payout_link", )?; let form_layout = payout_link_config_req .as_ref() .and_then(|config| config.form_layout.to_owned()) .or_else(|| { profile_config .as_ref() .and_then(|config| config.form_layout.to_owned()) }); let data = PayoutLinkData { payout_link_id: payout_link_id.clone(), customer_id: customer_id.clone(), payout_id: payout_id.clone(), link, client_secret: Secret::new(client_secret), session_expiry, ui_config: payout_link_config, enabled_payment_methods: req_enabled_payment_methods, amount: MinorUnit::from(*amount), currency: *currency, allowed_domains, form_layout, test_mode: test_mode_in_config, }; create_payout_link_db_entry(state, merchant_id, &data, req.return_url.clone()).await } pub async fn create_payout_link_db_entry( state: &SessionState, merchant_id: &id_type::MerchantId, payout_link_data: &PayoutLinkData, return_url: Option<String>, ) -> RouterResult<PayoutLink> { let db: &dyn StorageInterface = &*state.store; let link_data = serde_json::to_value(payout_link_data) .map_err(|_| report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable("Failed to convert PayoutLinkData to Value")?; let payout_link = GenericLinkNew { link_id: payout_link_data.payout_link_id.to_string(), primary_reference: payout_link_data.payout_id.get_string_repr().to_string(), merchant_id: merchant_id.to_owned(), link_type: common_enums::GenericLinkType::PayoutLink, link_status: GenericLinkStatus::PayoutLink(PayoutLinkStatus::Initiated), link_data, url: payout_link_data.link.to_string().into(), return_url, expiry: common_utils::date_time::now() + Duration::seconds(payout_link_data.session_expiry.into()), ..Default::default() }; db.insert_payout_link(payout_link) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: "payout link already exists".to_string(), }) } #[instrument(skip_all)] pub async fn get_mca_from_profile_id( state: &SessionState, merchant_context: &domain::MerchantContext, profile_id: &id_type::ProfileId, connector_name: &str, merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>, ) -> RouterResult<payment_helpers::MerchantConnectorAccountType> { let merchant_connector_account = payment_helpers::get_merchant_connector_account( state, merchant_context.get_merchant_account().get_id(), None, merchant_context.get_merchant_key_store(), profile_id, connector_name, merchant_connector_id, ) .await?; Ok(merchant_connector_account) }
{ "crate": "router", "file": "crates/router/src/core/payouts.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_55674060276059949
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/cards_info.rs // Contains: 1 structs, 0 enums use actix_multipart::form::{bytes::Bytes, MultipartForm}; use api_models::cards_info as cards_info_api_types; use common_utils::fp_utils::when; use csv::Reader; use diesel_models::cards_info as card_info_models; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::cards_info; use rdkafka::message::ToBytes; use router_env::{instrument, tracing}; use crate::{ core::{ errors::{self, RouterResponse, RouterResult, StorageErrorExt}, payments::helpers, }, routes, services::ApplicationResponse, types::{ domain, transformers::{ForeignFrom, ForeignInto}, }, }; fn verify_iin_length(card_iin: &str) -> Result<(), errors::ApiErrorResponse> { let is_bin_length_in_range = card_iin.len() == 6 || card_iin.len() == 8; when(!is_bin_length_in_range, || { Err(errors::ApiErrorResponse::InvalidCardIinLength) }) } #[instrument(skip_all)] pub async fn retrieve_card_info( state: routes::SessionState, merchant_context: domain::MerchantContext, request: cards_info_api_types::CardsInfoRequest, ) -> RouterResponse<cards_info_api_types::CardInfoResponse> { let db = state.store.as_ref(); verify_iin_length(&request.card_iin)?; helpers::verify_payment_intent_time_and_client_secret( &state, &merchant_context, request.client_secret, ) .await?; let card_info = db .get_card_info(&request.card_iin) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve card information")? .ok_or(report!(errors::ApiErrorResponse::InvalidCardIin))?; Ok(ApplicationResponse::Json( cards_info_api_types::CardInfoResponse::foreign_from(card_info), )) } #[instrument(skip_all)] pub async fn create_card_info( state: routes::SessionState, card_info_request: cards_info_api_types::CardInfoCreateRequest, ) -> RouterResponse<cards_info_api_types::CardInfoResponse> { let db = state.store.as_ref(); cards_info::CardsInfoInterface::add_card_info(db, card_info_request.foreign_into()) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: "CardInfo with given key already exists in our records".to_string(), }) .map(|card_info| ApplicationResponse::Json(card_info.foreign_into())) } #[instrument(skip_all)] pub async fn update_card_info( state: routes::SessionState, card_info_request: cards_info_api_types::CardInfoUpdateRequest, ) -> RouterResponse<cards_info_api_types::CardInfoResponse> { let db = state.store.as_ref(); cards_info::CardsInfoInterface::update_card_info( db, card_info_request.card_iin, card_info_models::UpdateCardInfo { card_issuer: card_info_request.card_issuer, card_network: card_info_request.card_network, card_type: card_info_request.card_type, card_subtype: card_info_request.card_subtype, card_issuing_country: card_info_request.card_issuing_country, bank_code_id: card_info_request.bank_code_id, bank_code: card_info_request.bank_code, country_code: card_info_request.country_code, last_updated: Some(common_utils::date_time::now()), last_updated_provider: card_info_request.last_updated_provider, }, ) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "Card info with given key does not exist in our records".to_string(), }) .attach_printable("Failed while updating card info") .map(|card_info| ApplicationResponse::Json(card_info.foreign_into())) } #[derive(Debug, MultipartForm)] pub struct CardsInfoUpdateForm { #[multipart(limit = "1MB")] pub file: Bytes, } fn parse_cards_bin_csv( data: &[u8], ) -> csv::Result<Vec<cards_info_api_types::CardInfoUpdateRequest>> { let mut csv_reader = Reader::from_reader(data); let mut records = Vec::new(); let mut id_counter = 0; for result in csv_reader.deserialize() { let mut record: cards_info_api_types::CardInfoUpdateRequest = result?; id_counter += 1; record.line_number = Some(id_counter); records.push(record); } Ok(records) } pub fn get_cards_bin_records( form: CardsInfoUpdateForm, ) -> Result<Vec<cards_info_api_types::CardInfoUpdateRequest>, errors::ApiErrorResponse> { match parse_cards_bin_csv(form.file.data.to_bytes()) { Ok(records) => Ok(records), Err(e) => Err(errors::ApiErrorResponse::PreconditionFailed { message: e.to_string(), }), } } #[instrument(skip_all)] pub async fn migrate_cards_info( state: routes::SessionState, card_info_records: Vec<cards_info_api_types::CardInfoUpdateRequest>, ) -> RouterResponse<Vec<cards_info_api_types::CardInfoMigrationResponse>> { let mut result = Vec::new(); for record in card_info_records { let res = card_info_flow(record.clone(), state.clone()).await; result.push(cards_info_api_types::CardInfoMigrationResponse::from(( match res { Ok(ApplicationResponse::Json(response)) => Ok(response), Err(e) => Err(e.to_string()), _ => Err("Failed to migrate card info".to_string()), }, record, ))); } Ok(ApplicationResponse::Json(result)) } pub trait State {} pub trait TransitionTo<S: State> {} // Available states for card info migration pub struct CardInfoFetch; pub struct CardInfoAdd; pub struct CardInfoUpdate; pub struct CardInfoResponse; impl State for CardInfoFetch {} impl State for CardInfoAdd {} impl State for CardInfoUpdate {} impl State for CardInfoResponse {} // State transitions for card info migration impl TransitionTo<CardInfoAdd> for CardInfoFetch {} impl TransitionTo<CardInfoUpdate> for CardInfoFetch {} impl TransitionTo<CardInfoResponse> for CardInfoAdd {} impl TransitionTo<CardInfoResponse> for CardInfoUpdate {} // Async executor pub struct CardInfoMigrateExecutor<'a> { state: &'a routes::SessionState, record: &'a cards_info_api_types::CardInfoUpdateRequest, } impl<'a> CardInfoMigrateExecutor<'a> { fn new( state: &'a routes::SessionState, record: &'a cards_info_api_types::CardInfoUpdateRequest, ) -> Self { Self { state, record } } async fn fetch_card_info(&self) -> RouterResult<Option<card_info_models::CardInfo>> { let db = self.state.store.as_ref(); let maybe_card_info = db .get_card_info(&self.record.card_iin) .await .change_context(errors::ApiErrorResponse::InvalidCardIin)?; Ok(maybe_card_info) } async fn add_card_info(&self) -> RouterResult<card_info_models::CardInfo> { let db = self.state.store.as_ref(); let card_info = cards_info::CardsInfoInterface::add_card_info(db, self.record.clone().foreign_into()) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: "CardInfo with given key already exists in our records".to_string(), })?; Ok(card_info) } async fn update_card_info(&self) -> RouterResult<card_info_models::CardInfo> { let db = self.state.store.as_ref(); let card_info = cards_info::CardsInfoInterface::update_card_info( db, self.record.card_iin.clone(), card_info_models::UpdateCardInfo { card_issuer: self.record.card_issuer.clone(), card_network: self.record.card_network.clone(), card_type: self.record.card_type.clone(), card_subtype: self.record.card_subtype.clone(), card_issuing_country: self.record.card_issuing_country.clone(), bank_code_id: self.record.bank_code_id.clone(), bank_code: self.record.bank_code.clone(), country_code: self.record.country_code.clone(), last_updated: Some(common_utils::date_time::now()), last_updated_provider: self.record.last_updated_provider.clone(), }, ) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "Card info with given key does not exist in our records".to_string(), }) .attach_printable("Failed while updating card info")?; Ok(card_info) } } // Builder pub struct CardInfoBuilder<S: State> { state: std::marker::PhantomData<S>, pub card_info: Option<card_info_models::CardInfo>, } impl CardInfoBuilder<CardInfoFetch> { fn new() -> Self { Self { state: std::marker::PhantomData, card_info: None, } } } impl CardInfoBuilder<CardInfoFetch> { fn set_card_info( self, card_info: card_info_models::CardInfo, ) -> CardInfoBuilder<CardInfoUpdate> { CardInfoBuilder { state: std::marker::PhantomData, card_info: Some(card_info), } } fn transition(self) -> CardInfoBuilder<CardInfoAdd> { CardInfoBuilder { state: std::marker::PhantomData, card_info: None, } } } impl CardInfoBuilder<CardInfoUpdate> { fn set_updated_card_info( self, card_info: card_info_models::CardInfo, ) -> CardInfoBuilder<CardInfoResponse> { CardInfoBuilder { state: std::marker::PhantomData, card_info: Some(card_info), } } } impl CardInfoBuilder<CardInfoAdd> { fn set_added_card_info( self, card_info: card_info_models::CardInfo, ) -> CardInfoBuilder<CardInfoResponse> { CardInfoBuilder { state: std::marker::PhantomData, card_info: Some(card_info), } } } impl CardInfoBuilder<CardInfoResponse> { pub fn build(self) -> cards_info_api_types::CardInfoMigrateResponseRecord { match self.card_info { Some(card_info) => cards_info_api_types::CardInfoMigrateResponseRecord { card_iin: Some(card_info.card_iin), card_issuer: card_info.card_issuer, card_network: card_info.card_network.map(|cn| cn.to_string()), card_type: card_info.card_type, card_sub_type: card_info.card_subtype, card_issuing_country: card_info.card_issuing_country, }, None => cards_info_api_types::CardInfoMigrateResponseRecord { card_iin: None, card_issuer: None, card_network: None, card_type: None, card_sub_type: None, card_issuing_country: None, }, } } } async fn card_info_flow( record: cards_info_api_types::CardInfoUpdateRequest, state: routes::SessionState, ) -> RouterResponse<cards_info_api_types::CardInfoMigrateResponseRecord> { let builder = CardInfoBuilder::new(); let executor = CardInfoMigrateExecutor::new(&state, &record); let fetched_card_info_details = executor.fetch_card_info().await?; let builder = match fetched_card_info_details { Some(card_info) => { let builder = builder.set_card_info(card_info); let updated_card_info = executor.update_card_info().await?; builder.set_updated_card_info(updated_card_info) } None => { let builder = builder.transition(); let added_card_info = executor.add_card_info().await?; builder.set_added_card_info(added_card_info) } }; Ok(ApplicationResponse::Json(builder.build())) }
{ "crate": "router", "file": "crates/router/src/core/cards_info.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_8984237172777371578
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments.rs // Contains: 5 structs, 1 enums pub mod access_token; pub mod conditional_configs; pub mod customers; pub mod flows; pub mod helpers; pub mod operations; #[cfg(feature = "retry")] pub mod retry; pub mod routing; #[cfg(feature = "v2")] pub mod session_operation; pub mod tokenization; pub mod transformers; pub mod types; #[cfg(feature = "v2")] pub mod vault_session; #[cfg(feature = "olap")] use std::collections::HashMap; use std::{ collections::HashSet, fmt::Debug, marker::PhantomData, ops::Deref, str::FromStr, time::Instant, vec::IntoIter, }; #[cfg(feature = "v2")] use external_services::grpc_client; #[cfg(feature = "v2")] pub mod payment_methods; use std::future; #[cfg(feature = "olap")] use api_models::admin::MerchantConnectorInfo; use api_models::{ self, enums, mandates::RecurringDetails, payments::{self as payments_api}, }; pub use common_enums::enums::{CallConnectorAction, ExecutionMode, ExecutionPath, GatewaySystem}; use common_types::payments as common_payments_types; use common_utils::{ ext_traits::{AsyncExt, StringExt}, id_type, pii, types::{AmountConvertor, MinorUnit, Surcharge}, }; use diesel_models::{ephemeral_key, fraud_check::FraudCheck, refund as diesel_refund}; use error_stack::{report, ResultExt}; use events::EventInfo; use futures::future::join_all; use helpers::{decrypt_paze_token, ApplePayData}; #[cfg(feature = "v2")] use hyperswitch_domain_models::payments::{ PaymentAttemptListData, PaymentCancelData, PaymentCaptureData, PaymentConfirmData, PaymentIntentData, PaymentStatusData, }; #[cfg(feature = "v2")] use hyperswitch_domain_models::router_response_types::RedirectForm; pub use hyperswitch_domain_models::{ mandates::MandateData, payment_address::PaymentAddress, payments::{self as domain_payments, HeaderPayload}, router_data::{PaymentMethodToken, RouterData}, router_request_types::CustomerDetails, }; use hyperswitch_domain_models::{ payments::{self, payment_intent::CustomerData, ClickToPayMetaData}, router_data::AccessToken, }; use masking::{ExposeInterface, PeekInterface, Secret}; #[cfg(feature = "v2")] use operations::ValidateStatusForOperation; use redis_interface::errors::RedisError; use router_env::{instrument, tracing}; #[cfg(feature = "olap")] use router_types::transformers::ForeignFrom; use rustc_hash::FxHashMap; use scheduler::utils as pt_utils; #[cfg(feature = "v2")] pub use session_operation::payments_session_core; #[cfg(feature = "olap")] use strum::IntoEnumIterator; use time; #[cfg(feature = "v1")] pub use self::operations::{ PaymentApprove, PaymentCancel, PaymentCancelPostCapture, PaymentCapture, PaymentConfirm, PaymentCreate, PaymentExtendAuthorization, PaymentIncrementalAuthorization, PaymentPostSessionTokens, PaymentReject, PaymentSession, PaymentSessionUpdate, PaymentStatus, PaymentUpdate, PaymentUpdateMetadata, }; use self::{ conditional_configs::perform_decision_management, flows::{ConstructFlowSpecificData, Feature}, operations::{BoxedOperation, Operation, PaymentResponse}, routing::{self as self_routing, SessionFlowRoutingInput}, }; use super::{ errors::StorageErrorExt, payment_methods::surcharge_decision_configs, routing::TransactionData, unified_connector_service::should_call_unified_connector_service, }; #[cfg(feature = "v1")] use crate::core::blocklist::utils as blocklist_utils; #[cfg(feature = "v1")] use crate::core::card_testing_guard::utils as card_testing_guard_utils; #[cfg(feature = "v1")] 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::payments::helpers::{ process_through_direct, process_through_direct_with_shadow_unified_connector_service, process_through_ucs, }; #[cfg(feature = "v1")] use crate::core::routing::helpers as routing_helpers; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use crate::types::api::convert_connector_data_to_routable_connectors; use crate::{ configs::settings::{ ApplePayPreDecryptFlow, GooglePayPreDecryptFlow, PaymentFlow, PaymentMethodTypeTokenFilter, }, consts, core::{ errors::{self, CustomResult, RouterResponse, RouterResult}, payment_methods::{cards, network_tokenization}, payouts, routing::{self as core_routing}, unified_authentication_service::types::{ClickToPay, UnifiedAuthenticationService}, utils as core_utils, }, db::StorageInterface, logger, routes::{app::ReqState, metrics, payment_methods::ParentPaymentMethodToken, SessionState}, services::{self, api::Authenticate, ConnectorRedirectResponse}, types::{ self as router_types, api::{self, ConnectorCallType, ConnectorCommon}, domain, storage::{self, enums as storage_enums, payment_attempt::PaymentAttemptExt}, transformers::ForeignTryInto, }, utils::{ self, add_apple_pay_flow_metrics, add_connector_http_status_code_metrics, Encode, OptionExt, ValueExt, }, workflows::payment_sync, }; #[cfg(feature = "v1")] use crate::{ core::authentication as authentication_core, types::{api::authentication, BrowserInformation}, }; #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments, clippy::type_complexity)] #[instrument(skip_all, fields(payment_id, merchant_id))] pub async fn payments_operation_core<F, Req, Op, FData, D>( state: &SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: &domain::Profile, operation: Op, req: Req, get_tracker_response: operations::GetTrackerResponse<D>, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, ) -> RouterResult<( D, Req, Option<domain::Customer>, Option<u16>, Option<u128>, common_types::domain::ConnectorResponseData, )> where F: Send + Clone + Sync, Req: Send + Sync + Authenticate, Op: Operation<F, Req, Data = D> + Send + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, // To create connector flow specific interface data D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>, // To perform router related operation for PaymentResponse PaymentResponse: Operation<F, FData, Data = D>, FData: Send + Sync + Clone, { let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation); // 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( 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")?; operation .to_domain()? .run_decision_manager(state, &mut payment_data, profile) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to run decision manager")?; let connector = operation .to_domain()? .perform_routing(&merchant_context, profile, state, &mut payment_data) .await?; let mut connector_http_status_code = None; let (payment_data, connector_response_data) = match connector { ConnectorCallType::PreDetermined(connector_data) => { let (mca_type_details, updated_customer, router_data, tokenization_action) = call_connector_service_prerequisites( state, req_state.clone(), &merchant_context, connector_data.connector_data.clone(), &operation, &mut payment_data, &customer, call_connector_action.clone(), None, header_payload.clone(), None, profile, false, false, //should_retry_with_pan is set to false in case of PreDetermined ConnectorCallType req.should_return_raw_response(), ) .await?; let router_data = decide_unified_connector_service_call( state, req_state.clone(), &merchant_context, connector_data.connector_data.clone(), &operation, &mut payment_data, &customer, call_connector_action.clone(), None, // schedule_time is not used in PreDetermined ConnectorCallType header_payload.clone(), #[cfg(feature = "frm")] None, profile, false, false, //should_retry_with_pan is set to false in case of PreDetermined ConnectorCallType req.should_return_raw_response(), mca_type_details, router_data, updated_customer, tokenization_action, ) .await?; let connector_response_data = common_types::domain::ConnectorResponseData { raw_connector_response: router_data.raw_connector_response.clone(), }; let payments_response_operation = Box::new(PaymentResponse); connector_http_status_code = router_data.connector_http_status_code; add_connector_http_status_code_metrics(connector_http_status_code); payments_response_operation .to_post_update_tracker()? .save_pm_and_mandate( state, &router_data, &merchant_context, &mut payment_data, profile, ) .await?; let payment_data = 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?; (payment_data, connector_response_data) } ConnectorCallType::Retryable(connectors) => { let mut connectors = connectors.clone().into_iter(); let connector_data = get_connector_data(&mut connectors)?; let (mca_type_details, updated_customer, router_data, tokenization_action) = call_connector_service_prerequisites( state, req_state.clone(), &merchant_context, connector_data.connector_data.clone(), &operation, &mut payment_data, &customer, call_connector_action.clone(), None, header_payload.clone(), None, profile, false, false, //should_retry_with_pan is set to false in case of Retryable ConnectorCallType req.should_return_raw_response(), ) .await?; let router_data = decide_unified_connector_service_call( state, req_state.clone(), &merchant_context, connector_data.connector_data.clone(), &operation, &mut payment_data, &customer, call_connector_action.clone(), None, // schedule_time is not used in Retryable ConnectorCallType header_payload.clone(), #[cfg(feature = "frm")] None, profile, true, false, //should_retry_with_pan is set to false in case of PreDetermined ConnectorCallType req.should_return_raw_response(), mca_type_details, router_data, updated_customer, tokenization_action, ) .await?; let connector_response_data = common_types::domain::ConnectorResponseData { raw_connector_response: router_data.raw_connector_response.clone(), }; let payments_response_operation = Box::new(PaymentResponse); connector_http_status_code = router_data.connector_http_status_code; add_connector_http_status_code_metrics(connector_http_status_code); payments_response_operation .to_post_update_tracker()? .save_pm_and_mandate( state, &router_data, &merchant_context, &mut payment_data, profile, ) .await?; let payment_data = 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?; (payment_data, connector_response_data) } ConnectorCallType::SessionMultiple(vec) => todo!(), ConnectorCallType::Skip => ( payment_data, common_types::domain::ConnectorResponseData { raw_connector_response: None, }, ), }; 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, connector_http_status_code, None, connector_response_data, )) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments, clippy::type_complexity)] #[instrument(skip_all, fields(payment_id, merchant_id))] pub async fn internal_payments_operation_core<F, Req, Op, FData, D>( state: &SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: &domain::Profile, operation: Op, req: Req, get_tracker_response: operations::GetTrackerResponse<D>, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, ) -> RouterResult<( D, Req, Option<u16>, Option<u128>, common_types::domain::ConnectorResponseData, )> where F: Send + Clone + Sync, Req: Send + Sync + Authenticate, Op: Operation<F, Req, Data = D> + Send + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, // To create connector flow specific interface data D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>, // To perform router related operation for PaymentResponse PaymentResponse: Operation<F, FData, Data = D>, FData: Send + Sync + Clone + serde::Serialize, { let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation); // Get the trackers related to track the state of the payment let operations::GetTrackerResponse { mut payment_data } = get_tracker_response; let connector_data = operation .to_domain()? .get_connector_from_request(state, &req, &mut payment_data) .await?; let merchant_connector_account = payment_data .get_merchant_connector_details() .map(domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails) .ok_or_else(|| { error_stack::report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Merchant connector details not found in payment data") })?; operation .to_domain()? .populate_payment_data( state, &mut payment_data, &merchant_context, profile, &connector_data, ) .await?; let router_data = connector_service_decider( state, req_state.clone(), &merchant_context, connector_data.clone(), &operation, &mut payment_data, call_connector_action.clone(), header_payload.clone(), profile, req.should_return_raw_response(), merchant_connector_account, ) .await?; let connector_response_data = common_types::domain::ConnectorResponseData { raw_connector_response: router_data.raw_connector_response.clone(), }; let payments_response_operation = Box::new(PaymentResponse); let connector_http_status_code = router_data.connector_http_status_code; add_connector_http_status_code_metrics(connector_http_status_code); let payment_data = 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?; Ok(( payment_data, req, connector_http_status_code, None, connector_response_data, )) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments, clippy::type_complexity)] #[instrument(skip_all, fields(payment_id, merchant_id))] pub async fn payments_operation_core<'a, F, Req, Op, FData, D>( state: &SessionState, req_state: ReqState, merchant_context: &domain::MerchantContext, profile_id_from_auth_layer: Option<id_type::ProfileId>, operation: Op, req: Req, call_connector_action: CallConnectorAction, auth_flow: services::AuthFlow, eligible_connectors: Option<Vec<common_enums::RoutableConnectors>>, header_payload: HeaderPayload, ) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)> where F: Send + Clone + Sync + 'static, Req: Authenticate + Clone, Op: Operation<F, Req, Data = D> + Send + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, // To create connector flow specific interface data D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, // To perform router related operation for PaymentResponse PaymentResponse: Operation<F, FData, Data = D>, FData: Send + Sync + Clone + router_types::Capturable + 'static + serde::Serialize, { 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 (operation, validate_result) = operation .to_validate_request()? .validate_request(&req, merchant_context)?; tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id)); // get profile from headers let operations::GetTrackerResponse { operation, customer_details, mut payment_data, business_profile, mandate_type, } = operation .to_get_tracker()? .get_trackers( state, &validate_result.payment_id, &req, merchant_context, auth_flow, &header_payload, ) .await?; operation .to_get_tracker()? .validate_request_with_state(state, &req, &mut payment_data, &business_profile) .await?; core_utils::validate_profile_id_from_auth_layer( profile_id_from_auth_layer, &payment_data.get_payment_intent().clone(), )?; let (operation, customer) = operation .to_domain()? // get_customer_details .get_or_create_customer_details( state, &mut payment_data, customer_details, 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 authentication_type = call_decision_manager(state, merchant_context, &business_profile, &payment_data).await?; payment_data.set_authentication_type_in_attempt(authentication_type); let connector = get_connector_choice( &operation, state, &req, merchant_context, &business_profile, &mut payment_data, eligible_connectors, mandate_type, ) .await?; let payment_method_token = get_decrypted_wallet_payment_method_token( &operation, state, merchant_context, &mut payment_data, connector.as_ref(), ) .await?; payment_method_token.map(|token| payment_data.set_payment_method_token(Some(token))); let (connector, debit_routing_output) = debit_routing::perform_debit_routing( &operation, state, &business_profile, &mut payment_data, connector, ) .await; operation .to_domain()? .apply_three_ds_authentication_strategy(state, &mut payment_data, &business_profile) .await?; let should_add_task_to_process_tracker = should_add_task_to_process_tracker(&payment_data); let locale = header_payload.locale.clone(); payment_data = tokenize_in_router_when_confirm_false_or_external_authentication( state, &operation, &mut payment_data, &validate_result, merchant_context.get_merchant_key_store(), &customer, &business_profile, ) .await?; let mut connector_http_status_code = None; let mut external_latency = None; if let Some(connector_details) = connector { // Fetch and check FRM configs #[cfg(feature = "frm")] let mut frm_info = None; #[allow(unused_variables, unused_mut)] let mut should_continue_transaction: bool = true; #[cfg(feature = "frm")] let mut should_continue_capture: bool = true; #[cfg(feature = "frm")] let frm_configs = if state.conf.frm.enabled { Box::pin(frm_core::call_frm_before_connector_call( &operation, merchant_context, &mut payment_data, state, &mut frm_info, &customer, &mut should_continue_transaction, &mut should_continue_capture, )) .await? } else { None }; #[cfg(feature = "frm")] logger::debug!( "frm_configs: {:?}\nshould_continue_transaction: {:?}\nshould_continue_capture: {:?}", frm_configs, should_continue_transaction, should_continue_capture, ); let is_eligible_for_uas = helpers::is_merchant_eligible_authentication_service( merchant_context.get_merchant_account().get_id(), state, ) .await?; if is_eligible_for_uas { operation .to_domain()? .call_unified_authentication_service_if_eligible( state, &mut payment_data, &mut should_continue_transaction, &connector_details, &business_profile, merchant_context.get_merchant_key_store(), mandate_type, ) .await?; } else { logger::info!( "skipping authentication service call since the merchant is not eligible." ); operation .to_domain()? .call_external_three_ds_authentication_if_eligible( state, &mut payment_data, &mut should_continue_transaction, &connector_details, &business_profile, merchant_context.get_merchant_key_store(), mandate_type, ) .await?; }; operation .to_domain()? .payments_dynamic_tax_calculation( state, &mut payment_data, &connector_details, &business_profile, merchant_context, ) .await?; if should_continue_transaction { #[cfg(feature = "frm")] match ( should_continue_capture, payment_data.get_payment_attempt().capture_method, ) { ( false, Some(storage_enums::CaptureMethod::Automatic) | Some(storage_enums::CaptureMethod::SequentialAutomatic), ) | (false, Some(storage_enums::CaptureMethod::Scheduled)) => { if let Some(info) = &mut frm_info { if let Some(frm_data) = &mut info.frm_data { frm_data.fraud_check.payment_capture_method = payment_data.get_payment_attempt().capture_method; } } payment_data .set_capture_method_in_attempt(storage_enums::CaptureMethod::Manual); logger::debug!("payment_id : {:?} capture method has been changed to manual, since it has configured Post FRM flow",payment_data.get_payment_attempt().payment_id); } _ => (), }; payment_data = match connector_details { ConnectorCallType::PreDetermined(ref connector) => { #[cfg(all(feature = "dynamic_routing", feature = "v1"))] let routable_connectors = convert_connector_data_to_routable_connectors( std::slice::from_ref(connector), ) .map_err(|e| logger::error!(routable_connector_error=?e)) .unwrap_or_default(); let schedule_time = if should_add_task_to_process_tracker { payment_sync::get_sync_process_schedule_time( &*state.store, connector.connector_data.connector.id(), merchant_context.get_merchant_account().get_id(), 0, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting process schedule time")? } else { None }; let (merchant_connector_account, router_data, tokenization_action) = call_connector_service_prerequisites( state, merchant_context, connector.connector_data.clone(), &operation, &mut payment_data, &customer, &validate_result, &business_profile, false, None, ) .await?; let (router_data, mca) = decide_unified_connector_service_call( state, req_state.clone(), merchant_context, connector.connector_data.clone(), &operation, &mut payment_data, &customer, call_connector_action.clone(), &validate_result, schedule_time, header_payload.clone(), #[cfg(feature = "frm")] frm_info.as_ref().and_then(|fi| fi.suggested_action), #[cfg(not(feature = "frm"))] None, &business_profile, false, <Req as Authenticate>::should_return_raw_response(&req), merchant_connector_account, router_data, tokenization_action, ) .await?; let op_ref = &operation; let should_trigger_post_processing_flows = is_operation_confirm(&operation); let operation = Box::new(PaymentResponse); connector_http_status_code = router_data.connector_http_status_code; external_latency = router_data.external_latency; //add connector http status code metrics add_connector_http_status_code_metrics(connector_http_status_code); operation .to_post_update_tracker()? .save_pm_and_mandate( state, &router_data, merchant_context, &mut payment_data, &business_profile, ) .await?; let mut payment_data = 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, &locale, #[cfg(all(feature = "dynamic_routing", feature = "v1"))] routable_connectors, #[cfg(all(feature = "dynamic_routing", feature = "v1"))] &business_profile, ) .await?; if should_trigger_post_processing_flows { complete_postprocessing_steps_if_required( state, merchant_context, &customer, &mca, &connector.connector_data, &mut payment_data, op_ref, Some(header_payload.clone()), ) .await?; } if is_eligible_for_uas { complete_confirmation_for_click_to_pay_if_required( state, merchant_context, &payment_data, ) .await?; } payment_data } ConnectorCallType::Retryable(ref connectors) => { #[cfg(all(feature = "dynamic_routing", feature = "v1"))] let routable_connectors = convert_connector_data_to_routable_connectors(connectors) .map_err(|e| logger::error!(routable_connector_error=?e)) .unwrap_or_default(); let mut connectors = connectors.clone().into_iter(); let (connector_data, routing_decision) = get_connector_data_with_routing_decision( &mut connectors, &business_profile, debit_routing_output, )?; let schedule_time = if should_add_task_to_process_tracker { payment_sync::get_sync_process_schedule_time( &*state.store, connector_data.connector.id(), merchant_context.get_merchant_account().get_id(), 0, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting process schedule time")? } else { None }; let (merchant_connector_account, router_data, tokenization_action) = call_connector_service_prerequisites( state, merchant_context, connector_data.clone(), &operation, &mut payment_data, &customer, &validate_result, &business_profile, false, routing_decision, ) .await?; let (router_data, mca) = decide_unified_connector_service_call( state, req_state.clone(), merchant_context, connector_data.clone(), &operation, &mut payment_data, &customer, call_connector_action.clone(), &validate_result, schedule_time, header_payload.clone(), #[cfg(feature = "frm")] frm_info.as_ref().and_then(|fi| fi.suggested_action), #[cfg(not(feature = "frm"))] None, &business_profile, false, <Req as Authenticate>::should_return_raw_response(&req), merchant_connector_account, router_data, tokenization_action, ) .await?; #[cfg(all(feature = "retry", feature = "v1"))] let mut router_data = router_data; #[cfg(all(feature = "retry", feature = "v1"))] { use crate::core::payments::retry::{self, GsmValidation}; let config_bool = retry::config_should_call_gsm( &*state.store, merchant_context.get_merchant_account().get_id(), &business_profile, ) .await; if config_bool && router_data.should_call_gsm() { router_data = retry::do_gsm_actions( state, req_state.clone(), &mut payment_data, connectors, &connector_data, router_data, merchant_context, &operation, &customer, &validate_result, schedule_time, #[cfg(feature = "frm")] frm_info.as_ref().and_then(|fi| fi.suggested_action), #[cfg(not(feature = "frm"))] None, &business_profile, ) .await?; }; } let op_ref = &operation; let should_trigger_post_processing_flows = is_operation_confirm(&operation); let operation = Box::new(PaymentResponse); connector_http_status_code = router_data.connector_http_status_code; external_latency = router_data.external_latency; //add connector http status code metrics add_connector_http_status_code_metrics(connector_http_status_code); operation .to_post_update_tracker()? .save_pm_and_mandate( state, &router_data, merchant_context, &mut payment_data, &business_profile, ) .await?; let mut payment_data = 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, &locale, #[cfg(all(feature = "dynamic_routing", feature = "v1"))] routable_connectors, #[cfg(all(feature = "dynamic_routing", feature = "v1"))] &business_profile, ) .await?; if should_trigger_post_processing_flows { complete_postprocessing_steps_if_required( state, merchant_context, &customer, &mca, &connector_data, &mut payment_data, op_ref, Some(header_payload.clone()), ) .await?; } if is_eligible_for_uas { complete_confirmation_for_click_to_pay_if_required( state, merchant_context, &payment_data, ) .await?; } payment_data } ConnectorCallType::SessionMultiple(connectors) => { let session_surcharge_details = call_surcharge_decision_management_for_session_flow( state, merchant_context, &business_profile, payment_data.get_payment_attempt(), payment_data.get_payment_intent(), payment_data.get_billing_address(), &connectors, ) .await?; Box::pin(call_multiple_connectors_service( state, merchant_context, connectors, &operation, payment_data, &customer, session_surcharge_details, &business_profile, header_payload.clone(), <Req as Authenticate>::should_return_raw_response(&req), )) .await? } }; #[cfg(feature = "frm")] if let Some(fraud_info) = &mut frm_info { #[cfg(feature = "v1")] Box::pin(frm_core::post_payment_frm_core( state, req_state, merchant_context, &mut payment_data, fraud_info, frm_configs .clone() .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "frm_configs", }) .attach_printable("Frm configs label not found")?, &customer, &mut should_continue_capture, )) .await?; } } else { (_, payment_data) = operation .to_update_tracker()? .update_trackers( state, req_state, payment_data.clone(), customer.clone(), validate_result.storage_scheme, None, merchant_context.get_merchant_key_store(), #[cfg(feature = "frm")] frm_info.and_then(|info| info.suggested_action), #[cfg(not(feature = "frm"))] None, header_payload.clone(), ) .await?; } let payment_intent_status = payment_data.get_payment_intent().status; payment_data .get_payment_attempt() .payment_token .as_ref() .zip(payment_data.get_payment_attempt().payment_method) .map(ParentPaymentMethodToken::create_key_for_token) .async_map(|key_for_hyperswitch_token| async move { if key_for_hyperswitch_token .should_delete_payment_method_token(payment_intent_status) { let _ = key_for_hyperswitch_token.delete(state).await; } }) .await; } else { (_, payment_data) = operation .to_update_tracker()? .update_trackers( state, req_state, payment_data.clone(), customer.clone(), validate_result.storage_scheme, None, merchant_context.get_merchant_key_store(), None, header_payload.clone(), ) .await?; } let cloned_payment_data = payment_data.clone(); let cloned_customer = customer.clone(); #[cfg(feature = "v1")] operation .to_domain()? .store_extended_card_info_temporarily( state, payment_data.get_payment_intent().get_id(), &business_profile, payment_data.get_payment_method_data(), ) .await?; utils::trigger_payments_webhook( merchant_context.clone(), business_profile, cloned_payment_data, cloned_customer, state, operation, ) .await .map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error)) .ok(); Ok(( payment_data, req, customer, connector_http_status_code, external_latency, )) } #[cfg(feature = "v1")] // This function is intended for use when the feature being implemented is not aligned with the // core payment operations. #[allow(clippy::too_many_arguments, clippy::type_complexity)] #[instrument(skip_all, fields(payment_id, merchant_id))] pub async fn proxy_for_payments_operation_core<F, Req, Op, FData, D>( state: &SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile_id_from_auth_layer: Option<id_type::ProfileId>, operation: Op, req: Req, call_connector_action: CallConnectorAction, auth_flow: services::AuthFlow, header_payload: HeaderPayload, return_raw_connector_response: Option<bool>, ) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)> where F: Send + Clone + Sync, Req: Authenticate + Clone, Op: Operation<F, Req, Data = D> + Send + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, // To create connector flow specific interface data D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData> + Send + Sync, // To perform router related operation for PaymentResponse PaymentResponse: Operation<F, FData, Data = D>, FData: 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 (operation, validate_result) = operation .to_validate_request()? .validate_request(&req, &merchant_context)?; tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id)); let operations::GetTrackerResponse { operation, customer_details, mut payment_data, business_profile, mandate_type: _, } = operation .to_get_tracker()? .get_trackers( state, &validate_result.payment_id, &req, &merchant_context, auth_flow, &header_payload, ) .await?; core_utils::validate_profile_id_from_auth_layer( profile_id_from_auth_layer, &payment_data.get_payment_intent().clone(), )?; common_utils::fp_utils::when(!should_call_connector(&operation, &payment_data), || { Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration).attach_printable(format!( "Nti and card details based mit flow is not support for this {operation:?} payment operation" )) })?; let connector_choice = operation .to_domain()? .get_connector( &merchant_context, &state.clone(), &req, payment_data.get_payment_intent(), ) .await?; let connector = set_eligible_connector_for_nti_in_payment_data( state, &business_profile, merchant_context.get_merchant_key_store(), &mut payment_data, connector_choice, ) .await?; let should_add_task_to_process_tracker = should_add_task_to_process_tracker(&payment_data); let locale = header_payload.locale.clone(); let schedule_time = if should_add_task_to_process_tracker { payment_sync::get_sync_process_schedule_time( &*state.store, connector.connector.id(), merchant_context.get_merchant_account().get_id(), 0, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting process schedule time")? } else { None }; let (operation, customer) = operation .to_domain()? .get_or_create_customer_details( state, &mut payment_data, customer_details, 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 (router_data, mca) = proxy_for_call_connector_service( state, req_state.clone(), &merchant_context, connector.clone(), &operation, &mut payment_data, &customer, call_connector_action.clone(), &validate_result, schedule_time, header_payload.clone(), &business_profile, return_raw_connector_response, ) .await?; let op_ref = &operation; let should_trigger_post_processing_flows = is_operation_confirm(&operation); let operation = Box::new(PaymentResponse); let connector_http_status_code = router_data.connector_http_status_code; let external_latency = router_data.external_latency; add_connector_http_status_code_metrics(connector_http_status_code); #[cfg(all(feature = "dynamic_routing", feature = "v1"))] let routable_connectors = convert_connector_data_to_routable_connectors(&[connector.clone().into()]) .map_err(|e| logger::error!(routable_connector_error=?e)) .unwrap_or_default(); let mut payment_data = 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, &locale, #[cfg(all(feature = "dynamic_routing", feature = "v1"))] routable_connectors, #[cfg(all(feature = "dynamic_routing", feature = "v1"))] &business_profile, ) .await?; if should_trigger_post_processing_flows { complete_postprocessing_steps_if_required( state, &merchant_context, &None, &mca, &connector, &mut payment_data, op_ref, Some(header_payload.clone()), ) .await?; } let cloned_payment_data = payment_data.clone(); utils::trigger_payments_webhook( merchant_context.clone(), business_profile, cloned_payment_data, None, state, operation, ) .await .map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error)) .ok(); Ok(( payment_data, req, None, connector_http_status_code, external_latency, )) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments, clippy::type_complexity)] #[instrument(skip_all, fields(payment_id, merchant_id))] pub async fn proxy_for_payments_operation_core<F, Req, Op, FData, D>( state: &SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, operation: Op, req: Req, get_tracker_response: operations::GetTrackerResponse<D>, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, return_raw_connector_response: Option<bool>, ) -> RouterResult<(D, Req, Option<u16>, Option<u128>)> where F: Send + Clone + Sync, Req: Send + Sync + Authenticate, Op: Operation<F, Req, Data = D> + Send + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, // To create connector flow specific interface data D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>, // To perform router related operation for PaymentResponse PaymentResponse: Operation<F, FData, Data = D>, FData: Send + Sync + Clone, { let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation); // Get the trackers related to track the state of the payment let operations::GetTrackerResponse { mut payment_data } = get_tracker_response; // consume the req merchant_connector_id and set it in the payment_data let connector = operation .to_domain()? .perform_routing(&merchant_context, &profile, state, &mut payment_data) .await?; let payment_data = match connector { ConnectorCallType::PreDetermined(connector_data) => { let router_data = proxy_for_call_connector_service( state, req_state.clone(), &merchant_context, connector_data.connector_data.clone(), &operation, &mut payment_data, call_connector_action.clone(), header_payload.clone(), &profile, return_raw_connector_response, ) .await?; let payments_response_operation = Box::new(PaymentResponse); 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::Retryable(vec) => todo!(), ConnectorCallType::SessionMultiple(vec) => todo!(), ConnectorCallType::Skip => payment_data, }; Ok((payment_data, req, None, None)) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments, clippy::type_complexity)] #[instrument(skip_all, fields(payment_id, merchant_id))] pub async fn external_vault_proxy_for_payments_operation_core<F, Req, Op, FData, D>( state: &SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, operation: Op, req: Req, get_tracker_response: operations::GetTrackerResponse<D>, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, return_raw_connector_response: Option<bool>, ) -> RouterResult<(D, Req, Option<u16>, Option<u128>)> where F: Send + Clone + Sync, Req: Send + Sync + Authenticate, Op: Operation<F, Req, Data = D> + Send + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, // To create connector flow specific interface data D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>, // To perform router related operation for PaymentResponse PaymentResponse: Operation<F, FData, Data = D>, FData: Send + Sync + Clone, { let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation); // Get the trackers related to track the state of the payment let operations::GetTrackerResponse { mut payment_data } = get_tracker_response; 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")?; operation .to_domain()? .create_or_fetch_payment_method(state, &merchant_context, &profile, &mut payment_data) .await?; // consume the req merchant_connector_id and set it in the payment_data let connector = operation .to_domain()? .perform_routing(&merchant_context, &profile, state, &mut payment_data) .await?; let payment_data = match connector { ConnectorCallType::PreDetermined(connector_data) => { let (mca_type_details, external_vault_mca_type_details, updated_customer, router_data) = call_connector_service_prerequisites_for_external_vault_proxy( state, req_state.clone(), &merchant_context, connector_data.connector_data.clone(), &operation, &mut payment_data, &customer, call_connector_action.clone(), None, header_payload.clone(), None, &profile, false, false, //should_retry_with_pan is set to false in case of PreDetermined ConnectorCallType req.should_return_raw_response(), ) .await?; let router_data = call_unified_connector_service_for_external_proxy( state, req_state.clone(), &merchant_context, connector_data.connector_data.clone(), &operation, &mut payment_data, &customer, call_connector_action.clone(), None, // schedule_time is not used in PreDetermined ConnectorCallType header_payload.clone(), #[cfg(feature = "frm")] None, &profile, false, false, //should_retry_with_pan is set to false in case of PreDetermined ConnectorCallType req.should_return_raw_response(), mca_type_details, external_vault_mca_type_details, router_data, updated_customer, ) .await?; // update payment method if its a successful transaction if router_data.status.is_success() { operation .to_domain()? .update_payment_method(state, &merchant_context, &mut payment_data) .await; } let payments_response_operation = Box::new(PaymentResponse); 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::Retryable(_) => todo!(), ConnectorCallType::SessionMultiple(_) => todo!(), ConnectorCallType::Skip => payment_data, }; Ok((payment_data, req, None, None)) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments, clippy::type_complexity)] #[instrument(skip_all, fields(payment_id, merchant_id))] pub async fn payments_intent_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> + OperationSessionSetters<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)) } #[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>( state: &SessionState, merchant_context: &domain::MerchantContext, _business_profile: &domain::Profile, payment_data: &D, ) -> RouterResult<Option<enums::AuthenticationType>> where F: Clone, D: OperationSessionGetters<F>, { let setup_mandate = payment_data.get_setup_mandate(); let payment_method_data = payment_data.get_payment_method_data(); let payment_dsl_data = core_routing::PaymentsDslInput::new( setup_mandate, payment_data.get_payment_attempt(), payment_data.get_payment_intent(), payment_method_data, payment_data.get_address(), payment_data.get_recurring_details(), payment_data.get_currency(), ); let algorithm_ref: api::routing::RoutingAlgorithmRef = merchant_context .get_merchant_account() .routing_algorithm .clone() .map(|val| val.parse_value("routing algorithm")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not decode the routing algorithm")? .unwrap_or_default(); let output = perform_decision_management( state, algorithm_ref, merchant_context.get_merchant_account().get_id(), &payment_dsl_data, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not decode the conditional config")?; Ok(payment_dsl_data .payment_attempt .authentication_type .or(output.override_3ds)) } // TODO: Move to business profile surcharge column #[instrument(skip_all)] #[cfg(feature = "v2")] pub fn call_decision_manager<F>( state: &SessionState, record: common_types::payments::DecisionManagerRecord, payment_data: &PaymentConfirmData<F>, ) -> RouterResult<Option<enums::AuthenticationType>> where F: Clone, { let payment_method_data = payment_data.get_payment_method_data(); let payment_dsl_data = core_routing::PaymentsDslInput::new( None, payment_data.get_payment_attempt(), payment_data.get_payment_intent(), payment_method_data, payment_data.get_address(), None, payment_data.get_currency(), ); let output = perform_decision_management(record, &payment_dsl_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not decode the conditional config")?; Ok(output.override_3ds) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn populate_surcharge_details<F>( state: &SessionState, payment_data: &mut PaymentData<F>, ) -> RouterResult<()> where F: Send + Clone, { todo!() } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn populate_surcharge_details<F>( state: &SessionState, payment_data: &mut PaymentData<F>, ) -> RouterResult<()> where F: Send + Clone, { if payment_data .payment_intent .surcharge_applicable .unwrap_or(false) { logger::debug!("payment_intent.surcharge_applicable = true"); if let Some(surcharge_details) = payment_data.payment_attempt.get_surcharge_details() { // if retry payment, surcharge would have been populated from the previous attempt. Use the same surcharge let surcharge_details = types::SurchargeDetails::from((&surcharge_details, &payment_data.payment_attempt)); payment_data.surcharge_details = Some(surcharge_details); return Ok(()); } let raw_card_key = payment_data .payment_method_data .as_ref() .and_then(helpers::get_key_params_for_surcharge_details) .map(|(payment_method, payment_method_type, card_network)| { types::SurchargeKey::PaymentMethodData( payment_method, payment_method_type, card_network, ) }); let saved_card_key = payment_data.token.clone().map(types::SurchargeKey::Token); let surcharge_key = raw_card_key .or(saved_card_key) .get_required_value("payment_method_data or payment_token")?; logger::debug!(surcharge_key_confirm =? surcharge_key); let calculated_surcharge_details = match types::SurchargeMetadata::get_individual_surcharge_detail_from_redis( state, surcharge_key, &payment_data.payment_attempt.attempt_id, ) .await { Ok(surcharge_details) => Some(surcharge_details), Err(err) if err.current_context() == &RedisError::NotFound => None, Err(err) => { Err(err).change_context(errors::ApiErrorResponse::InternalServerError)? } }; payment_data.surcharge_details = calculated_surcharge_details.clone(); //Update payment_attempt net_amount with surcharge details payment_data .payment_attempt .net_amount .set_surcharge_details(calculated_surcharge_details); } else { let surcharge_details = payment_data .payment_attempt .get_surcharge_details() .map(|surcharge_details| { logger::debug!("surcharge sent in payments create request"); types::SurchargeDetails::from(( &surcharge_details, &payment_data.payment_attempt, )) }); payment_data.surcharge_details = surcharge_details; } Ok(()) } #[inline] pub fn get_connector_data( connectors: &mut IntoIter<api::ConnectorRoutingData>, ) -> RouterResult<api::ConnectorRoutingData> { connectors .next() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Connector not found in connectors iterator") } #[cfg(feature = "v1")] pub fn get_connector_with_networks( connectors: &mut IntoIter<api::ConnectorRoutingData>, ) -> Option<(api::ConnectorData, enums::CardNetwork)> { connectors.find_map(|connector| { connector .network .map(|network| (connector.connector_data, network)) }) } #[cfg(feature = "v1")] fn get_connector_data_with_routing_decision( connectors: &mut IntoIter<api::ConnectorRoutingData>, business_profile: &domain::Profile, debit_routing_output_optional: Option<api_models::open_router::DebitRoutingOutput>, ) -> RouterResult<( api::ConnectorData, Option<routing_helpers::RoutingDecisionData>, )> { if business_profile.is_debit_routing_enabled && debit_routing_output_optional.is_some() { if let Some((data, card_network)) = get_connector_with_networks(connectors) { let debit_routing_output = debit_routing_output_optional.get_required_value("debit routing output")?; let routing_decision = routing_helpers::RoutingDecisionData::get_debit_routing_decision_data( card_network, Some(debit_routing_output), ); return Ok((data, Some(routing_decision))); } } Ok((get_connector_data(connectors)?.connector_data, None)) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn call_surcharge_decision_management_for_session_flow( _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_attempt: &storage::PaymentAttempt, _payment_intent: &storage::PaymentIntent, _billing_address: Option<hyperswitch_domain_models::address::Address>, _session_connector_data: &[api::SessionConnectorData], ) -> RouterResult<Option<api::SessionSurchargeDetails>> { todo!() } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn call_surcharge_decision_management_for_session_flow( state: &SessionState, merchant_context: &domain::MerchantContext, _business_profile: &domain::Profile, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, billing_address: Option<hyperswitch_domain_models::address::Address>, session_connector_data: &api::SessionConnectorDatas, ) -> RouterResult<Option<api::SessionSurchargeDetails>> { if let Some(surcharge_amount) = payment_attempt.net_amount.get_surcharge_amount() { Ok(Some(api::SessionSurchargeDetails::PreDetermined( types::SurchargeDetails { original_amount: payment_attempt.net_amount.get_order_amount(), surcharge: Surcharge::Fixed(surcharge_amount), tax_on_surcharge: None, surcharge_amount, tax_on_surcharge_amount: payment_attempt .net_amount .get_tax_on_surcharge() .unwrap_or_default(), }, ))) } else { let payment_method_type_list = session_connector_data .iter() .map(|session_connector_data| session_connector_data.payment_method_sub_type) .collect(); #[cfg(feature = "v1")] let algorithm_ref: api::routing::RoutingAlgorithmRef = merchant_context .get_merchant_account() .routing_algorithm .clone() .map(|val| val.parse_value("routing algorithm")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not decode the routing algorithm")? .unwrap_or_default(); // TODO: Move to business profile surcharge column #[cfg(feature = "v2")] let algorithm_ref: api::routing::RoutingAlgorithmRef = todo!(); let surcharge_results = surcharge_decision_configs::perform_surcharge_decision_management_for_session_flow( state, algorithm_ref, payment_attempt, payment_intent, billing_address, &payment_method_type_list, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error performing surcharge decision operation")?; Ok(if surcharge_results.is_empty_result() { None } else { Some(api::SessionSurchargeDetails::Calculated(surcharge_results)) }) } } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn payments_core<F, Res, Req, Op, FData, D>( state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile_id: Option<id_type::ProfileId>, operation: Op, req: Req, auth_flow: services::AuthFlow, call_connector_action: CallConnectorAction, eligible_connectors: Option<Vec<enums::Connector>>, header_payload: HeaderPayload, ) -> RouterResponse<Res> where F: Send + Clone + Sync + 'static, FData: Send + Sync + Clone + router_types::Capturable + 'static + serde::Serialize, Op: Operation<F, Req, Data = D> + Send + Sync + Clone, Req: Debug + Authenticate + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, Res: transformers::ToResponse<F, D, Op>, // To create connector flow specific interface data D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, // To perform router related operation for PaymentResponse PaymentResponse: Operation<F, FData, Data = D>, { let eligible_routable_connectors = eligible_connectors.map(|connectors| { connectors .into_iter() .flat_map(|c| c.foreign_try_into()) .collect() }); let (payment_data, _req, customer, connector_http_status_code, external_latency) = payments_operation_core::<_, _, _, _, _>( &state, req_state, &merchant_context, profile_id, operation.clone(), req, call_connector_action, auth_flow, eligible_routable_connectors, header_payload.clone(), ) .await?; Res::generate_response( payment_data, customer, auth_flow, &state.base_url, operation, &state.conf.connector_request_reference_id_config, connector_http_status_code, external_latency, header_payload.x_hs_latency, ) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn proxy_for_payments_core<F, Res, Req, Op, FData, D>( state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile_id: Option<id_type::ProfileId>, operation: Op, req: Req, auth_flow: services::AuthFlow, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, return_raw_connector_response: Option<bool>, ) -> RouterResponse<Res> where F: Send + Clone + Sync, FData: Send + Sync + Clone, Op: Operation<F, Req, Data = D> + Send + Sync + Clone, Req: Debug + Authenticate + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, Res: transformers::ToResponse<F, D, Op>, // To create connector flow specific interface data D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, // To perform router related operation for PaymentResponse PaymentResponse: Operation<F, FData, Data = D>, { let (payment_data, _req, customer, connector_http_status_code, external_latency) = proxy_for_payments_operation_core::<_, _, _, _, _>( &state, req_state, merchant_context, profile_id, operation.clone(), req, call_connector_action, auth_flow, header_payload.clone(), return_raw_connector_response, ) .await?; Res::generate_response( payment_data, customer, auth_flow, &state.base_url, operation, &state.conf.connector_request_reference_id_config, connector_http_status_code, external_latency, header_payload.x_hs_latency, ) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn proxy_for_payments_core<F, Res, Req, Op, FData, D>( state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, operation: Op, req: Req, payment_id: id_type::GlobalPaymentId, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, return_raw_connector_response: Option<bool>, ) -> RouterResponse<Res> where F: Send + Clone + Sync, Req: Send + Sync + Authenticate, FData: Send + Sync + Clone, Op: Operation<F, Req, Data = D> + ValidateStatusForOperation + Send + Sync + Clone, Req: Debug, D: OperationSessionGetters<F> + OperationSessionSetters<F> + transformers::GenerateResponse<Res> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, PaymentResponse: Operation<F, FData, Data = D>, RouterData<F, FData, router_types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>, { operation .to_validate_request()? .validate_request(&req, &merchant_context)?; let get_tracker_response = operation .to_get_tracker()? .get_trackers( &state, &payment_id, &req, &merchant_context, &profile, &header_payload, ) .await?; let (payment_data, _req, connector_http_status_code, external_latency) = proxy_for_payments_operation_core::<_, _, _, _, _>( &state, req_state, merchant_context.clone(), profile.clone(), operation.clone(), req, get_tracker_response, call_connector_action, header_payload.clone(), return_raw_connector_response, ) .await?; payment_data.generate_response( &state, connector_http_status_code, external_latency, header_payload.x_hs_latency, &merchant_context, &profile, None, ) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn external_vault_proxy_for_payments_core<F, Res, Req, Op, FData, D>( state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, operation: Op, req: Req, payment_id: id_type::GlobalPaymentId, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, return_raw_connector_response: Option<bool>, ) -> RouterResponse<Res> where F: Send + Clone + Sync, Req: Send + Sync + Authenticate, FData: Send + Sync + Clone, Op: Operation<F, Req, Data = D> + ValidateStatusForOperation + Send + Sync + Clone, Req: Debug, D: OperationSessionGetters<F> + OperationSessionSetters<F> + transformers::GenerateResponse<Res> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, PaymentResponse: Operation<F, FData, Data = D>, RouterData<F, FData, router_types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>, { operation .to_validate_request()? .validate_request(&req, &merchant_context)?; let get_tracker_response = operation .to_get_tracker()? .get_trackers( &state, &payment_id, &req, &merchant_context, &profile, &header_payload, ) .await?; let (payment_data, _req, connector_http_status_code, external_latency) = external_vault_proxy_for_payments_operation_core::<_, _, _, _, _>( &state, req_state, merchant_context.clone(), profile.clone(), operation.clone(), req, get_tracker_response, call_connector_action, header_payload.clone(), return_raw_connector_response, ) .await?; payment_data.generate_response( &state, connector_http_status_code, external_latency, header_payload.x_hs_latency, &merchant_context, &profile, None, ) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn record_attempt_core( state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, req: api_models::payments::PaymentsAttemptRecordRequest, payment_id: id_type::GlobalPaymentId, header_payload: HeaderPayload, ) -> RouterResponse<api_models::payments::PaymentAttemptRecordResponse> { tracing::Span::current().record( "merchant_id", merchant_context .get_merchant_account() .get_id() .get_string_repr(), ); let operation: &operations::payment_attempt_record::PaymentAttemptRecord = &operations::payment_attempt_record::PaymentAttemptRecord; let boxed_operation: BoxedOperation< '_, api::RecordAttempt, api_models::payments::PaymentsAttemptRecordRequest, domain_payments::PaymentAttemptRecordData<api::RecordAttempt>, > = Box::new(operation); let _validate_result = boxed_operation .to_validate_request()? .validate_request(&req, &merchant_context)?; tracing::Span::current().record("global_payment_id", payment_id.get_string_repr()); let operations::GetTrackerResponse { payment_data } = boxed_operation .to_get_tracker()? .get_trackers( &state, &payment_id, &req, &merchant_context, &profile, &header_payload, ) .await?; let default_payment_status_data = PaymentStatusData { flow: PhantomData, payment_intent: payment_data.payment_intent.clone(), payment_attempt: payment_data.payment_attempt.clone(), attempts: None, should_sync_with_connector: false, payment_address: payment_data.payment_address.clone(), merchant_connector_details: None, }; let payment_status_data = (req.triggered_by == common_enums::TriggeredBy::Internal) .then(|| default_payment_status_data.clone()) .async_unwrap_or_else(|| async { match Box::pin(proxy_for_payments_operation_core::< api::PSync, _, _, _, PaymentStatusData<api::PSync>, >( &state, req_state.clone(), merchant_context.clone(), profile.clone(), operations::PaymentGet, api::PaymentsRetrieveRequest { force_sync: true, expand_attempts: false, param: None, return_raw_connector_response: None, merchant_connector_details: None, }, operations::GetTrackerResponse { payment_data: PaymentStatusData { flow: PhantomData, payment_intent: payment_data.payment_intent.clone(), payment_attempt: payment_data.payment_attempt.clone(), attempts: None, should_sync_with_connector: true, payment_address: payment_data.payment_address.clone(), merchant_connector_details: None, }, }, CallConnectorAction::Trigger, HeaderPayload::default(), None, )) .await { Ok((data, _, _, _)) => data, Err(err) => { router_env::logger::error!(error=?err, "proxy_for_payments_operation_core failed for external payment attempt"); default_payment_status_data } } }) .await; let record_payment_data = domain_payments::PaymentAttemptRecordData { flow: PhantomData, payment_intent: payment_status_data.payment_intent, payment_attempt: payment_status_data.payment_attempt, revenue_recovery_data: payment_data.revenue_recovery_data.clone(), payment_address: payment_data.payment_address.clone(), }; let (_operation, final_payment_data) = boxed_operation .to_update_tracker()? .update_trackers( &state, req_state, record_payment_data, None, merchant_context.get_merchant_account().storage_scheme, None, merchant_context.get_merchant_key_store(), None, header_payload.clone(), ) .await?; transformers::GenerateResponse::generate_response( final_payment_data, &state, None, None, header_payload.x_hs_latency, &merchant_context, &profile, None, ) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn payments_intent_core<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> + OperationSessionSetters<F> + Send + Sync + Clone, Res: transformers::ToResponse<F, D, Op>, { let (payment_data, _req, customer) = payments_intent_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_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( state: SessionState, merchant_context: domain::MerchantContext, profile: domain::Profile, req_state: ReqState, merchant_reference_id: &id_type::PaymentReferenceId, header_payload: HeaderPayload, ) -> RouterResponse<api::PaymentsIntentResponse> { let db = state.store.as_ref(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let key_manager_state = &(&state).into(); let payment_intent = db .find_payment_intent_by_merchant_reference_id_profile_id( key_manager_state, merchant_reference_id, profile.get_id(), merchant_context.get_merchant_key_store(), &storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let (payment_data, _req, customer) = Box::pin(payments_intent_operation_core::< api::PaymentGetIntent, _, _, PaymentIntentData<api::PaymentGetIntent>, >( &state, req_state, merchant_context.clone(), profile.clone(), operations::PaymentGetIntent, api_models::payments::PaymentsGetIntentRequest { id: payment_intent.get_id().clone(), }, payment_intent.get_id().clone(), header_payload.clone(), )) .await?; transformers::ToResponse::< api::PaymentGetIntent, PaymentIntentData<api::PaymentGetIntent>, operations::PaymentGetIntent, >::generate_response( payment_data, customer, &state.base_url, operations::PaymentGetIntent, &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_core<F, Res, Req, Op, FData, D>( state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, operation: Op, req: Req, payment_id: id_type::GlobalPaymentId, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, ) -> RouterResponse<Res> where F: Send + Clone + Sync, Req: Send + Sync + Authenticate, FData: Send + Sync + Clone + serde::Serialize, Op: Operation<F, Req, Data = D> + ValidateStatusForOperation + Send + Sync + Clone, Req: Debug, D: OperationSessionGetters<F> + OperationSessionSetters<F> + transformers::GenerateResponse<Res> + Send + Sync + Clone, // To create connector flow specific interface data D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, // To perform router related operation for PaymentResponse PaymentResponse: Operation<F, FData, Data = D>, // To create updatable objects in post update tracker RouterData<F, FData, router_types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>, { // Validate the request fields operation .to_validate_request()? .validate_request(&req, &merchant_context)?; // Get the tracker related information. This includes payment intent and payment attempt let get_tracker_response = operation .to_get_tracker()? .get_trackers( &state, &payment_id, &req, &merchant_context, &profile, &header_payload, ) .await?; let (payment_data, connector_http_status_code, external_latency, connector_response_data) = if state.conf.merchant_id_auth.merchant_id_auth_enabled { let ( payment_data, _req, connector_http_status_code, external_latency, connector_response_data, ) = internal_payments_operation_core::<_, _, _, _, _>( &state, req_state, merchant_context.clone(), &profile, operation.clone(), req, get_tracker_response, call_connector_action, header_payload.clone(), ) .await?; ( payment_data, connector_http_status_code, external_latency, connector_response_data, ) } else { let ( payment_data, _req, _customer, connector_http_status_code, external_latency, connector_response_data, ) = payments_operation_core::<_, _, _, _, _>( &state, req_state, merchant_context.clone(), &profile, operation.clone(), req, get_tracker_response, call_connector_action, header_payload.clone(), ) .await?; ( payment_data, connector_http_status_code, external_latency, connector_response_data, ) }; payment_data.generate_response( &state, connector_http_status_code, external_latency, header_payload.x_hs_latency, &merchant_context, &profile, Some(connector_response_data), ) } #[allow(clippy::too_many_arguments)] #[cfg(feature = "v2")] pub(crate) async fn payments_create_and_confirm_intent( state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, request: payments_api::PaymentsRequest, header_payload: HeaderPayload, ) -> RouterResponse<payments_api::PaymentsResponse> { use hyperswitch_domain_models::{ payments::PaymentIntentData, router_flow_types::PaymentCreateIntent, }; let payment_id = id_type::GlobalPaymentId::generate(&state.conf.cell_information.id); let payload = payments_api::PaymentsCreateIntentRequest::from(&request); let create_intent_response = Box::pin(payments_intent_core::< PaymentCreateIntent, payments_api::PaymentsIntentResponse, _, _, PaymentIntentData<PaymentCreateIntent>, >( state.clone(), req_state.clone(), merchant_context.clone(), profile.clone(), operations::PaymentIntentCreate, payload, payment_id.clone(), header_payload.clone(), )) .await?; logger::info!(?create_intent_response); let create_intent_response = create_intent_response .get_json_body() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unexpected response from payments core")?; let payload = payments_api::PaymentsConfirmIntentRequest::from(&request); let confirm_intent_response = decide_authorize_or_setup_intent_flow( state, req_state, merchant_context, profile, &create_intent_response, payload, payment_id, header_payload, ) .await?; logger::info!(?confirm_intent_response); Ok(confirm_intent_response) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn decide_authorize_or_setup_intent_flow( state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, create_intent_response: &payments_api::PaymentsIntentResponse, confirm_intent_request: payments_api::PaymentsConfirmIntentRequest, payment_id: id_type::GlobalPaymentId, header_payload: HeaderPayload, ) -> RouterResponse<payments_api::PaymentsResponse> { use hyperswitch_domain_models::{ payments::PaymentConfirmData, router_flow_types::{Authorize, SetupMandate}, }; if create_intent_response.amount_details.order_amount == MinorUnit::zero() { Box::pin(payments_core::< SetupMandate, api_models::payments::PaymentsResponse, _, _, _, PaymentConfirmData<SetupMandate>, >( state, req_state, merchant_context, profile, operations::PaymentIntentConfirm, confirm_intent_request, payment_id, CallConnectorAction::Trigger, header_payload, )) .await } else { Box::pin(payments_core::< Authorize, api_models::payments::PaymentsResponse, _, _, _, PaymentConfirmData<Authorize>, >( state, req_state, merchant_context, profile, operations::PaymentIntentConfirm, confirm_intent_request, payment_id, CallConnectorAction::Trigger, header_payload, )) .await } } fn is_start_pay<Op: Debug>(operation: &Op) -> bool { format!("{operation:?}").eq("PaymentStart") } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsRedirectResponseData { pub connector: Option<String>, pub param: Option<String>, pub merchant_id: Option<id_type::MerchantId>, pub json_payload: Option<serde_json::Value>, pub resource_id: api::PaymentIdType, pub force_sync: bool, pub creds_identifier: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsRedirectResponseData { pub payment_id: id_type::GlobalPaymentId, pub query_params: String, pub json_payload: Option<serde_json::Value>, } #[async_trait::async_trait] pub trait PaymentRedirectFlow: Sync { // Associated type for call_payment_flow response type PaymentFlowResponse; #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn call_payment_flow( &self, state: &SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, req: PaymentsRedirectResponseData, connector_action: CallConnectorAction, connector: String, payment_id: id_type::PaymentId, ) -> RouterResult<Self::PaymentFlowResponse>; #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn call_payment_flow( &self, state: &SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, req: PaymentsRedirectResponseData, ) -> RouterResult<Self::PaymentFlowResponse>; fn get_payment_action(&self) -> services::PaymentAction; #[cfg(feature = "v1")] fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, payment_id: id_type::PaymentId, connector: String, ) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>>; #[cfg(feature = "v2")] fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, ) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>>; #[cfg(feature = "v1")] async fn handle_payments_redirect_response( &self, state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, req: PaymentsRedirectResponseData, ) -> RouterResponse<api::RedirectionResponse> { metrics::REDIRECTION_TRIGGERED.add( 1, router_env::metric_attributes!( ( "connector", req.connector.to_owned().unwrap_or("null".to_string()), ), ( "merchant_id", merchant_context.get_merchant_account().get_id().clone() ), ), ); let connector = req.connector.clone().get_required_value("connector")?; let query_params = req.param.clone().get_required_value("param")?; #[cfg(feature = "v1")] let resource_id = api::PaymentIdTypeExt::get_payment_intent_id(&req.resource_id) .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "payment_id", })?; #[cfg(feature = "v2")] //TODO: Will get the global payment id from the resource id, we need to handle this in the further flow let resource_id: id_type::PaymentId = todo!(); // This connector data is ephemeral, the call payment flow will get new connector data // with merchant account details, so the connector_id can be safely set to None here let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector, api::GetToken::Connector, None, )?; let flow_type = connector_data .connector .get_flow_type( &query_params, req.json_payload.clone(), self.get_payment_action(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to decide the response flow")?; let payment_flow_response = self .call_payment_flow( &state, req_state, merchant_context, req.clone(), flow_type, connector.clone(), resource_id.clone(), ) .await?; self.generate_response(&payment_flow_response, resource_id, connector) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn handle_payments_redirect_response( &self, state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, request: PaymentsRedirectResponseData, ) -> RouterResponse<api::RedirectionResponse> { metrics::REDIRECTION_TRIGGERED.add( 1, router_env::metric_attributes!(( "merchant_id", merchant_context.get_merchant_account().get_id().clone() )), ); let payment_flow_response = self .call_payment_flow(&state, req_state, merchant_context, profile, request) .await?; self.generate_response(&payment_flow_response) } } #[derive(Clone, Debug)] pub struct PaymentRedirectCompleteAuthorize; #[cfg(feature = "v1")] #[async_trait::async_trait] impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { type PaymentFlowResponse = router_types::RedirectPaymentFlowResponse; #[allow(clippy::too_many_arguments)] async fn call_payment_flow( &self, state: &SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, req: PaymentsRedirectResponseData, connector_action: CallConnectorAction, _connector: String, _payment_id: id_type::PaymentId, ) -> RouterResult<Self::PaymentFlowResponse> { let key_manager_state = &state.into(); let payment_confirm_req = api::PaymentsRequest { payment_id: Some(req.resource_id.clone()), merchant_id: req.merchant_id.clone(), merchant_connector_details: req.creds_identifier.map(|creds_id| { api::MerchantConnectorDetailsWrap { creds_identifier: creds_id, encoded_data: None, } }), feature_metadata: Some(api_models::payments::FeatureMetadata { redirect_response: Some(api_models::payments::RedirectResponse { param: req.param.map(Secret::new), json_payload: Some(req.json_payload.unwrap_or(serde_json::json!({})).into()), }), search_tags: None, apple_pay_recurring_details: None, }), ..Default::default() }; let response = Box::pin(payments_core::< api::CompleteAuthorize, api::PaymentsResponse, _, _, _, _, >( state.clone(), req_state, merchant_context.clone(), None, operations::payment_complete_authorize::CompleteAuthorize, payment_confirm_req, services::api::AuthFlow::Merchant, connector_action, None, HeaderPayload::default(), )) .await?; let payments_response = match response { services::ApplicationResponse::Json(response) => Ok(response), services::ApplicationResponse::JsonWithHeaders((response, _)) => Ok(response), _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the response in json"), }?; let profile_id = payments_response .profile_id .as_ref() .get_required_value("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(), })?; Ok(router_types::RedirectPaymentFlowResponse { payments_response, business_profile, }) } fn get_payment_action(&self) -> services::PaymentAction { services::PaymentAction::CompleteAuthorize } fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, payment_id: id_type::PaymentId, connector: String, ) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>> { let payments_response = &payment_flow_response.payments_response; // There might be multiple redirections needed for some flows // If the status is requires customer action, then send the startpay url again // The redirection data must have been provided and updated by the connector let redirection_response = match payments_response.status { enums::IntentStatus::RequiresCustomerAction => { let startpay_url = payments_response .next_action .clone() .and_then(|next_action_data| match next_action_data { api_models::payments::NextActionData::RedirectToUrl { redirect_to_url } => Some(redirect_to_url), api_models::payments::NextActionData::RedirectInsidePopup{popup_url, ..} => Some(popup_url), api_models::payments::NextActionData::DisplayBankTransferInformation { .. } => None, api_models::payments::NextActionData::ThirdPartySdkSessionToken { .. } => None, api_models::payments::NextActionData::QrCodeInformation{..} => None, api_models::payments::NextActionData::FetchQrCodeInformation{..} => None, api_models::payments::NextActionData::DisplayVoucherInformation{ .. } => None, api_models::payments::NextActionData::WaitScreenInformation{..} => None, api_models::payments::NextActionData::ThreeDsInvoke{..} => None, api_models::payments::NextActionData::InvokeSdkClient{..} => None, api_models::payments::NextActionData::CollectOtp{ .. } => None, api_models::payments::NextActionData::InvokeHiddenIframe{ .. } => None, api_models::payments::NextActionData::SdkUpiIntentInformation{ .. } => None, }) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable( "did not receive redirect to url when status is requires customer action", )?; Ok(api::RedirectionResponse { return_url: String::new(), params: vec![], return_url_with_query_params: startpay_url, http_method: "GET".to_string(), headers: vec![], }) } // If the status is terminal status, then redirect to merchant return url to provide status enums::IntentStatus::Succeeded | enums::IntentStatus::Failed | enums::IntentStatus::Cancelled | enums::IntentStatus::RequiresCapture| enums::IntentStatus::Processing=> helpers::get_handle_response_url( payment_id, &payment_flow_response.business_profile, payments_response, connector, ), _ => Err(errors::ApiErrorResponse::InternalServerError).attach_printable_lazy(|| format!("Could not proceed with payment as payment status {} cannot be handled during redirection",payments_response.status))? }?; if payments_response .is_iframe_redirection_enabled .unwrap_or(false) { // html script to check if inside iframe, then send post message to parent for redirection else redirect self to return_url let html = core_utils::get_html_redirect_response_popup( redirection_response.return_url_with_query_params, )?; Ok(services::ApplicationResponse::Form(Box::new( services::RedirectionFormData { redirect_form: services::RedirectForm::Html { html_data: html }, payment_method_data: None, amount: payments_response.amount.to_string(), currency: payments_response.currency.clone(), }, ))) } else { Ok(services::ApplicationResponse::JsonForRedirection( redirection_response, )) } } } #[derive(Clone, Debug)] pub struct PaymentRedirectSync; #[cfg(feature = "v1")] #[async_trait::async_trait] impl PaymentRedirectFlow for PaymentRedirectSync { type PaymentFlowResponse = router_types::RedirectPaymentFlowResponse; #[allow(clippy::too_many_arguments)] async fn call_payment_flow( &self, state: &SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, req: PaymentsRedirectResponseData, connector_action: CallConnectorAction, _connector: String, _payment_id: id_type::PaymentId, ) -> RouterResult<Self::PaymentFlowResponse> { let key_manager_state = &state.into(); let payment_sync_req = api::PaymentsRetrieveRequest { resource_id: req.resource_id, merchant_id: req.merchant_id, param: req.param, force_sync: req.force_sync, connector: req.connector, merchant_connector_details: req.creds_identifier.map(|creds_id| { api::MerchantConnectorDetailsWrap { creds_identifier: creds_id, encoded_data: None, } }), client_secret: None, expand_attempts: None, expand_captures: None, all_keys_required: None, }; let response = Box::pin( payments_core::<api::PSync, api::PaymentsResponse, _, _, _, _>( state.clone(), req_state, merchant_context.clone(), None, PaymentStatus, payment_sync_req, services::api::AuthFlow::Merchant, connector_action, None, HeaderPayload::default(), ), ) .await?; let payments_response = match response { services::ApplicationResponse::Json(response) => Ok(response), services::ApplicationResponse::JsonWithHeaders((response, _)) => Ok(response), _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the response in json"), }?; let profile_id = payments_response .profile_id .as_ref() .get_required_value("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(), })?; Ok(router_types::RedirectPaymentFlowResponse { payments_response, business_profile, }) } fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, payment_id: id_type::PaymentId, connector: String, ) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>> { let payments_response = &payment_flow_response.payments_response; let redirect_response = helpers::get_handle_response_url( payment_id.clone(), &payment_flow_response.business_profile, payments_response, connector.clone(), )?; if payments_response .is_iframe_redirection_enabled .unwrap_or(false) { // html script to check if inside iframe, then send post message to parent for redirection else redirect self to return_url let html = core_utils::get_html_redirect_response_popup( redirect_response.return_url_with_query_params, )?; Ok(services::ApplicationResponse::Form(Box::new( services::RedirectionFormData { redirect_form: services::RedirectForm::Html { html_data: html }, payment_method_data: None, amount: payments_response.amount.to_string(), currency: payments_response.currency.clone(), }, ))) } else { Ok(services::ApplicationResponse::JsonForRedirection( redirect_response, )) } } fn get_payment_action(&self) -> services::PaymentAction { services::PaymentAction::PSync } } #[cfg(feature = "v2")] impl ValidateStatusForOperation for &PaymentRedirectSync { fn validate_status_for_operation( &self, intent_status: common_enums::IntentStatus, ) -> Result<(), errors::ApiErrorResponse> { match intent_status { common_enums::IntentStatus::RequiresCustomerAction => Ok(()), common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Processing | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::Expired => { Err(errors::ApiErrorResponse::PaymentUnexpectedState { current_flow: format!("{self:?}"), field_name: "status".to_string(), current_value: intent_status.to_string(), states: ["requires_customer_action".to_string()].join(", "), }) } } } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl PaymentRedirectFlow for PaymentRedirectSync { type PaymentFlowResponse = router_types::RedirectPaymentFlowResponse<PaymentStatusData<api::PSync>>; async fn call_payment_flow( &self, state: &SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, req: PaymentsRedirectResponseData, ) -> RouterResult<Self::PaymentFlowResponse> { let payment_id = req.payment_id.clone(); let payment_sync_request = api::PaymentsRetrieveRequest { param: Some(req.query_params.clone()), force_sync: true, expand_attempts: false, return_raw_connector_response: None, merchant_connector_details: None, // TODO: Implement for connectors requiring 3DS or redirection-based authentication flows. }; let operation = operations::PaymentGet; let boxed_operation: BoxedOperation< '_, api::PSync, api::PaymentsRetrieveRequest, PaymentStatusData<api::PSync>, > = Box::new(operation); let get_tracker_response = boxed_operation .to_get_tracker()? .get_trackers( state, &payment_id, &payment_sync_request, &merchant_context, &profile, &HeaderPayload::default(), ) .await?; 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.clone(); let connector = payment_attempt .connector .as_ref() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable( "connector is not set in payment attempt in finish redirection flow", )?; // This connector data is ephemeral, the call payment flow will get new connector data // with merchant account details, so the connector_id can be safely set to None here let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, connector, api::GetToken::Connector, None, )?; let call_connector_action = connector_data .connector .get_flow_type( &req.query_params, req.json_payload.clone(), self.get_payment_action(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to decide the response flow")?; let (payment_data, _, _, _, _, _) = Box::pin(payments_operation_core::<api::PSync, _, _, _, _>( state, req_state, merchant_context, &profile, operation, payment_sync_request, get_tracker_response, call_connector_action, HeaderPayload::default(), )) .await?; Ok(router_types::RedirectPaymentFlowResponse { payment_data, profile, }) } fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, ) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>> { let payment_intent = &payment_flow_response.payment_data.payment_intent; let profile = &payment_flow_response.profile; let return_url = payment_intent .return_url .as_ref() .or(profile.return_url.as_ref()) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("return url not found in payment intent and profile")? .to_owned(); let return_url = return_url .add_query_params(("id", payment_intent.id.get_string_repr())) .add_query_params(("status", &payment_intent.status.to_string())); let return_url_str = return_url.into_inner().to_string(); Ok(services::ApplicationResponse::JsonForRedirection( api::RedirectionResponse { return_url_with_query_params: return_url_str, }, )) } fn get_payment_action(&self) -> services::PaymentAction { services::PaymentAction::PSync } } #[derive(Clone, Debug)] pub struct PaymentAuthenticateCompleteAuthorize; #[cfg(feature = "v1")] #[async_trait::async_trait] impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize { type PaymentFlowResponse = router_types::AuthenticatePaymentFlowResponse; #[allow(clippy::too_many_arguments)] async fn call_payment_flow( &self, state: &SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, req: PaymentsRedirectResponseData, connector_action: CallConnectorAction, connector: String, payment_id: id_type::PaymentId, ) -> RouterResult<Self::PaymentFlowResponse> { let merchant_id = merchant_context.get_merchant_account().get_id().clone(); let key_manager_state = &state.into(); let payment_intent = state .store .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, &merchant_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_attempt = state .store .find_payment_attempt_by_attempt_id_merchant_id( &payment_intent.active_attempt.get_id(), &merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let authentication_id = payment_attempt .authentication_id .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing authentication_id in payment_attempt")?; let authentication = state .store .find_authentication_by_merchant_id_authentication_id(&merchant_id, &authentication_id) .await .to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound { id: authentication_id.get_string_repr().to_string(), })?; // Fetching merchant_connector_account to check if pull_mechanism is enabled for 3ds connector let authentication_merchant_connector_account = helpers::get_merchant_connector_account( state, &merchant_id, None, merchant_context.get_merchant_key_store(), &payment_intent .profile_id .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing profile_id in payment_intent")?, &payment_attempt .authentication_connector .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing authentication connector in payment_intent")?, None, ) .await?; let is_pull_mechanism_enabled = utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata( authentication_merchant_connector_account .get_metadata() .map(|metadata| metadata.expose()), ); let response = if is_pull_mechanism_enabled || authentication.authentication_type != Some(common_enums::DecoupledAuthenticationType::Challenge) { let payment_confirm_req = api::PaymentsRequest { payment_id: Some(req.resource_id.clone()), merchant_id: req.merchant_id.clone(), feature_metadata: Some(api_models::payments::FeatureMetadata { redirect_response: Some(api_models::payments::RedirectResponse { param: req.param.map(Secret::new), json_payload: Some( req.json_payload.unwrap_or(serde_json::json!({})).into(), ), }), search_tags: None, apple_pay_recurring_details: None, }), ..Default::default() }; Box::pin(payments_core::< api::Authorize, api::PaymentsResponse, _, _, _, _, >( state.clone(), req_state, merchant_context.clone(), None, PaymentConfirm, payment_confirm_req, services::api::AuthFlow::Merchant, connector_action, None, HeaderPayload::with_source(enums::PaymentSource::ExternalAuthenticator), )) .await? } else { let payment_sync_req = api::PaymentsRetrieveRequest { resource_id: req.resource_id, merchant_id: req.merchant_id, param: req.param, force_sync: req.force_sync, connector: req.connector, merchant_connector_details: req.creds_identifier.map(|creds_id| { api::MerchantConnectorDetailsWrap { creds_identifier: creds_id, encoded_data: None, } }), client_secret: None, expand_attempts: None, expand_captures: None, all_keys_required: None, }; Box::pin( payments_core::<api::PSync, api::PaymentsResponse, _, _, _, _>( state.clone(), req_state, merchant_context.clone(), None, PaymentStatus, payment_sync_req, services::api::AuthFlow::Merchant, connector_action, None, HeaderPayload::default(), ), ) .await? }; let payments_response = match response { services::ApplicationResponse::Json(response) => Ok(response), services::ApplicationResponse::JsonWithHeaders((response, _)) => Ok(response), _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the response in json"), }?; // When intent status is RequiresCustomerAction, Set poll_id in redis to allow the fetch status of poll through retrieve_poll_status api from client if payments_response.status == common_enums::IntentStatus::RequiresCustomerAction { let req_poll_id = core_utils::get_external_authentication_request_poll_id(&payment_id); let poll_id = core_utils::get_poll_id(&merchant_id, req_poll_id.clone()); let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; redis_conn .set_key_with_expiry( &poll_id.into(), api_models::poll::PollStatus::Pending.to_string(), consts::POLL_ID_TTL, ) .await .change_context(errors::StorageError::KVError) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add poll_id in redis")?; }; let default_poll_config = router_types::PollConfig::default(); let default_config_str = default_poll_config .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while stringifying default poll config")?; let poll_config = state .store .find_config_by_key_unwrap_or( &router_types::PollConfig::get_poll_config_key(connector), Some(default_config_str), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("The poll config was not found in the DB")?; let poll_config: router_types::PollConfig = poll_config .config .parse_struct("PollConfig") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while parsing PollConfig")?; let profile_id = payments_response .profile_id .as_ref() .get_required_value("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(), })?; Ok(router_types::AuthenticatePaymentFlowResponse { payments_response, poll_config, business_profile, }) } fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, payment_id: id_type::PaymentId, connector: String, ) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>> { let payments_response = &payment_flow_response.payments_response; let redirect_response = helpers::get_handle_response_url( payment_id.clone(), &payment_flow_response.business_profile, payments_response, connector.clone(), )?; // html script to check if inside iframe, then send post message to parent for redirection else redirect self to return_url let html = core_utils::get_html_redirect_response_for_external_authentication( redirect_response.return_url_with_query_params, payments_response, payment_id, &payment_flow_response.poll_config, )?; Ok(services::ApplicationResponse::Form(Box::new( services::RedirectionFormData { redirect_form: services::RedirectForm::Html { html_data: html }, payment_method_data: None, amount: payments_response.amount.to_string(), currency: payments_response.currency.clone(), }, ))) } fn get_payment_action(&self) -> services::PaymentAction { services::PaymentAction::PaymentAuthenticateCompleteAuthorize } } #[cfg(feature = "v1")] pub async fn get_decrypted_wallet_payment_method_token<F, Req, D>( operation: &BoxedOperation<'_, F, Req, D>, state: &SessionState, merchant_context: &domain::MerchantContext, payment_data: &mut D, connector_call_type_optional: Option<&ConnectorCallType>, ) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse> where F: Send + Clone + Sync, D: OperationSessionGetters<F> + Send + Sync + Clone, { if is_operation_confirm(operation) && payment_data.get_payment_attempt().payment_method == Some(storage_enums::PaymentMethod::Wallet) && payment_data.get_payment_method_data().is_some() { let wallet_type = payment_data .get_payment_attempt() .payment_method_type .get_required_value("payment_method_type")?; let wallet: Box<dyn WalletFlow<F, D>> = match wallet_type { storage_enums::PaymentMethodType::ApplePay => Box::new(ApplePayWallet), storage_enums::PaymentMethodType::Paze => Box::new(PazeWallet), storage_enums::PaymentMethodType::GooglePay => Box::new(GooglePayWallet), _ => return Ok(None), }; // Check if the wallet has already decrypted the token from the payment data. // If a pre-decrypted token is available, use it directly to avoid redundant decryption. if let Some(predecrypted_token) = wallet.check_predecrypted_token(payment_data)? { logger::debug!("Using predecrypted token for wallet"); return Ok(Some(predecrypted_token)); } let merchant_connector_account = get_merchant_connector_account_for_wallet_decryption_flow::<F, D>( state, merchant_context, payment_data, connector_call_type_optional, ) .await?; let decide_wallet_flow = &wallet .decide_wallet_flow(state, payment_data, &merchant_connector_account) .attach_printable("Failed to decide wallet flow")? .async_map(|payment_price_data| async move { wallet .decrypt_wallet_token(&payment_price_data, payment_data) .await }) .await .transpose() .attach_printable("Failed to decrypt Wallet token")?; Ok(decide_wallet_flow.clone()) } else { Ok(None) } } #[cfg(feature = "v1")] pub async fn get_merchant_connector_account_for_wallet_decryption_flow<F, D>( state: &SessionState, merchant_context: &domain::MerchantContext, payment_data: &mut D, connector_call_type_optional: Option<&ConnectorCallType>, ) -> RouterResult<helpers::MerchantConnectorAccountType> where F: Send + Clone + Sync, D: OperationSessionGetters<F> + Send + Sync + Clone, { let connector_call_type = connector_call_type_optional .get_required_value("connector_call_type") .change_context(errors::ApiErrorResponse::InternalServerError)?; let connector_routing_data = match connector_call_type { ConnectorCallType::PreDetermined(connector_routing_data) => connector_routing_data, ConnectorCallType::Retryable(connector_routing_data) => connector_routing_data .first() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Found no connector routing data in retryable call")?, ConnectorCallType::SessionMultiple(_session_connector_data) => { return Err(errors::ApiErrorResponse::InternalServerError).attach_printable( "SessionMultiple connector call type is invalid in confirm calls", ); } }; construct_profile_id_and_get_mca( state, merchant_context, payment_data, &connector_routing_data .connector_data .connector_name .to_string(), connector_routing_data .connector_data .merchant_connector_id .as_ref(), false, ) .await } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>( state: &SessionState, req_state: ReqState, merchant_context: &domain::MerchantContext, connector: api::ConnectorData, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, customer: &Option<domain::Customer>, call_connector_action: CallConnectorAction, validate_result: &operations::ValidateResult, schedule_time: Option<time::PrimitiveDateTime>, header_payload: HeaderPayload, frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &domain::Profile, is_retry_payment: bool, return_raw_connector_response: Option<bool>, merchant_connector_account: helpers::MerchantConnectorAccountType, mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>, tokenization_action: TokenizationAction, ) -> RouterResult<( RouterData<F, RouterDReq, router_types::PaymentsResponseData>, helpers::MerchantConnectorAccountType, )> where F: Send + Clone + Sync, RouterDReq: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData> + Send + Sync, { let add_access_token_result = router_data .add_access_token( state, &connector, merchant_context, payment_data.get_creds_identifier(), ) .await?; router_data = router_data.add_session_token(state, &connector).await?; let should_continue_further = access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &call_connector_action, ); let should_continue_further = match router_data .create_order_at_connector(state, &connector, should_continue_further) .await? { Some(create_order_response) => { if let Ok(order_id) = create_order_response.clone().create_order_result { payment_data.set_connector_response_reference_id(Some(order_id.clone())) } // Set the response in routerdata response to carry forward router_data .update_router_data_with_create_order_response(create_order_response.clone()); create_order_response.create_order_result.ok().is_some() } // If create order is not required, then we can proceed with further processing None => true, }; let updated_customer = call_create_connector_customer_if_required( state, customer, merchant_context, &merchant_connector_account, payment_data, router_data.access_token.as_ref(), ) .await?; #[cfg(feature = "v1")] if let Some(connector_customer_id) = payment_data.get_connector_customer_id() { router_data.connector_customer = Some(connector_customer_id); } router_data.payment_method_token = payment_data.get_payment_method_token().cloned(); let payment_method_token_response = router_data .add_payment_method_token( state, &connector, &tokenization_action, should_continue_further, ) .await?; let mut should_continue_further = tokenization::update_router_data_with_payment_method_token_result( payment_method_token_response, &mut router_data, is_retry_payment, should_continue_further, ); (router_data, should_continue_further) = complete_preprocessing_steps_if_required( state, &connector, payment_data, router_data, operation, should_continue_further, ) .await?; if let Ok(router_types::PaymentsResponseData::PreProcessingResponse { session_token: Some(session_token), .. }) = router_data.response.to_owned() { payment_data.push_sessions_token(session_token); }; // In case of authorize flow, pre-task and post-tasks are being called in build request // if we do not want to proceed further, then the function will return Ok(None, false) let (connector_request, should_continue_further) = if should_continue_further { // Check if the actual flow specific request can be built with available data router_data .build_flow_specific_connector_request(state, &connector, call_connector_action.clone()) .await? } else { (None, false) }; if should_add_task_to_process_tracker(payment_data) { operation .to_domain()? .add_task_to_process_tracker( state, payment_data.get_payment_attempt(), validate_result.requeue, schedule_time, ) .await .map_err(|error| logger::error!(process_tracker_error=?error)) .ok(); } // Update the payment trackers just before calling the connector // Since the request is already built in the previous step, // there should be no error in request construction from hyperswitch end (_, *payment_data) = operation .to_update_tracker()? .update_trackers( state, req_state, payment_data.clone(), customer.clone(), merchant_context.get_merchant_account().storage_scheme, updated_customer, merchant_context.get_merchant_key_store(), frm_suggestion, header_payload.clone(), ) .await?; let router_data = if should_continue_further { // The status of payment_attempt and intent will be updated in the previous step // update this in router_data. // This is added because few connector integrations do not update the status, // and rely on previous status set in router_data router_data.status = payment_data.get_payment_attempt().status; router_data .decide_flows( state, &connector, call_connector_action, connector_request, business_profile, header_payload.clone(), return_raw_connector_response, ) .await } else { Ok(router_data) }?; Ok((router_data, merchant_connector_account)) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn call_connector_service_prerequisites<F, RouterDReq, ApiRequest, D>( state: &SessionState, merchant_context: &domain::MerchantContext, connector: api::ConnectorData, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, customer: &Option<domain::Customer>, validate_result: &operations::ValidateResult, business_profile: &domain::Profile, should_retry_with_pan: bool, routing_decision: Option<routing_helpers::RoutingDecisionData>, ) -> RouterResult<( helpers::MerchantConnectorAccountType, RouterData<F, RouterDReq, router_types::PaymentsResponseData>, TokenizationAction, )> where F: Send + Clone + Sync, RouterDReq: Send + Clone + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send + Clone, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { let merchant_connector_account = construct_profile_id_and_get_mca( state, merchant_context, payment_data, &connector.connector_name.to_string(), connector.merchant_connector_id.as_ref(), false, ) .await?; let customer_acceptance = payment_data .get_payment_attempt() .customer_acceptance .clone(); if is_pre_network_tokenization_enabled( state, business_profile, customer_acceptance, connector.connector_name, ) { let payment_method_data = payment_data.get_payment_method_data(); let customer_id = payment_data.get_payment_intent().customer_id.clone(); if let (Some(domain::PaymentMethodData::Card(card_data)), Some(customer_id)) = (payment_method_data, customer_id) { let vault_operation = get_vault_operation_for_pre_network_tokenization(state, customer_id, card_data) .await; match vault_operation { payments::VaultOperation::SaveCardAndNetworkTokenData( card_and_network_token_data, ) => { payment_data.set_vault_operation( payments::VaultOperation::SaveCardAndNetworkTokenData(Box::new( *card_and_network_token_data.clone(), )), ); payment_data.set_payment_method_data(Some( domain::PaymentMethodData::NetworkToken( card_and_network_token_data .network_token .network_token_data .clone(), ), )); } payments::VaultOperation::SaveCardData(card_data_for_vault) => payment_data .set_vault_operation(payments::VaultOperation::SaveCardData( card_data_for_vault.clone(), )), payments::VaultOperation::ExistingVaultData(_) => (), } } } if payment_data .get_payment_attempt() .merchant_connector_id .is_none() { payment_data.set_merchant_connector_id_in_attempt(merchant_connector_account.get_mca_id()); } operation .to_domain()? .populate_payment_data( state, payment_data, merchant_context, business_profile, &connector, ) .await?; let (pd, tokenization_action) = get_connector_tokenization_action_when_confirm_true( state, operation, payment_data, validate_result, merchant_context.get_merchant_key_store(), customer, business_profile, should_retry_with_pan, ) .await?; *payment_data = pd; // This is used to apply any kind of routing decision to the required data, // before the call to `connector` is made. routing_decision.map(|decision| decision.apply_routing_decision(payment_data)); // Validating the blocklist guard and generate the fingerprint blocklist_guard(state, merchant_context, operation, payment_data).await?; let merchant_recipient_data = payment_data .get_merchant_recipient_data( state, merchant_context, &merchant_connector_account, &connector, ) .await?; let router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_context, customer, &merchant_connector_account, merchant_recipient_data, None, payment_data.get_payment_attempt().payment_method, payment_data.get_payment_attempt().payment_method_type, ) .await?; let connector_request_reference_id = router_data.connector_request_reference_id.clone(); payment_data .set_connector_request_reference_id_in_payment_attempt(connector_request_reference_id); Ok((merchant_connector_account, router_data, tokenization_action)) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn decide_unified_connector_service_call<'a, F, RouterDReq, ApiRequest, D>( state: &'a SessionState, req_state: ReqState, merchant_context: &'a domain::MerchantContext, connector: api::ConnectorData, operation: &'a BoxedOperation<'a, F, ApiRequest, D>, payment_data: &'a mut D, customer: &Option<domain::Customer>, call_connector_action: CallConnectorAction, validate_result: &'a operations::ValidateResult, schedule_time: Option<time::PrimitiveDateTime>, header_payload: HeaderPayload, frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &'a domain::Profile, is_retry_payment: bool, all_keys_required: Option<bool>, merchant_connector_account: helpers::MerchantConnectorAccountType, router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>, tokenization_action: TokenizationAction, ) -> RouterResult<( RouterData<F, RouterDReq, router_types::PaymentsResponseData>, helpers::MerchantConnectorAccountType, )> where F: Send + Clone + Sync + 'static, RouterDReq: Send + Sync + Clone + 'static + serde::Serialize, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send + Clone + serde::Serialize, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { let execution_path = should_call_unified_connector_service( state, merchant_context, &router_data, Some(payment_data), ) .await?; let is_handle_response_action = matches!( call_connector_action, CallConnectorAction::UCSHandleResponse(_) | CallConnectorAction::HandleResponse(_) ); record_time_taken_with(|| async { match (execution_path, is_handle_response_action) { // Process through UCS when system is UCS and not handling response (ExecutionPath::UnifiedConnectorService, false) => { process_through_ucs( state, req_state, merchant_context, operation, payment_data, customer, validate_result, schedule_time, header_payload, frm_suggestion, business_profile, merchant_connector_account, router_data, ) .await } // Process through Direct with Shadow UCS (ExecutionPath::ShadowUnifiedConnectorService, false) => { process_through_direct_with_shadow_unified_connector_service( state, req_state, merchant_context, connector, operation, payment_data, customer, call_connector_action, validate_result, schedule_time, header_payload, frm_suggestion, business_profile, is_retry_payment, all_keys_required, merchant_connector_account, router_data, tokenization_action, ) .await } // Process through Direct gateway (ExecutionPath::Direct, _) | (ExecutionPath::UnifiedConnectorService, true) | (ExecutionPath::ShadowUnifiedConnectorService, true) => { process_through_direct( state, req_state, merchant_context, connector, operation, payment_data, customer, call_connector_action, validate_result, schedule_time, header_payload, frm_suggestion, business_profile, is_retry_payment, all_keys_required, merchant_connector_account, router_data, tokenization_action, ) .await } } }) .await } async fn record_time_taken_with<F, Fut, R>(f: F) -> RouterResult<R> where F: FnOnce() -> Fut, Fut: future::Future<Output = RouterResult<R>>, { let stime = Instant::now(); let result = f().await; let etime = Instant::now(); let duration = etime.saturating_duration_since(stime); tracing::info!(duration = format!("Duration taken: {}", duration.as_millis())); result } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>( state: &SessionState, req_state: ReqState, merchant_context: &domain::MerchantContext, connector: api::ConnectorData, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, customer: &Option<domain::Customer>, call_connector_action: CallConnectorAction, schedule_time: Option<time::PrimitiveDateTime>, header_payload: HeaderPayload, frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &domain::Profile, is_retry_payment: bool, should_retry_with_pan: bool, return_raw_connector_response: Option<bool>, merchant_connector_account_type_details: domain::MerchantConnectorAccountTypeDetails, mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>, updated_customer: Option<storage::CustomerUpdate>, tokenization_action: TokenizationAction, ) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, RouterDReq: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { let add_access_token_result = router_data .add_access_token( state, &connector, merchant_context, payment_data.get_creds_identifier(), ) .await?; router_data = router_data.add_session_token(state, &connector).await?; let should_continue_further = access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &call_connector_action, ); let payment_method_token_response = router_data .add_payment_method_token( state, &connector, &tokenization_action, should_continue_further, ) .await?; let should_continue_further = tokenization::update_router_data_with_payment_method_token_result( payment_method_token_response, &mut router_data, is_retry_payment, should_continue_further, ); let should_continue = match router_data .create_order_at_connector(state, &connector, should_continue_further) .await? { Some(create_order_response) => { if let Ok(order_id) = create_order_response.clone().create_order_result { payment_data.set_connector_response_reference_id(Some(order_id)) } // Set the response in routerdata response to carry forward router_data .update_router_data_with_create_order_response(create_order_response.clone()); create_order_response.create_order_result.ok().map(|_| ()) } // If create order is not required, then we can proceed with further processing None => Some(()), }; // In case of authorize flow, pre-task and post-tasks are being called in build request // if we do not want to proceed further, then the function will return Ok(None, false) let (connector_request, should_continue_further) = match should_continue { Some(_) => { router_data .build_flow_specific_connector_request( state, &connector, call_connector_action.clone(), ) .await? } None => (None, false), }; // Update the payment trackers just before calling the connector // Since the request is already built in the previous step, // there should be no error in request construction from hyperswitch end (_, *payment_data) = operation .to_update_tracker()? .update_trackers( state, req_state, payment_data.clone(), customer.clone(), merchant_context.get_merchant_account().storage_scheme, updated_customer, merchant_context.get_merchant_key_store(), frm_suggestion, header_payload.clone(), ) .await?; let router_data = if should_continue_further { // The status of payment_attempt and intent will be updated in the previous step // update this in router_data. // This is added because few connector integrations do not update the status, // and rely on previous status set in router_data // TODO: status is already set when constructing payment data, why should this be done again? // router_data.status = payment_data.get_payment_attempt().status; router_data .decide_flows( state, &connector, call_connector_action, connector_request, business_profile, header_payload.clone(), return_raw_connector_response, ) .await } else { Ok(router_data) }?; Ok(router_data) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] #[allow(clippy::type_complexity)] #[instrument(skip_all)] pub async fn call_connector_service_prerequisites<F, RouterDReq, ApiRequest, D>( state: &SessionState, req_state: ReqState, merchant_context: &domain::MerchantContext, connector: api::ConnectorData, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, customer: &Option<domain::Customer>, call_connector_action: CallConnectorAction, schedule_time: Option<time::PrimitiveDateTime>, header_payload: HeaderPayload, frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &domain::Profile, is_retry_payment: bool, should_retry_with_pan: bool, all_keys_required: Option<bool>, ) -> RouterResult<( domain::MerchantConnectorAccountTypeDetails, Option<storage::CustomerUpdate>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>, TokenizationAction, )> where F: Send + Clone + Sync, RouterDReq: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { let merchant_connector_account_type_details = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new( helpers::get_merchant_connector_account_v2( state, merchant_context.get_merchant_key_store(), connector.merchant_connector_id.as_ref(), ) .await?, )); operation .to_domain()? .populate_payment_data( state, payment_data, merchant_context, business_profile, &connector, ) .await?; let updated_customer = call_create_connector_customer_if_required( state, customer, merchant_context, &merchant_connector_account_type_details, payment_data, ) .await?; let router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_context, customer, &merchant_connector_account_type_details, None, Some(header_payload), ) .await?; let tokenization_action = operation .to_domain()? .get_connector_tokenization_action(state, payment_data) .await?; Ok(( merchant_connector_account_type_details, updated_customer, router_data, tokenization_action, )) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] #[allow(clippy::type_complexity)] #[instrument(skip_all)] pub async fn call_connector_service_prerequisites_for_external_vault_proxy< F, RouterDReq, ApiRequest, D, >( state: &SessionState, req_state: ReqState, merchant_context: &domain::MerchantContext, connector: api::ConnectorData, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, customer: &Option<domain::Customer>, call_connector_action: CallConnectorAction, schedule_time: Option<time::PrimitiveDateTime>, header_payload: HeaderPayload, frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &domain::Profile, is_retry_payment: bool, should_retry_with_pan: bool, all_keys_required: Option<bool>, ) -> RouterResult<( domain::MerchantConnectorAccountTypeDetails, domain::MerchantConnectorAccountTypeDetails, Option<storage::CustomerUpdate>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>, )> where F: Send + Clone + Sync, RouterDReq: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { // get merchant connector account related to external vault let external_vault_source: id_type::MerchantConnectorAccountId = business_profile .external_vault_connector_details .clone() .map(|connector_details| connector_details.vault_connector_id.clone()) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("mca_id not present for external vault")?; let external_vault_merchant_connector_account_type_details = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new( helpers::get_merchant_connector_account_v2( state, merchant_context.get_merchant_key_store(), Some(&external_vault_source), ) .await?, )); let ( merchant_connector_account_type_details, updated_customer, router_data, _tokenization_action, ) = call_connector_service_prerequisites( state, req_state, merchant_context, connector, operation, payment_data, customer, call_connector_action, schedule_time, header_payload, frm_suggestion, business_profile, is_retry_payment, should_retry_with_pan, all_keys_required, ) .await?; Ok(( merchant_connector_account_type_details, external_vault_merchant_connector_account_type_details, updated_customer, router_data, )) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn internal_call_connector_service_prerequisites<F, RouterDReq, ApiRequest, D>( state: &SessionState, merchant_context: &domain::MerchantContext, connector: api::ConnectorData, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, business_profile: &domain::Profile, ) -> RouterResult<( domain::MerchantConnectorAccountTypeDetails, RouterData<F, RouterDReq, router_types::PaymentsResponseData>, )> where F: Send + Clone + Sync, RouterDReq: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { let merchant_connector_details = payment_data .get_merchant_connector_details() .ok_or_else(|| { error_stack::report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Merchant connector details not found in payment data") })?; let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails( merchant_connector_details, ); operation .to_domain()? .populate_payment_data( state, payment_data, merchant_context, business_profile, &connector, ) .await?; let router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_context, &None, &merchant_connector_account, None, None, ) .await?; Ok((merchant_connector_account, router_data)) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn connector_service_decider<F, RouterDReq, ApiRequest, D>( state: &SessionState, req_state: ReqState, merchant_context: &domain::MerchantContext, connector: api::ConnectorData, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, business_profile: &domain::Profile, return_raw_connector_response: Option<bool>, merchant_connector_account_type_details: domain::MerchantConnectorAccountTypeDetails, ) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, RouterDReq: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { let mut router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_context, &None, &merchant_connector_account_type_details, None, Some(header_payload.clone()), ) .await?; // do order creation let execution_path = should_call_unified_connector_service( state, merchant_context, &router_data, Some(payment_data), ) .await?; let (connector_request, should_continue_further) = if matches!(execution_path, ExecutionPath::Direct) { let mut should_continue_further = true; let should_continue = match router_data .create_order_at_connector(state, &connector, should_continue_further) .await? { Some(create_order_response) => { if let Ok(order_id) = create_order_response.clone().create_order_result { payment_data.set_connector_response_reference_id(Some(order_id)) } // Set the response in routerdata response to carry forward router_data.update_router_data_with_create_order_response( create_order_response.clone(), ); create_order_response.create_order_result.ok().map(|_| ()) } // If create order is not required, then we can proceed with further processing None => Some(()), }; let should_continue: (Option<common_utils::request::Request>, bool) = match should_continue { Some(_) => { router_data .build_flow_specific_connector_request( state, &connector, call_connector_action.clone(), ) .await? } None => (None, false), }; should_continue } else { // If unified connector service is called, these values are not used // as the request is built in the unified connector service call (None, false) }; (_, *payment_data) = operation .to_update_tracker()? .update_trackers( state, req_state, payment_data.clone(), None, // customer is not used in internal flows merchant_context.get_merchant_account().storage_scheme, None, merchant_context.get_merchant_key_store(), None, // frm_suggestion is not used in internal flows header_payload.clone(), ) .await?; record_time_taken_with(|| async { if matches!(execution_path, ExecutionPath::UnifiedConnectorService) { router_env::logger::info!( "Processing payment through UCS gateway system- payment_id={}, attempt_id={}", payment_data.get_payment_intent().id.get_string_repr(), payment_data.get_payment_attempt().id.get_string_repr() ); let lineage_ids = grpc_client::LineageIds::new(business_profile.merchant_id.clone(), business_profile.get_id().clone()); router_data .call_unified_connector_service( state, &header_payload, lineage_ids, merchant_connector_account_type_details.clone(), merchant_context, ExecutionMode::Primary, // UCS is called in primary mode ) .await?; Ok(router_data) } else { Err( errors::ApiErrorResponse::InternalServerError ) .attach_printable("Unified connector service is down and traditional connector service fallback is not implemented") } }) .await } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn decide_unified_connector_service_call<F, RouterDReq, ApiRequest, D>( state: &SessionState, req_state: ReqState, merchant_context: &domain::MerchantContext, connector: api::ConnectorData, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, customer: &Option<domain::Customer>, call_connector_action: CallConnectorAction, schedule_time: Option<time::PrimitiveDateTime>, header_payload: HeaderPayload, frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &domain::Profile, is_retry_payment: bool, should_retry_with_pan: bool, return_raw_connector_response: Option<bool>, merchant_connector_account_type_details: domain::MerchantConnectorAccountTypeDetails, mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>, updated_customer: Option<storage::CustomerUpdate>, tokenization_action: TokenizationAction, ) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, RouterDReq: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { record_time_taken_with(|| async { let execution_path = should_call_unified_connector_service( state, merchant_context, &router_data, Some(payment_data), ) .await?; if matches!(execution_path, ExecutionPath::UnifiedConnectorService) { router_env::logger::info!( "Executing payment through UCS gateway system - payment_id={}, attempt_id={}", payment_data.get_payment_intent().id.get_string_repr(), payment_data.get_payment_attempt().id.get_string_repr() ); if should_add_task_to_process_tracker(payment_data) { operation .to_domain()? .add_task_to_process_tracker( state, payment_data.get_payment_attempt(), false, schedule_time, ) .await .map_err(|error| logger::error!(process_tracker_error=?error)) .ok(); } (_, *payment_data) = operation .to_update_tracker()? .update_trackers( state, req_state, payment_data.clone(), customer.clone(), merchant_context.get_merchant_account().storage_scheme, None, merchant_context.get_merchant_key_store(), frm_suggestion, header_payload.clone(), ) .await?; let lineage_ids = grpc_client::LineageIds::new( business_profile.merchant_id.clone(), business_profile.get_id().clone(), ); router_data .call_unified_connector_service( state, &header_payload, lineage_ids, merchant_connector_account_type_details.clone(), merchant_context, ExecutionMode::Primary, //UCS is called in primary mode ) .await?; Ok(router_data) } else { if matches!(execution_path, ExecutionPath::ShadowUnifiedConnectorService) { router_env::logger::info!( "Shadow UCS mode not implemented in v2, processing through direct path - payment_id={}, attempt_id={}", payment_data.get_payment_intent().id.get_string_repr(), payment_data.get_payment_attempt().id.get_string_repr() ); } else { router_env::logger::info!( "Processing payment through Direct gateway system - payment_id={}, attempt_id={}", payment_data.get_payment_intent().id.get_string_repr(), payment_data.get_payment_attempt().id.get_string_repr() ); } call_connector_service( state, req_state, merchant_context, connector, operation, payment_data, customer, call_connector_action, schedule_time, header_payload, frm_suggestion, business_profile, is_retry_payment, should_retry_with_pan, return_raw_connector_response, merchant_connector_account_type_details, router_data, updated_customer, tokenization_action, ) .await } }) .await } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn call_unified_connector_service_for_external_proxy<F, RouterDReq, ApiRequest, D>( state: &SessionState, req_state: ReqState, merchant_context: &domain::MerchantContext, _connector: api::ConnectorData, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, customer: &Option<domain::Customer>, _call_connector_action: CallConnectorAction, _schedule_time: Option<time::PrimitiveDateTime>, header_payload: HeaderPayload, frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &domain::Profile, _is_retry_payment: bool, _should_retry_with_pan: bool, _return_raw_connector_response: Option<bool>, merchant_connector_account_type_details: domain::MerchantConnectorAccountTypeDetails, external_vault_merchant_connector_account_type_details: domain::MerchantConnectorAccountTypeDetails, mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>, _updated_customer: Option<storage::CustomerUpdate>, ) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, RouterDReq: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { record_time_taken_with(|| async { (_, *payment_data) = operation .to_update_tracker()? .update_trackers( state, req_state, payment_data.clone(), customer.clone(), merchant_context.get_merchant_account().storage_scheme, None, merchant_context.get_merchant_key_store(), frm_suggestion, header_payload.clone(), ) .await?; let lineage_ids = grpc_client::LineageIds::new( business_profile.merchant_id.clone(), business_profile.get_id().clone(), ); router_data .call_unified_connector_service_with_external_vault_proxy( state, &header_payload, lineage_ids, merchant_connector_account_type_details.clone(), external_vault_merchant_connector_account_type_details.clone(), merchant_context, ExecutionMode::Primary, //UCS is called in primary mode ) .await?; Ok(router_data) }) .await } #[cfg(feature = "v1")] // This function does not perform the tokenization action, as the payment method is not saved in this flow. #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn proxy_for_call_connector_service<F, RouterDReq, ApiRequest, D>( state: &SessionState, req_state: ReqState, merchant_context: &domain::MerchantContext, connector: api::ConnectorData, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, customer: &Option<domain::Customer>, call_connector_action: CallConnectorAction, validate_result: &operations::ValidateResult, schedule_time: Option<time::PrimitiveDateTime>, header_payload: HeaderPayload, business_profile: &domain::Profile, return_raw_connector_response: Option<bool>, ) -> RouterResult<( RouterData<F, RouterDReq, router_types::PaymentsResponseData>, helpers::MerchantConnectorAccountType, )> where F: Send + Clone + Sync, RouterDReq: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { let stime_connector = Instant::now(); let merchant_connector_account = construct_profile_id_and_get_mca( state, merchant_context, payment_data, &connector.connector_name.to_string(), connector.merchant_connector_id.as_ref(), false, ) .await?; if payment_data .get_payment_attempt() .merchant_connector_id .is_none() { payment_data.set_merchant_connector_id_in_attempt(merchant_connector_account.get_mca_id()); } let merchant_recipient_data = None; let mut router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_context, customer, &merchant_connector_account, merchant_recipient_data, Some(header_payload.clone()), payment_data.get_payment_attempt().payment_method, payment_data.get_payment_attempt().payment_method_type, ) .await?; let add_access_token_result = router_data .add_access_token( state, &connector, merchant_context, payment_data.get_creds_identifier(), ) .await?; router_data = router_data.add_session_token(state, &connector).await?; let mut should_continue_further = access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &call_connector_action, ); (router_data, should_continue_further) = complete_preprocessing_steps_if_required( state, &connector, payment_data, router_data, operation, should_continue_further, ) .await?; if let Ok(router_types::PaymentsResponseData::PreProcessingResponse { session_token: Some(session_token), .. }) = router_data.response.to_owned() { payment_data.push_sessions_token(session_token); }; let (connector_request, should_continue_further) = if should_continue_further { // Check if the actual flow specific request can be built with available data router_data .build_flow_specific_connector_request(state, &connector, call_connector_action.clone()) .await? } else { (None, false) }; if should_add_task_to_process_tracker(payment_data) { operation .to_domain()? .add_task_to_process_tracker( state, payment_data.get_payment_attempt(), validate_result.requeue, schedule_time, ) .await .map_err(|error| logger::error!(process_tracker_error=?error)) .ok(); } let updated_customer = None; let frm_suggestion = None; (_, *payment_data) = operation .to_update_tracker()? .update_trackers( state, req_state, payment_data.clone(), customer.clone(), merchant_context.get_merchant_account().storage_scheme, updated_customer, merchant_context.get_merchant_key_store(), frm_suggestion, header_payload.clone(), ) .await?; let router_data = if should_continue_further { // The status of payment_attempt and intent will be updated in the previous step // update this in router_data. // This is added because few connector integrations do not update the status, // and rely on previous status set in router_data router_data.status = payment_data.get_payment_attempt().status; router_data .decide_flows( state, &connector, call_connector_action, connector_request, business_profile, header_payload.clone(), return_raw_connector_response, ) .await } else { Ok(router_data) }?; let etime_connector = Instant::now(); let duration_connector = etime_connector.saturating_duration_since(stime_connector); tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis())); Ok((router_data, merchant_connector_account)) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn proxy_for_call_connector_service<F, RouterDReq, ApiRequest, D>( state: &SessionState, req_state: ReqState, merchant_context: &domain::MerchantContext, connector: api::ConnectorData, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, business_profile: &domain::Profile, return_raw_connector_response: Option<bool>, ) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, RouterDReq: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { let stime_connector = Instant::now(); let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new( helpers::get_merchant_connector_account_v2( state, merchant_context.get_merchant_key_store(), connector.merchant_connector_id.as_ref(), ) .await?, )); operation .to_domain()? .populate_payment_data( state, payment_data, merchant_context, business_profile, &connector, ) .await?; let mut router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_context, &None, &merchant_connector_account, None, Some(header_payload.clone()), ) .await?; let add_access_token_result = router_data .add_access_token( state, &connector, merchant_context, payment_data.get_creds_identifier(), ) .await?; router_data = router_data.add_session_token(state, &connector).await?; let mut should_continue_further = access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &call_connector_action, ); let (connector_request, should_continue_further) = if should_continue_further { router_data .build_flow_specific_connector_request(state, &connector, call_connector_action.clone()) .await? } else { (None, false) }; (_, *payment_data) = operation .to_update_tracker()? .update_trackers( state, req_state, payment_data.clone(), None, merchant_context.get_merchant_account().storage_scheme, None, merchant_context.get_merchant_key_store(), None, header_payload.clone(), ) .await?; let router_data = if should_continue_further { router_data .decide_flows( state, &connector, call_connector_action, connector_request, business_profile, header_payload.clone(), return_raw_connector_response, ) .await } else { Ok(router_data) }?; let etime_connector = Instant::now(); let duration_connector = etime_connector.saturating_duration_since(stime_connector); tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis())); Ok(router_data) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn call_connector_service_for_external_vault_proxy<F, RouterDReq, ApiRequest, D>( state: &SessionState, req_state: ReqState, merchant_context: &domain::MerchantContext, connector: api::ConnectorData, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, business_profile: &domain::Profile, return_raw_connector_response: Option<bool>, ) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, RouterDReq: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { let stime_connector = Instant::now(); let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new( helpers::get_merchant_connector_account_v2( state, merchant_context.get_merchant_key_store(), connector.merchant_connector_id.as_ref(), ) .await?, )); operation .to_domain()? .populate_payment_data( state, payment_data, merchant_context, business_profile, &connector, ) .await?; let mut router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_context, &None, &merchant_connector_account, None, Some(header_payload.clone()), ) .await?; // let add_access_token_result = router_data // .add_access_token( // state, // &connector, // merchant_context, // payment_data.get_creds_identifier(), // ) // .await?; // router_data = router_data.add_session_token(state, &connector).await?; // let mut should_continue_further = access_token::update_router_data_with_access_token_result( // &add_access_token_result, // &mut router_data, // &call_connector_action, // ); let should_continue_further = true; let (connector_request, should_continue_further) = if should_continue_further { router_data .build_flow_specific_connector_request(state, &connector, call_connector_action.clone()) .await? } else { (None, false) }; (_, *payment_data) = operation .to_update_tracker()? .update_trackers( state, req_state, payment_data.clone(), None, merchant_context.get_merchant_account().storage_scheme, None, merchant_context.get_merchant_key_store(), None, header_payload.clone(), ) .await?; let router_data = if should_continue_further { router_data .decide_flows( state, &connector, call_connector_action, connector_request, business_profile, header_payload.clone(), return_raw_connector_response, ) .await } else { Ok(router_data) }?; let etime_connector = Instant::now(); let duration_connector = etime_connector.saturating_duration_since(stime_connector); tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis())); Ok(router_data) } struct ApplePayWallet; struct PazeWallet; struct GooglePayWallet; #[async_trait::async_trait] pub trait WalletFlow<F, D>: Send + Sync where F: Send + Clone, D: OperationSessionGetters<F> + Send + Sync + Clone, { /// Check if wallet data is already decrypted and return token if so fn check_predecrypted_token( &self, _payment_data: &D, ) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse> { // Default implementation returns None (no pre-decrypted data) Ok(None) } fn decide_wallet_flow( &self, state: &SessionState, payment_data: &D, merchant_connector_account: &helpers::MerchantConnectorAccountType, ) -> CustomResult<Option<DecideWalletFlow>, errors::ApiErrorResponse>; async fn decrypt_wallet_token( &self, wallet_flow: &DecideWalletFlow, payment_data: &D, ) -> CustomResult<PaymentMethodToken, errors::ApiErrorResponse>; } #[async_trait::async_trait] impl<F, D> WalletFlow<F, D> for PazeWallet where F: Send + Clone, D: OperationSessionGetters<F> + Send + Sync + Clone, { fn decide_wallet_flow( &self, state: &SessionState, _payment_data: &D, _merchant_connector_account: &helpers::MerchantConnectorAccountType, ) -> CustomResult<Option<DecideWalletFlow>, errors::ApiErrorResponse> { let paze_keys = state .conf .paze_decrypt_keys .as_ref() .get_required_value("Paze decrypt keys") .attach_printable("Paze decrypt keys not found in the configuration")?; let wallet_flow = DecideWalletFlow::PazeDecrypt(PazePaymentProcessingDetails { paze_private_key: paze_keys.get_inner().paze_private_key.clone(), paze_private_key_passphrase: paze_keys.get_inner().paze_private_key_passphrase.clone(), }); Ok(Some(wallet_flow)) } async fn decrypt_wallet_token( &self, wallet_flow: &DecideWalletFlow, payment_data: &D, ) -> CustomResult<PaymentMethodToken, errors::ApiErrorResponse> { let paze_payment_processing_details = wallet_flow .get_paze_payment_processing_details() .get_required_value("Paze payment processing details") .attach_printable( "Paze payment processing details not found in Paze decryption flow", )?; let paze_wallet_data = payment_data .get_payment_method_data() .and_then(|payment_method_data| payment_method_data.get_wallet_data()) .and_then(|wallet_data| wallet_data.get_paze_wallet_data()) .get_required_value("Paze wallet token").attach_printable( "Paze wallet data not found in the payment method data during the Paze decryption flow", )?; let paze_data = decrypt_paze_token( paze_wallet_data.clone(), paze_payment_processing_details.paze_private_key.clone(), paze_payment_processing_details .paze_private_key_passphrase .clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to decrypt paze token")?; let paze_decrypted_data = paze_data .parse_value::<hyperswitch_domain_models::router_data::PazeDecryptedData>( "PazeDecryptedData", ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to parse PazeDecryptedData")?; Ok(PaymentMethodToken::PazeDecrypt(Box::new( paze_decrypted_data, ))) } } #[async_trait::async_trait] impl<F, D> WalletFlow<F, D> for ApplePayWallet where F: Send + Clone, D: OperationSessionGetters<F> + Send + Sync + Clone, { fn check_predecrypted_token( &self, payment_data: &D, ) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse> { let apple_pay_wallet_data = payment_data .get_payment_method_data() .and_then(|payment_method_data| payment_method_data.get_wallet_data()) .and_then(|wallet_data| wallet_data.get_apple_pay_wallet_data()); let result = if let Some(data) = apple_pay_wallet_data { match &data.payment_data { common_payments_types::ApplePayPaymentData::Encrypted(_) => None, common_payments_types::ApplePayPaymentData::Decrypted( apple_pay_predecrypt_data, ) => { helpers::validate_card_expiry( &apple_pay_predecrypt_data.application_expiration_month, &apple_pay_predecrypt_data.application_expiration_year, )?; Some(PaymentMethodToken::ApplePayDecrypt(Box::new( apple_pay_predecrypt_data.clone(), ))) } } } else { None }; Ok(result) } fn decide_wallet_flow( &self, state: &SessionState, payment_data: &D, merchant_connector_account: &helpers::MerchantConnectorAccountType, ) -> CustomResult<Option<DecideWalletFlow>, errors::ApiErrorResponse> { let apple_pay_metadata = check_apple_pay_metadata(state, Some(merchant_connector_account)); add_apple_pay_flow_metrics( &apple_pay_metadata, payment_data.get_payment_attempt().connector.clone(), payment_data.get_payment_attempt().merchant_id.clone(), ); let wallet_flow = match apple_pay_metadata { Some(domain::ApplePayFlow::Simplified(payment_processing_details)) => Some( DecideWalletFlow::ApplePayDecrypt(payment_processing_details), ), Some(domain::ApplePayFlow::Manual) | None => None, }; Ok(wallet_flow) } async fn decrypt_wallet_token( &self, wallet_flow: &DecideWalletFlow, payment_data: &D, ) -> CustomResult<PaymentMethodToken, errors::ApiErrorResponse> { let apple_pay_payment_processing_details = wallet_flow .get_apple_pay_payment_processing_details() .get_required_value("Apple Pay payment processing details") .attach_printable( "Apple Pay payment processing details not found in Apple Pay decryption flow", )?; let apple_pay_wallet_data = payment_data .get_payment_method_data() .and_then(|payment_method_data| payment_method_data.get_wallet_data()) .and_then(|wallet_data| wallet_data.get_apple_pay_wallet_data()) .get_required_value("Apple Pay wallet token").attach_printable( "Apple Pay wallet data not found in the payment method data during the Apple Pay decryption flow", )?; let apple_pay_data = ApplePayData::token_json(domain::WalletData::ApplePay(apple_pay_wallet_data.clone())) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to parse apple pay token to json")? .decrypt( &apple_pay_payment_processing_details.payment_processing_certificate, &apple_pay_payment_processing_details.payment_processing_certificate_key, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to decrypt apple pay token")?; let apple_pay_predecrypt_internal = apple_pay_data .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptDataInternal>( "ApplePayPredecryptDataInternal", ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "failed to parse decrypted apple pay response to ApplePayPredecryptData", )?; let apple_pay_predecrypt = common_types::payments::ApplePayPredecryptData::try_from(apple_pay_predecrypt_internal) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "failed to convert ApplePayPredecryptDataInternal to ApplePayPredecryptData", )?; Ok(PaymentMethodToken::ApplePayDecrypt(Box::new( apple_pay_predecrypt, ))) } } #[async_trait::async_trait] impl<F, D> WalletFlow<F, D> for GooglePayWallet where F: Send + Clone, D: OperationSessionGetters<F> + Send + Sync + Clone, { fn check_predecrypted_token( &self, payment_data: &D, ) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse> { let google_pay_wallet_data = payment_data .get_payment_method_data() .and_then(|payment_method_data| payment_method_data.get_wallet_data()) .and_then(|wallet_data| wallet_data.get_google_pay_wallet_data()); let result = if let Some(data) = google_pay_wallet_data { match &data.tokenization_data { common_payments_types::GpayTokenizationData::Encrypted(_) => None, common_payments_types::GpayTokenizationData::Decrypted( google_pay_predecrypt_data, ) => { helpers::validate_card_expiry( &google_pay_predecrypt_data.card_exp_month, &google_pay_predecrypt_data.card_exp_year, )?; Some(PaymentMethodToken::GooglePayDecrypt(Box::new( google_pay_predecrypt_data.clone(), ))) } } } else { None }; Ok(result) } fn decide_wallet_flow( &self, state: &SessionState, _payment_data: &D, merchant_connector_account: &helpers::MerchantConnectorAccountType, ) -> CustomResult<Option<DecideWalletFlow>, errors::ApiErrorResponse> { Ok( get_google_pay_connector_wallet_details(state, merchant_connector_account) .map(DecideWalletFlow::GooglePayDecrypt), ) } async fn decrypt_wallet_token( &self, wallet_flow: &DecideWalletFlow, payment_data: &D, ) -> CustomResult<PaymentMethodToken, errors::ApiErrorResponse> { let google_pay_payment_processing_details = wallet_flow .get_google_pay_payment_processing_details() .get_required_value("Google Pay payment processing details") .attach_printable( "Google Pay payment processing details not found in Google Pay decryption flow", )?; let google_pay_wallet_data = payment_data .get_payment_method_data() .and_then(|payment_method_data| payment_method_data.get_wallet_data()) .and_then(|wallet_data| wallet_data.get_google_pay_wallet_data()) .get_required_value("Paze wallet token").attach_printable( "Google Pay wallet data not found in the payment method data during the Google Pay decryption flow", )?; let decryptor = helpers::GooglePayTokenDecryptor::new( google_pay_payment_processing_details .google_pay_root_signing_keys .clone(), google_pay_payment_processing_details .google_pay_recipient_id .clone(), google_pay_payment_processing_details .google_pay_private_key .clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to create google pay token decryptor")?; // should_verify_token is set to false to disable verification of token let google_pay_data_internal = decryptor .decrypt_token( google_pay_wallet_data .tokenization_data .get_encrypted_google_pay_token() .change_context(errors::ApiErrorResponse::InternalServerError)? .clone(), false, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to decrypt google pay token")?; let google_pay_data = common_types::payments::GPayPredecryptData::from(google_pay_data_internal); Ok(PaymentMethodToken::GooglePayDecrypt(Box::new( google_pay_data, ))) } } #[derive(Debug, Clone)] pub enum DecideWalletFlow { ApplePayDecrypt(payments_api::PaymentProcessingDetails), PazeDecrypt(PazePaymentProcessingDetails), GooglePayDecrypt(GooglePayPaymentProcessingDetails), SkipDecryption, } impl DecideWalletFlow { fn get_paze_payment_processing_details(&self) -> Option<&PazePaymentProcessingDetails> { if let Self::PazeDecrypt(details) = self { Some(details) } else { None } } fn get_apple_pay_payment_processing_details( &self, ) -> Option<&payments_api::PaymentProcessingDetails> { if let Self::ApplePayDecrypt(details) = self { Some(details) } else { None } } fn get_google_pay_payment_processing_details( &self, ) -> Option<&GooglePayPaymentProcessingDetails> { if let Self::GooglePayDecrypt(details) = self { Some(details) } else { None } } } pub async fn get_merchant_bank_data_for_open_banking_connectors( merchant_connector_account: &helpers::MerchantConnectorAccountType, merchant_context: &domain::MerchantContext, connector: &api::ConnectorData, state: &SessionState, ) -> RouterResult<Option<router_types::MerchantRecipientData>> { let merchant_data = merchant_connector_account .get_additional_merchant_data() .get_required_value("additional_merchant_data")? .into_inner() .peek() .clone(); let merchant_recipient_data = merchant_data .parse_value::<router_types::AdditionalMerchantData>("AdditionalMerchantData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to decode MerchantRecipientData")?; let connector_name = enums::Connector::to_string(&connector.connector_name); let locker_based_connector_list = state.conf.locker_based_open_banking_connectors.clone(); let contains = locker_based_connector_list .connector_list .contains(connector_name.as_str()); let recipient_id = helpers::get_recipient_id_for_open_banking(&merchant_recipient_data)?; let final_recipient_data = if let Some(id) = recipient_id { if contains { // Customer Id for OpenBanking connectors will be merchant_id as the account data stored at locker belongs to the merchant let merchant_id_str = merchant_context .get_merchant_account() .get_id() .get_string_repr() .to_owned(); let cust_id = id_type::CustomerId::try_from(std::borrow::Cow::from(merchant_id_str)) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert to CustomerId")?; let locker_resp = cards::get_payment_method_from_hs_locker( state, merchant_context.get_merchant_key_store(), &cust_id, merchant_context.get_merchant_account().get_id(), id.as_str(), Some(enums::LockerChoice::HyperswitchCardVault), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Merchant bank account data could not be fetched from locker")?; let parsed: router_types::MerchantAccountData = locker_resp .peek() .to_string() .parse_struct("MerchantAccountData") .change_context(errors::ApiErrorResponse::InternalServerError)?; Some(router_types::MerchantRecipientData::AccountData(parsed)) } else { Some(router_types::MerchantRecipientData::ConnectorRecipientId( Secret::new(id), )) } } else { None }; Ok(final_recipient_data) } async fn blocklist_guard<F, ApiRequest, D>( state: &SessionState, merchant_context: &domain::MerchantContext, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, ) -> CustomResult<bool, errors::ApiErrorResponse> where F: Send + Clone + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let merchant_id = merchant_context.get_merchant_account().get_id(); let blocklist_enabled_key = merchant_id.get_blocklist_guard_key(); let blocklist_guard_enabled = state .store .find_config_by_key_unwrap_or(&blocklist_enabled_key, Some("false".to_string())) .await; let blocklist_guard_enabled: bool = match blocklist_guard_enabled { Ok(config) => serde_json::from_str(&config.config).unwrap_or(false), // If it is not present in db we are defaulting it to false Err(inner) => { if !inner.current_context().is_db_not_found() { logger::error!("Error fetching guard blocklist enabled config {:?}", inner); } false } }; if blocklist_guard_enabled { Ok(operation .to_domain()? .guard_payment_against_blocklist(state, merchant_context, payment_data) .await?) } else { Ok(false) } } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn call_multiple_connectors_service<F, Op, Req, D>( state: &SessionState, merchant_context: &domain::MerchantContext, connectors: api::SessionConnectorDatas, _operation: &Op, mut payment_data: D, customer: &Option<domain::Customer>, _session_surcharge_details: Option<api::SessionSurchargeDetails>, business_profile: &domain::Profile, header_payload: HeaderPayload, return_raw_connector_response: Option<bool>, ) -> RouterResult<D> where Op: Debug, F: Send + Clone + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, Req, router_types::PaymentsResponseData>, RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req>, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>, { let call_connectors_start_time = Instant::now(); let mut join_handlers = Vec::with_capacity(connectors.len()); for session_connector_data in connectors.iter() { let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new( helpers::get_merchant_connector_account_v2( state, merchant_context.get_merchant_key_store(), session_connector_data .connector .merchant_connector_id .as_ref(), ) .await?, )); let connector_id = session_connector_data.connector.connector.id(); let router_data = payment_data .construct_router_data( state, connector_id, merchant_context, customer, &merchant_connector_account, None, Some(header_payload.clone()), ) .await?; let res = router_data.decide_flows( state, &session_connector_data.connector, CallConnectorAction::Trigger, None, business_profile, header_payload.clone(), return_raw_connector_response, ); join_handlers.push(res); } let result = join_all(join_handlers).await; for (connector_res, session_connector) in result.into_iter().zip(connectors) { let connector_name = session_connector.connector.connector_name.to_string(); match connector_res { Ok(connector_response) => { if let Ok(router_types::PaymentsResponseData::SessionResponse { session_token, .. }) = connector_response.response.clone() { // If session token is NoSessionTokenReceived, it is not pushed into the sessions_token as there is no response or there can be some error // In case of error, that error is already logged if !matches!( session_token, api_models::payments::SessionToken::NoSessionTokenReceived, ) { payment_data.push_sessions_token(session_token); } } if let Err(connector_error_response) = connector_response.response { logger::error!( "sessions_connector_error {} {:?}", connector_name, connector_error_response ); } } Err(api_error) => { logger::error!("sessions_api_error {} {:?}", connector_name, api_error); } } } let call_connectors_end_time = Instant::now(); let call_connectors_duration = call_connectors_end_time.saturating_duration_since(call_connectors_start_time); tracing::info!(duration = format!("Duration taken: {}", call_connectors_duration.as_millis())); Ok(payment_data) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn call_multiple_connectors_service<F, Op, Req, D>( state: &SessionState, merchant_context: &domain::MerchantContext, connectors: api::SessionConnectorDatas, _operation: &Op, mut payment_data: D, customer: &Option<domain::Customer>, session_surcharge_details: Option<api::SessionSurchargeDetails>, business_profile: &domain::Profile, header_payload: HeaderPayload, return_raw_connector_response: Option<bool>, ) -> RouterResult<D> where Op: Debug, F: Send + Clone, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, Req, router_types::PaymentsResponseData>, RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req>, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>, { let call_connectors_start_time = Instant::now(); let mut join_handlers = Vec::with_capacity(connectors.len()); for session_connector_data in connectors.iter() { let connector_id = session_connector_data.connector.connector.id(); let merchant_connector_account = construct_profile_id_and_get_mca( state, merchant_context, &payment_data, &session_connector_data.connector.connector_name.to_string(), session_connector_data .connector .merchant_connector_id .as_ref(), false, ) .await?; payment_data.set_surcharge_details(session_surcharge_details.as_ref().and_then( |session_surcharge_details| { session_surcharge_details.fetch_surcharge_details( session_connector_data.payment_method_sub_type.into(), session_connector_data.payment_method_sub_type, None, ) }, )); let router_data = payment_data .construct_router_data( state, connector_id, merchant_context, customer, &merchant_connector_account, None, Some(header_payload.clone()), Some(session_connector_data.payment_method_type), Some(session_connector_data.payment_method_sub_type), ) .await?; let res = router_data.decide_flows( state, &session_connector_data.connector, CallConnectorAction::Trigger, None, business_profile, header_payload.clone(), return_raw_connector_response, ); join_handlers.push(res); } let result = join_all(join_handlers).await; for (connector_res, session_connector) in result.into_iter().zip(connectors) { let connector_name = session_connector.connector.connector_name.to_string(); match connector_res { Ok(connector_response) => { if let Ok(router_types::PaymentsResponseData::SessionResponse { session_token, .. }) = connector_response.response.clone() { // If session token is NoSessionTokenReceived, it is not pushed into the sessions_token as there is no response or there can be some error // In case of error, that error is already logged if !matches!( session_token, api_models::payments::SessionToken::NoSessionTokenReceived, ) { payment_data.push_sessions_token(session_token); } } if let Err(connector_error_response) = connector_response.response { logger::error!( "sessions_connector_error {} {:?}", connector_name, connector_error_response ); } } Err(api_error) => { logger::error!("sessions_api_error {} {:?}", connector_name, api_error); } } } // If click_to_pay is enabled and authentication_product_ids is configured in profile, we need to attach click_to_pay block in the session response for invoking click_to_pay SDK if business_profile.is_click_to_pay_enabled { if let Some(value) = business_profile.authentication_product_ids.clone() { let session_token = get_session_token_for_click_to_pay( state, merchant_context.get_merchant_account().get_id(), merchant_context, value, payment_data.get_payment_intent(), business_profile.get_id(), ) .await?; payment_data.push_sessions_token(session_token); } } let call_connectors_end_time = Instant::now(); let call_connectors_duration = call_connectors_end_time.saturating_duration_since(call_connectors_start_time); tracing::info!(duration = format!("Duration taken: {}", call_connectors_duration.as_millis())); Ok(payment_data) } #[cfg(feature = "v1")] pub async fn get_session_token_for_click_to_pay( state: &SessionState, merchant_id: &id_type::MerchantId, merchant_context: &domain::MerchantContext, authentication_product_ids: common_types::payments::AuthenticationConnectorAccountMap, payment_intent: &payments::PaymentIntent, profile_id: &id_type::ProfileId, ) -> RouterResult<api_models::payments::SessionToken> { let click_to_pay_mca_id = authentication_product_ids .get_click_to_pay_connector_account_id() .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "authentication_product_ids", })?; let key_manager_state = &(state).into(); let merchant_connector_account = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_id, &click_to_pay_mca_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: click_to_pay_mca_id.get_string_repr().to_string(), })?; let click_to_pay_metadata: ClickToPayMetaData = merchant_connector_account .metadata .parse_value("ClickToPayMetaData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while parsing ClickToPayMetaData")?; let transaction_currency = payment_intent .currency .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("currency is not present in payment_data.payment_intent")?; let required_amount_type = common_utils::types::StringMajorUnitForConnector; let transaction_amount = required_amount_type .convert(payment_intent.amount, transaction_currency) .change_context(errors::ApiErrorResponse::AmountConversionFailed { amount_type: "string major unit", })?; let customer_details_value = payment_intent .customer_details .clone() .get_required_value("customer_details")?; let customer_details: CustomerData = customer_details_value .parse_value("CustomerData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while parsing customer data from payment intent")?; validate_customer_details_for_click_to_pay(&customer_details)?; let provider = match merchant_connector_account.connector_name.as_str() { "ctp_mastercard" => Some(enums::CtpServiceProvider::Mastercard), "ctp_visa" => Some(enums::CtpServiceProvider::Visa), _ => None, }; let card_brands = get_card_brands_based_on_active_merchant_connector_account( state, profile_id, merchant_context.get_merchant_key_store(), ) .await?; Ok(api_models::payments::SessionToken::ClickToPay(Box::new( api_models::payments::ClickToPaySessionResponse { dpa_id: click_to_pay_metadata.dpa_id, dpa_name: click_to_pay_metadata.dpa_name, locale: click_to_pay_metadata.locale, card_brands, acquirer_bin: click_to_pay_metadata.acquirer_bin, acquirer_merchant_id: click_to_pay_metadata.acquirer_merchant_id, merchant_category_code: click_to_pay_metadata.merchant_category_code, merchant_country_code: click_to_pay_metadata.merchant_country_code, transaction_amount, transaction_currency_code: transaction_currency, phone_number: customer_details.phone.clone(), email: customer_details.email.clone(), phone_country_code: customer_details.phone_country_code.clone(), provider, dpa_client_id: click_to_pay_metadata.dpa_client_id.clone(), }, ))) } #[cfg(feature = "v1")] async fn get_card_brands_based_on_active_merchant_connector_account( state: &SessionState, profile_id: &id_type::ProfileId, key_store: &domain::MerchantKeyStore, ) -> RouterResult<HashSet<enums::CardNetwork>> { let key_manager_state = &(state).into(); let merchant_configured_payment_connectors = 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("error when fetching merchant connector accounts")?; let payment_connectors_eligible_for_click_to_pay = state.conf.authentication_providers.click_to_pay.clone(); let filtered_payment_connector_accounts: Vec< hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, > = merchant_configured_payment_connectors .into_iter() .filter(|account| { enums::Connector::from_str(&account.connector_name) .ok() .map(|connector| payment_connectors_eligible_for_click_to_pay.contains(&connector)) .unwrap_or(false) }) .collect(); let mut card_brands = HashSet::new(); for account in filtered_payment_connector_accounts { if let Some(values) = &account.payment_methods_enabled { for val in values { let payment_methods_enabled: api_models::admin::PaymentMethodsEnabled = serde_json::from_value(val.peek().to_owned()).inspect_err(|err| { logger::error!("Failed to parse Payment methods enabled data set from dashboard because {}", err) }) .change_context(errors::ApiErrorResponse::InternalServerError)?; if let Some(payment_method_types) = payment_methods_enabled.payment_method_types { for payment_method_type in payment_method_types { if let Some(networks) = payment_method_type.card_networks { card_brands.extend(networks); } } } } } } Ok(card_brands) } fn validate_customer_details_for_click_to_pay(customer_details: &CustomerData) -> RouterResult<()> { match ( customer_details.phone.as_ref(), customer_details.phone_country_code.as_ref(), customer_details.email.as_ref() ) { (None, None, Some(_)) => Ok(()), (Some(_), Some(_), Some(_)) => Ok(()), (Some(_), Some(_), None) => Ok(()), (Some(_), None, Some(_)) => Ok(()), (None, Some(_), None) => Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "phone", }) .attach_printable("phone number is not present in payment_intent.customer_details"), (Some(_), None, None) => Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "phone_country_code", }) .attach_printable("phone_country_code is not present in payment_intent.customer_details"), (_, _, _) => Err(errors::ApiErrorResponse::MissingRequiredFields { field_names: vec!["phone", "phone_country_code", "email"], }) .attach_printable("either of phone, phone_country_code or email is not present in payment_intent.customer_details"), } } #[cfg(feature = "v1")] pub async fn call_create_connector_customer_if_required<F, Req, D>( state: &SessionState, customer: &Option<domain::Customer>, merchant_context: &domain::MerchantContext, merchant_connector_account: &helpers::MerchantConnectorAccountType, payment_data: &mut D, access_token: Option<&AccessToken>, ) -> RouterResult<Option<storage::CustomerUpdate>> where F: Send + Clone + Sync, Req: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, Req, router_types::PaymentsResponseData>, RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>, { let connector_name = payment_data.get_payment_attempt().connector.clone(); match connector_name { Some(connector_name) => { let connector = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_name, api::GetToken::Connector, merchant_connector_account.get_mca_id(), )?; let label = { let connector_label = core_utils::get_connector_label( payment_data.get_payment_intent().business_country, payment_data.get_payment_intent().business_label.as_ref(), payment_data .get_payment_attempt() .business_sub_label .as_ref(), &connector_name, ); if let Some(connector_label) = merchant_connector_account .get_mca_id() .map(|mca_id| mca_id.get_string_repr().to_string()) .or(connector_label) { connector_label } else { let profile_id = payment_data .get_payment_intent() .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")?; format!("{connector_name}_{}", profile_id.get_string_repr()) } }; let (should_call_connector, existing_connector_customer_id) = customers::should_call_connector_create_customer( &connector, customer, payment_data.get_payment_attempt(), &label, ); if should_call_connector { // Create customer at connector and update the customer table to store this data let mut customer_router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_context, customer, merchant_connector_account, None, None, payment_data.get_payment_attempt().payment_method, payment_data.get_payment_attempt().payment_method_type, ) .await?; customer_router_data.access_token = access_token.cloned(); let connector_customer_id = customer_router_data .create_connector_customer(state, &connector) .await?; let customer_update = customers::update_connector_customer_in_customers( &label, customer.as_ref(), connector_customer_id.clone(), ) .await; payment_data.set_connector_customer_id(connector_customer_id); Ok(customer_update) } else { // Customer already created in previous calls use the same value, no need to update payment_data.set_connector_customer_id( existing_connector_customer_id.map(ToOwned::to_owned), ); Ok(None) } } None => Ok(None), } } #[cfg(feature = "v2")] pub async fn call_create_connector_customer_if_required<F, Req, D>( state: &SessionState, customer: &Option<domain::Customer>, merchant_context: &domain::MerchantContext, merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails, payment_data: &mut D, ) -> RouterResult<Option<storage::CustomerUpdate>> where F: Send + Clone + Sync, Req: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, Req, router_types::PaymentsResponseData>, RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>, { let connector_name = payment_data.get_payment_attempt().connector.clone(); match connector_name { Some(connector_name) => { let connector = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_name, api::GetToken::Connector, merchant_connector_account.get_id(), )?; let (should_call_connector, existing_connector_customer_id) = customers::should_call_connector_create_customer( &connector, customer, payment_data.get_payment_attempt(), merchant_connector_account, ); if should_call_connector { // Create customer at connector and update the customer table to store this data let router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_context, customer, merchant_connector_account, None, None, ) .await?; let connector_customer_id = router_data .create_connector_customer(state, &connector) .await?; let customer_update = customers::update_connector_customer_in_customers( merchant_connector_account, customer.as_ref(), connector_customer_id.clone(), ) .await; payment_data.set_connector_customer_id(connector_customer_id); Ok(customer_update) } else { // Customer already created in previous calls use the same value, no need to update payment_data.set_connector_customer_id( existing_connector_customer_id.map(ToOwned::to_owned), ); Ok(None) } } None => Ok(None), } } async fn complete_preprocessing_steps_if_required<F, Req, Q, D>( state: &SessionState, connector: &api::ConnectorData, payment_data: &D, mut router_data: RouterData<F, Req, router_types::PaymentsResponseData>, operation: &BoxedOperation<'_, F, Q, D>, should_continue_payment: bool, ) -> RouterResult<(RouterData<F, Req, router_types::PaymentsResponseData>, bool)> where F: Send + Clone + Sync, D: OperationSessionGetters<F> + Send + Sync + Clone, Req: Send + Sync, RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req> + Send, dyn api::Connector: services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>, { if !is_operation_complete_authorize(&operation) && connector .connector_name .is_pre_processing_required_before_authorize() { router_data = router_data.preprocessing_steps(state, connector).await?; return Ok((router_data, should_continue_payment)); } //TODO: For ACH transfers, if preprocessing_step is not required for connectors encountered in future, add the check let router_data_and_should_continue_payment = match payment_data.get_payment_method_data() { Some(domain::PaymentMethodData::BankTransfer(_)) => (router_data, should_continue_payment), Some(domain::PaymentMethodData::Wallet(_)) => { if is_preprocessing_required_for_wallets(connector.connector_name.to_string()) { ( router_data.preprocessing_steps(state, connector).await?, false, ) } else if connector.connector_name == router_types::Connector::Paysafe { match payment_data.get_payment_method_data() { Some(domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(_))) => { router_data = router_data.preprocessing_steps(state, connector).await?; let is_error_in_response = router_data.response.is_err(); (router_data, !is_error_in_response) } _ => (router_data, should_continue_payment), } } else { (router_data, should_continue_payment) } } Some(domain::PaymentMethodData::Card(_)) => { if connector.connector_name == router_types::Connector::Payme && !matches!(format!("{operation:?}").as_str(), "CompleteAuthorize") { 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 (router_data, !is_error_in_response) } else if connector.connector_name == router_types::Connector::Nmi && !matches!(format!("{operation:?}").as_str(), "CompleteAuthorize") && router_data.auth_type == storage_enums::AuthenticationType::ThreeDs && !matches!( payment_data .get_payment_attempt() .external_three_ds_authentication_attempted, Some(true) ) { router_data = router_data.preprocessing_steps(state, connector).await?; (router_data, false) } else if connector.connector_name == router_types::Connector::Paysafe && router_data.auth_type == storage_enums::AuthenticationType::NoThreeDs { 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 (router_data, !is_error_in_response) } else if (connector.connector_name == router_types::Connector::Cybersource || connector.connector_name == router_types::Connector::Barclaycard) && is_operation_complete_authorize(&operation) && router_data.auth_type == storage_enums::AuthenticationType::ThreeDs { router_data = router_data.preprocessing_steps(state, connector).await?; // Should continue the flow only if no redirection_data is returned else a response with redirection form shall be returned let should_continue = matches!( router_data.response, Ok(router_types::PaymentsResponseData::TransactionResponse { ref redirection_data, .. }) if redirection_data.is_none() ) && router_data.status != common_enums::AttemptStatus::AuthenticationFailed; (router_data, should_continue) } else if router_data.auth_type == common_enums::AuthenticationType::ThreeDs && ((connector.connector_name == router_types::Connector::Nexixpay && is_operation_complete_authorize(&operation)) || (((connector.connector_name == router_types::Connector::Nuvei && { #[cfg(feature = "v1")] { payment_data .get_payment_intent() .request_external_three_ds_authentication != Some(true) } #[cfg(feature = "v2")] { payment_data .get_payment_intent() .request_external_three_ds_authentication != Some(true).into() } }) || connector.connector_name == router_types::Connector::Shift4) && !is_operation_complete_authorize(&operation))) { router_data = router_data.preprocessing_steps(state, connector).await?; (router_data, should_continue_payment) } else if connector.connector_name == router_types::Connector::Xendit && is_operation_confirm(&operation) { match payment_data.get_payment_intent().split_payments { Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment( common_types::payments::XenditSplitRequest::MultipleSplits(_), )) => { router_data = router_data.preprocessing_steps(state, connector).await?; let is_error_in_response = router_data.response.is_err(); (router_data, !is_error_in_response) } _ => (router_data, should_continue_payment), } } else if connector.connector_name == router_types::Connector::Redsys && router_data.auth_type == common_enums::AuthenticationType::ThreeDs && is_operation_confirm(&operation) { router_data = router_data.preprocessing_steps(state, connector).await?; let should_continue = match router_data.response { Ok(router_types::PaymentsResponseData::TransactionResponse { ref connector_metadata, .. }) => { let three_ds_invoke_data: Option< api_models::payments::PaymentsConnectorThreeDsInvokeData, > = connector_metadata.clone().and_then(|metadata| { metadata .parse_value("PaymentsConnectorThreeDsInvokeData") .ok() // "ThreeDsInvokeData was not found; proceeding with the payment flow without triggering the ThreeDS invoke action" }); three_ds_invoke_data.is_none() } _ => false, }; (router_data, should_continue) } else { (router_data, should_continue_payment) } } Some(domain::PaymentMethodData::GiftCard(gift_card_data)) => { if connector.connector_name == router_types::Connector::Adyen && matches!(gift_card_data.deref(), domain::GiftCardData::Givex(..)) { 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 (router_data, !is_error_in_response) } else { (router_data, should_continue_payment) } } Some(domain::PaymentMethodData::BankDebit(_)) => { 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 (router_data, !is_error_in_response) } else { (router_data, should_continue_payment) } } _ => { // 3DS validation for paypal cards after verification (authorize call) if connector.connector_name == router_types::Connector::Paypal && payment_data.get_payment_attempt().get_payment_method() == Some(storage_enums::PaymentMethod::Card) && matches!(format!("{operation:?}").as_str(), "CompleteAuthorize") { 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 (router_data, !is_error_in_response) } else { (router_data, should_continue_payment) } } }; Ok(router_data_and_should_continue_payment) } #[cfg(feature = "v1")] async fn complete_confirmation_for_click_to_pay_if_required<F, D>( state: &SessionState, merchant_context: &domain::MerchantContext, payment_data: &D, ) -> RouterResult<()> where F: Send + Clone + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let payment_attempt = payment_data.get_payment_attempt(); let payment_intent = payment_data.get_payment_intent(); let service_details = payment_data.get_click_to_pay_service_details(); let authentication = payment_data.get_authentication(); let should_do_uas_confirmation_call = service_details .as_ref() .map(|details| details.is_network_confirmation_call_required()) .unwrap_or(false); if should_do_uas_confirmation_call && (payment_intent.status == storage_enums::IntentStatus::Succeeded || payment_intent.status == storage_enums::IntentStatus::Failed) { let authentication_connector_id = authentication .as_ref() .and_then(|auth| auth.authentication.merchant_connector_id.clone()) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to get authentication connector id from authentication table", )?; let key_manager_state = &(state).into(); let key_store = merchant_context.get_merchant_key_store(); let merchant_id = merchant_context.get_merchant_account().get_id(); let connector_mca = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_id, &authentication_connector_id, key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: authentication_connector_id.get_string_repr().to_string(), })?; let payment_method = payment_attempt .payment_method .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get payment method from payment attempt")?; ClickToPay::confirmation( state, payment_attempt.authentication_id.as_ref(), payment_intent.currency, payment_attempt.status, service_details.cloned(), &helpers::MerchantConnectorAccountType::DbVal(Box::new(connector_mca.clone())), &connector_mca.connector_name, payment_method, payment_attempt.net_amount.get_order_amount(), Some(&payment_intent.payment_id), merchant_id, ) .await?; Ok(()) } else { Ok(()) } } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn complete_postprocessing_steps_if_required<F, Q, RouterDReq, D>( state: &SessionState, merchant_context: &domain::MerchantContext, customer: &Option<domain::Customer>, merchant_conn_account: &helpers::MerchantConnectorAccountType, connector: &api::ConnectorData, payment_data: &mut D, _operation: &BoxedOperation<'_, F, Q, D>, header_payload: Option<HeaderPayload>, ) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, RouterDReq: Send + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, { let mut router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_context, customer, merchant_conn_account, None, header_payload, payment_data.get_payment_attempt().payment_method, payment_data.get_payment_attempt().payment_method_type, ) .await?; match payment_data.get_payment_method_data() { Some(domain::PaymentMethodData::OpenBanking(domain::OpenBankingData::OpenBankingPIS { .. })) => { if connector.connector_name == router_types::Connector::Plaid { router_data = router_data.postprocessing_steps(state, connector).await?; let token = if let Ok(ref res) = router_data.response { match res { router_types::PaymentsResponseData::PostProcessingResponse { session_token, } => session_token .as_ref() .map(|token| api::SessionToken::OpenBanking(token.clone())), _ => None, } } else { None }; if let Some(t) = token { payment_data.push_sessions_token(t); } Ok(router_data) } else { Ok(router_data) } } _ => Ok(router_data), } } pub fn is_preprocessing_required_for_wallets(connector_name: String) -> bool { connector_name == *"trustpay" || connector_name == *"payme" } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn construct_profile_id_and_get_mca<'a, F, D>( state: &'a SessionState, merchant_context: &domain::MerchantContext, payment_data: &D, connector_name: &str, merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>, _should_validate: bool, ) -> RouterResult<helpers::MerchantConnectorAccountType> where F: Clone, D: OperationSessionGetters<F> + Send + Sync + Clone, { let profile_id = payment_data .get_payment_intent() .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")? .clone(); #[cfg(feature = "v2")] let profile_id = payment_data.get_payment_intent().profile_id.clone(); let merchant_connector_account = helpers::get_merchant_connector_account( state, merchant_context.get_merchant_account().get_id(), payment_data.get_creds_identifier(), merchant_context.get_merchant_key_store(), &profile_id, connector_name, merchant_connector_id, ) .await?; Ok(merchant_connector_account) } #[cfg(feature = "v2")] fn is_payment_method_tokenization_enabled_for_connector( state: &SessionState, connector_name: &str, payment_method: storage::enums::PaymentMethod, payment_method_type: Option<storage::enums::PaymentMethodType>, mandate_flow_enabled: storage_enums::FutureUsage, ) -> RouterResult<bool> { let connector_tokenization_filter = state.conf.tokenization.0.get(connector_name); Ok(connector_tokenization_filter .map(|connector_filter| { connector_filter .payment_method .clone() .contains(&payment_method) && is_payment_method_type_allowed_for_connector( payment_method_type, connector_filter.payment_method_type.clone(), ) && is_payment_flow_allowed_for_connector( mandate_flow_enabled, connector_filter.flow.clone(), ) }) .unwrap_or(false)) } // Determines connector tokenization eligibility: if no flow restriction, allow for one-off/CIT with raw cards; if flow = “mandates”, only allow MIT off-session with stored tokens. #[cfg(feature = "v2")] fn is_payment_flow_allowed_for_connector( mandate_flow_enabled: storage_enums::FutureUsage, payment_flow: Option<PaymentFlow>, ) -> bool { if payment_flow.is_none() { true } else { matches!(payment_flow, Some(PaymentFlow::Mandates)) && matches!(mandate_flow_enabled, storage_enums::FutureUsage::OffSession) } } #[cfg(feature = "v1")] fn is_payment_method_tokenization_enabled_for_connector( state: &SessionState, connector_name: &str, payment_method: storage::enums::PaymentMethod, payment_method_type: Option<storage::enums::PaymentMethodType>, payment_method_token: Option<&PaymentMethodToken>, mandate_flow_enabled: Option<storage_enums::FutureUsage>, ) -> RouterResult<bool> { let connector_tokenization_filter = state.conf.tokenization.0.get(connector_name); Ok(connector_tokenization_filter .map(|connector_filter| { connector_filter .payment_method .clone() .contains(&payment_method) && is_payment_method_type_allowed_for_connector( payment_method_type, connector_filter.payment_method_type.clone(), ) && is_apple_pay_pre_decrypt_type_connector_tokenization( payment_method_type, payment_method_token, connector_filter.apple_pay_pre_decrypt_flow.clone(), ) && is_google_pay_pre_decrypt_type_connector_tokenization( payment_method_type, payment_method_token, connector_filter.google_pay_pre_decrypt_flow.clone(), ) && is_payment_flow_allowed_for_connector( mandate_flow_enabled, connector_filter.flow.clone(), ) }) .unwrap_or(false)) } #[cfg(feature = "v1")] fn is_payment_flow_allowed_for_connector( mandate_flow_enabled: Option<storage_enums::FutureUsage>, payment_flow: Option<PaymentFlow>, ) -> bool { if payment_flow.is_none() { true } else { matches!(payment_flow, Some(PaymentFlow::Mandates)) && matches!( mandate_flow_enabled, Some(storage_enums::FutureUsage::OffSession) ) } } fn is_apple_pay_pre_decrypt_type_connector_tokenization( payment_method_type: Option<storage::enums::PaymentMethodType>, payment_method_token: Option<&PaymentMethodToken>, apple_pay_pre_decrypt_flow_filter: Option<ApplePayPreDecryptFlow>, ) -> bool { match (payment_method_type, payment_method_token) { ( Some(storage::enums::PaymentMethodType::ApplePay), Some(PaymentMethodToken::ApplePayDecrypt(..)), ) => !matches!( apple_pay_pre_decrypt_flow_filter, Some(ApplePayPreDecryptFlow::NetworkTokenization) ), _ => true, } } fn is_google_pay_pre_decrypt_type_connector_tokenization( payment_method_type: Option<storage::enums::PaymentMethodType>, payment_method_token: Option<&PaymentMethodToken>, google_pay_pre_decrypt_flow_filter: Option<GooglePayPreDecryptFlow>, ) -> bool { if let ( Some(storage::enums::PaymentMethodType::GooglePay), Some(PaymentMethodToken::GooglePayDecrypt(..)), ) = (payment_method_type, payment_method_token) { !matches!( google_pay_pre_decrypt_flow_filter, Some(GooglePayPreDecryptFlow::NetworkTokenization) ) } else { // Always return true for non–Google Pay pre-decrypt cases, // because the filter is only relevant for Google Pay pre-decrypt tokenization. // Returning true ensures that other payment methods or token types are not blocked. true } } fn decide_apple_pay_flow( state: &SessionState, payment_method_type: Option<enums::PaymentMethodType>, merchant_connector_account: Option<&helpers::MerchantConnectorAccountType>, ) -> Option<domain::ApplePayFlow> { payment_method_type.and_then(|pmt| match pmt { enums::PaymentMethodType::ApplePay => { check_apple_pay_metadata(state, merchant_connector_account) } _ => None, }) } fn check_apple_pay_metadata( state: &SessionState, merchant_connector_account: Option<&helpers::MerchantConnectorAccountType>, ) -> Option<domain::ApplePayFlow> { merchant_connector_account.and_then(|mca| { let metadata = mca.get_metadata(); metadata.and_then(|apple_pay_metadata| { let parsed_metadata = apple_pay_metadata .clone() .parse_value::<api_models::payments::ApplepayCombinedSessionTokenData>( "ApplepayCombinedSessionTokenData", ) .map(|combined_metadata| { api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined( combined_metadata.apple_pay_combined, ) }) .or_else(|_| { apple_pay_metadata .parse_value::<api_models::payments::ApplepaySessionTokenData>( "ApplepaySessionTokenData", ) .map(|old_metadata| { api_models::payments::ApplepaySessionTokenMetadata::ApplePay( old_metadata.apple_pay, ) }) }) .map_err(|error| { logger::warn!(?error, "Failed to Parse Value to ApplepaySessionTokenData") }); parsed_metadata.ok().map(|metadata| match metadata { api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined( apple_pay_combined, ) => match apple_pay_combined { api_models::payments::ApplePayCombinedMetadata::Simplified { .. } => { domain::ApplePayFlow::Simplified(payments_api::PaymentProcessingDetails { payment_processing_certificate: state .conf .applepay_decrypt_keys .get_inner() .apple_pay_ppc .clone(), payment_processing_certificate_key: state .conf .applepay_decrypt_keys .get_inner() .apple_pay_ppc_key .clone(), }) } api_models::payments::ApplePayCombinedMetadata::Manual { payment_request_data: _, session_token_data, } => { if let Some(manual_payment_processing_details_at) = session_token_data.payment_processing_details_at { match manual_payment_processing_details_at { payments_api::PaymentProcessingDetailsAt::Hyperswitch( payment_processing_details, ) => domain::ApplePayFlow::Simplified(payment_processing_details), payments_api::PaymentProcessingDetailsAt::Connector => { domain::ApplePayFlow::Manual } } } else { domain::ApplePayFlow::Manual } } }, api_models::payments::ApplepaySessionTokenMetadata::ApplePay(_) => { domain::ApplePayFlow::Manual } }) }) }) } fn get_google_pay_connector_wallet_details( state: &SessionState, merchant_connector_account: &helpers::MerchantConnectorAccountType, ) -> Option<GooglePayPaymentProcessingDetails> { let google_pay_root_signing_keys = state .conf .google_pay_decrypt_keys .as_ref() .map(|google_pay_keys| google_pay_keys.google_pay_root_signing_keys.clone()); match merchant_connector_account.get_connector_wallets_details() { Some(wallet_details) => { let google_pay_wallet_details = wallet_details .parse_value::<api_models::payments::GooglePayWalletDetails>( "GooglePayWalletDetails", ) .map_err(|error| { logger::warn!(?error, "Failed to Parse Value to GooglePayWalletDetails") }); google_pay_wallet_details .ok() .and_then( |google_pay_wallet_details| { match google_pay_wallet_details .google_pay .provider_details { api_models::payments::GooglePayProviderDetails::GooglePayMerchantDetails(merchant_details) => { match ( merchant_details .merchant_info .tokenization_specification .parameters .private_key, google_pay_root_signing_keys, merchant_details .merchant_info .tokenization_specification .parameters .recipient_id, ) { (Some(google_pay_private_key), Some(google_pay_root_signing_keys), Some(google_pay_recipient_id)) => { Some(GooglePayPaymentProcessingDetails { google_pay_private_key, google_pay_root_signing_keys, google_pay_recipient_id }) } _ => { logger::warn!("One or more of the following fields are missing in GooglePayMerchantDetails: google_pay_private_key, google_pay_root_signing_keys, google_pay_recipient_id"); None } } } } } ) } None => None, } } fn is_payment_method_type_allowed_for_connector( current_pm_type: Option<storage::enums::PaymentMethodType>, pm_type_filter: Option<PaymentMethodTypeTokenFilter>, ) -> bool { match (current_pm_type).zip(pm_type_filter) { Some((pm_type, type_filter)) => match type_filter { PaymentMethodTypeTokenFilter::AllAccepted => true, PaymentMethodTypeTokenFilter::EnableOnly(enabled) => enabled.contains(&pm_type), PaymentMethodTypeTokenFilter::DisableOnly(disabled) => !disabled.contains(&pm_type), }, None => true, // Allow all types if payment_method_type is not present } } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn decide_payment_method_tokenize_action( state: &SessionState, connector_name: &str, payment_method: storage::enums::PaymentMethod, payment_intent_data: payments::PaymentIntent, pm_parent_token: Option<&str>, is_connector_tokenization_enabled: bool, ) -> RouterResult<TokenizationAction> { if matches!( payment_intent_data.split_payments, Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(_)) ) { Ok(TokenizationAction::TokenizeInConnector) } else { match pm_parent_token { None => Ok(if is_connector_tokenization_enabled { TokenizationAction::TokenizeInConnectorAndRouter } else { TokenizationAction::TokenizeInRouter }), Some(token) => { 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_{}_{}_{}", token.to_owned(), payment_method, connector_name ); let connector_token_option = redis_conn .get_key::<Option<String>>(&key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch the token from redis")?; match connector_token_option { Some(connector_token) => { Ok(TokenizationAction::ConnectorToken(connector_token)) } None => Ok(if is_connector_tokenization_enabled { TokenizationAction::TokenizeInConnectorAndRouter } else { TokenizationAction::TokenizeInRouter }), } } } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct PazePaymentProcessingDetails { pub paze_private_key: Secret<String>, pub paze_private_key_passphrase: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayPaymentProcessingDetails { pub google_pay_private_key: Secret<String>, pub google_pay_root_signing_keys: Secret<String>, pub google_pay_recipient_id: Secret<String>, } #[cfg(feature = "v1")] #[derive(Clone, Debug)] pub enum TokenizationAction { TokenizeInRouter, TokenizeInConnector, TokenizeInConnectorAndRouter, ConnectorToken(String), SkipConnectorTokenization, } #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub enum TokenizationAction { TokenizeInConnector, SkipConnectorTokenization, } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn get_connector_tokenization_action_when_confirm_true<F, Req, D>( state: &SessionState, operation: &BoxedOperation<'_, F, Req, D>, payment_data: &mut D, validate_result: &operations::ValidateResult, merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, should_retry_with_pan: bool, ) -> RouterResult<(D, TokenizationAction)> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let connector = payment_data.get_payment_attempt().connector.to_owned(); let is_mandate = payment_data .get_mandate_id() .as_ref() .and_then(|inner| inner.mandate_reference_id.as_ref()) .map(|mandate_reference| match mandate_reference { api_models::payments::MandateReferenceId::ConnectorMandateId(_) => true, api_models::payments::MandateReferenceId::NetworkMandateId(_) | api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_) => false, }) .unwrap_or(false); let payment_data_and_tokenization_action = match connector { Some(_) if is_mandate => ( payment_data.to_owned(), TokenizationAction::SkipConnectorTokenization, ), Some(connector) if is_operation_confirm(&operation) => { let payment_method = payment_data .get_payment_attempt() .payment_method .get_required_value("payment_method")?; let payment_method_type = payment_data.get_payment_attempt().payment_method_type; let mandate_flow_enabled = payment_data .get_payment_attempt() .setup_future_usage_applied; let is_connector_tokenization_enabled = is_payment_method_tokenization_enabled_for_connector( state, &connector, payment_method, payment_method_type, payment_data.get_payment_method_token(), mandate_flow_enabled, )?; let payment_method_action = decide_payment_method_tokenize_action( state, &connector, payment_method, payment_data.get_payment_intent().clone(), payment_data.get_token(), is_connector_tokenization_enabled, ) .await?; let connector_tokenization_action = match payment_method_action { TokenizationAction::TokenizeInRouter => { let (_operation, payment_method_data, pm_id) = operation .to_domain()? .make_pm_data( state, payment_data, validate_result.storage_scheme, merchant_key_store, customer, business_profile, should_retry_with_pan, ) .await?; payment_data.set_payment_method_data(payment_method_data); payment_data.set_payment_method_id_in_attempt(pm_id); TokenizationAction::SkipConnectorTokenization } TokenizationAction::TokenizeInConnector => TokenizationAction::TokenizeInConnector, TokenizationAction::TokenizeInConnectorAndRouter => { let (_operation, payment_method_data, pm_id) = operation .to_domain()? .make_pm_data( state, payment_data, validate_result.storage_scheme, merchant_key_store, customer, business_profile, should_retry_with_pan, ) .await?; payment_data.set_payment_method_data(payment_method_data); payment_data.set_payment_method_id_in_attempt(pm_id); TokenizationAction::TokenizeInConnector } TokenizationAction::ConnectorToken(token) => { payment_data.set_pm_token(token); TokenizationAction::SkipConnectorTokenization } TokenizationAction::SkipConnectorTokenization => { TokenizationAction::SkipConnectorTokenization } }; (payment_data.to_owned(), connector_tokenization_action) } _ => ( payment_data.to_owned(), TokenizationAction::SkipConnectorTokenization, ), }; Ok(payment_data_and_tokenization_action) } #[cfg(feature = "v2")] pub async fn tokenize_in_router_when_confirm_false_or_external_authentication<F, Req, D>( state: &SessionState, operation: &BoxedOperation<'_, F, Req, D>, payment_data: &mut D, validate_result: &operations::ValidateResult, merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, ) -> RouterResult<D> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { todo!() } #[cfg(feature = "v1")] pub async fn tokenize_in_router_when_confirm_false_or_external_authentication<F, Req, D>( state: &SessionState, operation: &BoxedOperation<'_, F, Req, D>, payment_data: &mut D, validate_result: &operations::ValidateResult, merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, ) -> RouterResult<D> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { // On confirm is false and only router related let is_external_authentication_requested = payment_data .get_payment_intent() .request_external_three_ds_authentication; let payment_data = if !is_operation_confirm(operation) || is_external_authentication_requested == Some(true) { let (_operation, payment_method_data, pm_id) = operation .to_domain()? .make_pm_data( state, payment_data, validate_result.storage_scheme, merchant_key_store, customer, business_profile, false, ) .await?; payment_data.set_payment_method_data(payment_method_data); if let Some(payment_method_id) = pm_id { payment_data.set_payment_method_id_in_attempt(Some(payment_method_id)); } payment_data } else { payment_data }; Ok(payment_data.to_owned()) } #[derive(Clone)] pub struct MandateConnectorDetails { pub connector: String, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, } #[derive(Clone)] pub struct PaymentData<F> where F: Clone, { pub flow: PhantomData<F>, pub payment_intent: storage::PaymentIntent, pub payment_attempt: storage::PaymentAttempt, pub multiple_capture_data: Option<types::MultipleCaptureData>, pub amount: api::Amount, pub mandate_id: Option<api_models::payments::MandateIds>, pub mandate_connector: Option<MandateConnectorDetails>, pub currency: storage_enums::Currency, pub setup_mandate: Option<MandateData>, pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, pub address: PaymentAddress, pub token: Option<String>, 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_token: Option<PaymentMethodToken>, pub payment_method_info: Option<domain::PaymentMethod>, pub refunds: Vec<diesel_refund::Refund>, pub disputes: Vec<storage::Dispute>, pub attempts: Option<Vec<storage::PaymentAttempt>>, pub sessions_token: Vec<api::SessionToken>, pub card_cvc: Option<Secret<String>>, pub email: Option<pii::Email>, pub creds_identifier: Option<String>, pub pm_token: Option<String>, pub connector_customer_id: Option<String>, pub recurring_mandate_payment_data: Option<hyperswitch_domain_models::router_data::RecurringMandatePaymentData>, pub ephemeral_key: Option<ephemeral_key::EphemeralKey>, pub redirect_response: Option<api_models::payments::RedirectResponse>, pub surcharge_details: Option<types::SurchargeDetails>, pub frm_message: Option<FraudCheck>, pub payment_link_data: Option<api_models::payments::PaymentLinkResponse>, pub incremental_authorization_details: Option<IncrementalAuthorizationDetails>, pub authorizations: Vec<diesel_models::authorization::Authorization>, pub authentication: Option<domain::authentication::AuthenticationStore>, pub recurring_details: Option<RecurringDetails>, pub poll_config: Option<router_types::PollConfig>, pub tax_data: Option<TaxData>, pub session_id: Option<String>, pub service_details: Option<api_models::payments::CtpServiceDetails>, pub card_testing_guard_data: 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<Secret<String>>, pub is_manual_retry_enabled: Option<bool>, pub is_l2_l3_enabled: bool, } #[cfg(feature = "v1")] #[derive(Clone)] pub struct PaymentEligibilityData { pub payment_method_data: Option<domain::PaymentMethodData>, pub payment_intent: storage::PaymentIntent, pub browser_info: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v1")] impl PaymentEligibilityData { pub async fn from_request( state: &SessionState, merchant_context: &domain::MerchantContext, payments_eligibility_request: &api_models::payments::PaymentsEligibilityRequest, ) -> CustomResult<Self, errors::ApiErrorResponse> { let key_manager_state = &(state).into(); let payment_method_data = payments_eligibility_request .payment_method_data .payment_method_data .clone() .map(domain::PaymentMethodData::from); let browser_info = payments_eligibility_request .browser_info .clone() .map(|browser_info| { serde_json::to_value(browser_info) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encode payout method data") }) .transpose()? .map(pii::SecretSerdeValue::new); let payment_intent = state .store .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payments_eligibility_request.payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; Ok(Self { payment_method_data, browser_info, payment_intent, }) } } #[derive(Clone, serde::Serialize, Debug)] pub struct TaxData { pub shipping_details: hyperswitch_domain_models::address::Address, pub payment_method_type: enums::PaymentMethodType, } #[derive(Clone, serde::Serialize, Debug)] pub struct PaymentEvent { payment_intent: storage::PaymentIntent, payment_attempt: storage::PaymentAttempt, } impl<F: Clone> PaymentData<F> { // Get the method by which a card is discovered during a payment #[cfg(feature = "v1")] fn get_card_discovery_for_card_payment_method(&self) -> Option<common_enums::CardDiscovery> { match self.payment_attempt.payment_method { Some(storage_enums::PaymentMethod::Card) => { if self .token_data .as_ref() .map(storage::PaymentTokenData::is_permanent_card) .unwrap_or(false) { Some(common_enums::CardDiscovery::SavedCard) } else if self.service_details.is_some() { Some(common_enums::CardDiscovery::ClickToPay) } else { Some(common_enums::CardDiscovery::Manual) } } _ => None, } } fn to_event(&self) -> PaymentEvent { PaymentEvent { payment_intent: self.payment_intent.clone(), payment_attempt: self.payment_attempt.clone(), } } } impl EventInfo for PaymentEvent { type Data = Self; fn data(&self) -> error_stack::Result<Self::Data, events::EventsError> { Ok(self.clone()) } fn key(&self) -> String { "payment".to_string() } } #[derive(Debug, Default, Clone)] pub struct IncrementalAuthorizationDetails { pub additional_amount: MinorUnit, pub total_amount: MinorUnit, pub reason: Option<String>, pub authorization_id: Option<String>, } pub async fn get_payment_link_response_from_id( state: &SessionState, payment_link_id: &str, ) -> CustomResult<api_models::payments::PaymentLinkResponse, errors::ApiErrorResponse> { let db = &*state.store; let payment_link_object = db .find_payment_link_by_payment_link_id(payment_link_id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?; Ok(api_models::payments::PaymentLinkResponse { link: payment_link_object.link_to_pay.clone(), secure_link: payment_link_object.secure_link, payment_link_id: payment_link_object.payment_link_id, }) } #[cfg(feature = "v1")] pub fn if_not_create_change_operation<'a, Op, F>( status: storage_enums::IntentStatus, confirm: Option<bool>, current: &'a Op, ) -> BoxedOperation<'a, F, api::PaymentsRequest, PaymentData<F>> where F: Send + Clone + Sync, Op: Operation<F, api::PaymentsRequest, Data = PaymentData<F>> + Send + Sync, &'a Op: Operation<F, api::PaymentsRequest, Data = PaymentData<F>>, PaymentStatus: Operation<F, api::PaymentsRequest, Data = PaymentData<F>>, &'a PaymentStatus: Operation<F, api::PaymentsRequest, Data = PaymentData<F>>, { if confirm.unwrap_or(false) { Box::new(PaymentConfirm) } else { match status { storage_enums::IntentStatus::RequiresConfirmation | storage_enums::IntentStatus::RequiresCustomerAction | storage_enums::IntentStatus::RequiresPaymentMethod => Box::new(current), _ => Box::new(&PaymentStatus), } } } #[cfg(feature = "v1")] pub fn is_confirm<'a, F: Clone + Send, R, Op>( operation: &'a Op, confirm: Option<bool>, ) -> BoxedOperation<'a, F, R, PaymentData<F>> where PaymentConfirm: Operation<F, R, Data = PaymentData<F>>, &'a PaymentConfirm: Operation<F, R, Data = PaymentData<F>>, Op: Operation<F, R, Data = PaymentData<F>> + Send + Sync, &'a Op: Operation<F, R, Data = PaymentData<F>>, { if confirm.unwrap_or(false) { Box::new(&PaymentConfirm) } else { Box::new(operation) } } #[cfg(feature = "v1")] pub fn should_call_connector<Op: Debug, F: Clone, D>(operation: &Op, payment_data: &D) -> bool where D: OperationSessionGetters<F> + Send + Sync + Clone, { match format!("{operation:?}").as_str() { "PaymentConfirm" => true, "PaymentStart" => { !matches!( payment_data.get_payment_intent().status, storage_enums::IntentStatus::Failed | storage_enums::IntentStatus::Succeeded ) && payment_data .get_payment_attempt() .authentication_data .is_none() } "PaymentStatus" => { 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, storage_enums::IntentStatus::RequiresCapture | storage_enums::IntentStatus::PartiallyCapturedAndCapturable ), "PaymentCancelPostCapture" => matches!( payment_data.get_payment_intent().status, storage_enums::IntentStatus::Succeeded | storage_enums::IntentStatus::PartiallyCaptured | storage_enums::IntentStatus::PartiallyCapturedAndCapturable ), "PaymentCapture" => { matches!( payment_data.get_payment_intent().status, storage_enums::IntentStatus::RequiresCapture | storage_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | storage_enums::IntentStatus::PartiallyCapturedAndCapturable ) || (matches!( payment_data.get_payment_intent().status, storage_enums::IntentStatus::Processing ) && matches!( payment_data.get_capture_method(), Some(storage_enums::CaptureMethod::ManualMultiple) )) } "CompleteAuthorize" => true, "PaymentApprove" => true, "PaymentReject" => true, "PaymentSession" => true, "PaymentSessionUpdate" => true, "PaymentPostSessionTokens" => true, "PaymentUpdateMetadata" => true, "PaymentExtendAuthorization" => matches!( payment_data.get_payment_intent().status, storage_enums::IntentStatus::RequiresCapture | storage_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture ), "PaymentIncrementalAuthorization" => matches!( payment_data.get_payment_intent().status, storage_enums::IntentStatus::RequiresCapture ), _ => false, } } pub fn is_operation_confirm<Op: Debug>(operation: &Op) -> bool { matches!(format!("{operation:?}").as_str(), "PaymentConfirm") } pub fn is_operation_complete_authorize<Op: Debug>(operation: &Op) -> bool { matches!(format!("{operation:?}").as_str(), "CompleteAuthorize") } #[cfg(all(feature = "olap", feature = "v1"))] pub async fn list_payments( state: SessionState, merchant_context: domain::MerchantContext, profile_id_list: Option<Vec<id_type::ProfileId>>, constraints: api::PaymentListConstraints, ) -> RouterResponse<api::PaymentListResponse> { helpers::validate_payment_list_request(&constraints)?; let merchant_id = merchant_context.get_merchant_account().get_id(); let db = state.store.as_ref(); let payment_intents = helpers::filter_by_constraints( &state, &(constraints, profile_id_list).try_into()?, merchant_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let collected_futures = payment_intents.into_iter().map(|pi| { async { match db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &pi.payment_id, merchant_id, &pi.active_attempt.get_id(), // since OLAP doesn't have KV. Force to get the data from PSQL. storage_enums::MerchantStorageScheme::PostgresOnly, ) .await { Ok(pa) => Some(Ok((pi, pa))), Err(error) => { if matches!( error.current_context(), errors::StorageError::ValueNotFound(_) ) { logger::warn!( ?error, "payment_attempts missing for payment_id : {:?}", pi.payment_id, ); return None; } Some(Err(error)) } } } }); //If any of the response are Err, we will get Result<Err(_)> let pi_pa_tuple_vec: Result<Vec<(storage::PaymentIntent, storage::PaymentAttempt)>, _> = join_all(collected_futures) .await .into_iter() .flatten() //Will ignore `None`, will only flatten 1 level .collect::<Result<Vec<(storage::PaymentIntent, storage::PaymentAttempt)>, _>>(); //Will collect responses in same order async, leading to sorted responses //Converting Intent-Attempt array to Response if no error let data: Vec<api::PaymentsResponse> = pi_pa_tuple_vec .change_context(errors::ApiErrorResponse::InternalServerError)? .into_iter() .map(ForeignFrom::foreign_from) .collect(); Ok(services::ApplicationResponse::Json( api::PaymentListResponse { size: data.len(), data, }, )) } #[cfg(all(feature = "v2", feature = "olap"))] pub async fn list_payments( state: SessionState, merchant_context: domain::MerchantContext, constraints: api::PaymentListConstraints, ) -> RouterResponse<payments_api::PaymentListResponse> { common_utils::metrics::utils::record_operation_time( async { let limit = &constraints.limit; helpers::validate_payment_list_request_for_joins(*limit)?; let db: &dyn StorageInterface = state.store.as_ref(); let fetch_constraints = constraints.clone().into(); let list: Vec<(storage::PaymentIntent, Option<storage::PaymentAttempt>)> = db .get_filtered_payment_intents_attempt( &(&state).into(), merchant_context.get_merchant_account().get_id(), &fetch_constraints, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let data: Vec<api_models::payments::PaymentsListResponseItem> = list.into_iter().map(ForeignFrom::foreign_from).collect(); let active_attempt_ids = db .get_filtered_active_attempt_ids_for_total_count( merchant_context.get_merchant_account().get_id(), &fetch_constraints, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while retrieving active_attempt_ids for merchant")?; let total_count = if constraints.has_no_attempt_filters() { i64::try_from(active_attempt_ids.len()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while converting from usize to i64") } else { let active_attempt_ids = active_attempt_ids .into_iter() .flatten() .collect::<Vec<String>>(); db.get_total_count_of_filtered_payment_attempts( merchant_context.get_merchant_account().get_id(), &active_attempt_ids, constraints.connector, constraints.payment_method_type, constraints.payment_method_subtype, constraints.authentication_type, constraints.merchant_connector_id, constraints.card_network, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while retrieving total count of payment attempts") }?; Ok(services::ApplicationResponse::Json( api_models::payments::PaymentListResponse { count: data.len(), total_count, data, }, )) }, &metrics::PAYMENT_LIST_LATENCY, router_env::metric_attributes!(( "merchant_id", merchant_context.get_merchant_account().get_id().clone() )), ) .await } #[cfg(all(feature = "olap", feature = "v1"))] pub async fn apply_filters_on_payments( state: SessionState, merchant_context: domain::MerchantContext, profile_id_list: Option<Vec<id_type::ProfileId>>, constraints: api::PaymentListFilterConstraints, ) -> RouterResponse<api::PaymentListResponseV2> { common_utils::metrics::utils::record_operation_time( async { let limit = &constraints.limit; helpers::validate_payment_list_request_for_joins(*limit)?; let db: &dyn StorageInterface = state.store.as_ref(); let pi_fetch_constraints = (constraints.clone(), profile_id_list.clone()).try_into()?; let list: Vec<(storage::PaymentIntent, storage::PaymentAttempt)> = db .get_filtered_payment_intents_attempt( &(&state).into(), merchant_context.get_merchant_account().get_id(), &pi_fetch_constraints, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let data: Vec<api::PaymentsResponse> = list.into_iter().map(ForeignFrom::foreign_from).collect(); let active_attempt_ids = db .get_filtered_active_attempt_ids_for_total_count( merchant_context.get_merchant_account().get_id(), &pi_fetch_constraints, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; let total_count = if constraints.has_no_attempt_filters() { i64::try_from(active_attempt_ids.len()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while converting from usize to i64") } else { db.get_total_count_of_filtered_payment_attempts( merchant_context.get_merchant_account().get_id(), &active_attempt_ids, constraints.connector, constraints.payment_method, constraints.payment_method_type, constraints.authentication_type, constraints.merchant_connector_id, constraints.card_network, constraints.card_discovery, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) }?; Ok(services::ApplicationResponse::Json( api::PaymentListResponseV2 { count: data.len(), total_count, data, }, )) }, &metrics::PAYMENT_LIST_LATENCY, router_env::metric_attributes!(( "merchant_id", merchant_context.get_merchant_account().get_id().clone() )), ) .await } #[cfg(all(feature = "olap", feature = "v1"))] pub async fn get_filters_for_payments( state: SessionState, merchant_context: domain::MerchantContext, time_range: common_utils::types::TimeRange, ) -> RouterResponse<api::PaymentListFilters> { let db = state.store.as_ref(); let pi = db .filter_payment_intents_by_time_range_constraints( &(&state).into(), merchant_context.get_merchant_account().get_id(), &time_range, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let filters = db .get_filters_for_payments( pi.as_slice(), merchant_context.get_merchant_account().get_id(), // since OLAP doesn't have KV. Force to get the data from PSQL. storage_enums::MerchantStorageScheme::PostgresOnly, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; Ok(services::ApplicationResponse::Json( api::PaymentListFilters { connector: filters.connector, currency: filters.currency, status: filters.status, payment_method: filters.payment_method, payment_method_type: filters.payment_method_type, authentication_type: filters.authentication_type, }, )) } #[cfg(feature = "olap")] pub async fn get_payment_filters( state: SessionState, merchant_context: domain::MerchantContext, profile_id_list: Option<Vec<id_type::ProfileId>>, ) -> RouterResponse<api::PaymentListFiltersV2> { let merchant_connector_accounts = if let services::ApplicationResponse::Json(data) = super::admin::list_payment_connectors( state, merchant_context.get_merchant_account().get_id().to_owned(), profile_id_list, ) .await? { data } else { return Err(errors::ApiErrorResponse::InternalServerError.into()); }; let mut connector_map: HashMap<String, Vec<MerchantConnectorInfo>> = HashMap::new(); let mut payment_method_types_map: HashMap< enums::PaymentMethod, HashSet<enums::PaymentMethodType>, > = HashMap::new(); // populate connector map merchant_connector_accounts .iter() .filter_map(|merchant_connector_account| { merchant_connector_account .connector_label .as_ref() .map(|label| { let info = merchant_connector_account.to_merchant_connector_info(label); (merchant_connector_account.get_connector_name(), info) }) }) .for_each(|(connector_name, info)| { connector_map .entry(connector_name.to_string()) .or_default() .push(info); }); // populate payment method type map merchant_connector_accounts .iter() .flat_map(|merchant_connector_account| { merchant_connector_account.payment_methods_enabled.as_ref() }) .map(|payment_methods_enabled| { payment_methods_enabled .iter() .filter_map(|payment_method_enabled| { payment_method_enabled .get_payment_method_type() .map(|types_vec| { ( payment_method_enabled.get_payment_method(), types_vec.clone(), ) }) }) }) .for_each(|payment_methods_enabled| { payment_methods_enabled.for_each( |(payment_method_option, payment_method_types_vec)| { if let Some(payment_method) = payment_method_option { payment_method_types_map .entry(payment_method) .or_default() .extend(payment_method_types_vec.iter().filter_map( |req_payment_method_types| { req_payment_method_types.get_payment_method_type() }, )); } }, ); }); Ok(services::ApplicationResponse::Json( api::PaymentListFiltersV2 { connector: connector_map, currency: enums::Currency::iter().collect(), status: enums::IntentStatus::iter().collect(), payment_method: payment_method_types_map, authentication_type: enums::AuthenticationType::iter().collect(), card_network: enums::CardNetwork::iter().collect(), card_discovery: enums::CardDiscovery::iter().collect(), }, )) } #[cfg(feature = "olap")] pub async fn get_aggregates_for_payments( state: SessionState, merchant_context: domain::MerchantContext, profile_id_list: Option<Vec<id_type::ProfileId>>, time_range: common_utils::types::TimeRange, ) -> RouterResponse<api::PaymentsAggregateResponse> { let db = state.store.as_ref(); let intent_status_with_count = db .get_intent_status_with_count( merchant_context.get_merchant_account().get_id(), profile_id_list, &time_range, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let mut status_map: HashMap<enums::IntentStatus, i64> = intent_status_with_count.into_iter().collect(); for status in enums::IntentStatus::iter() { status_map.entry(status).or_default(); } Ok(services::ApplicationResponse::Json( api::PaymentsAggregateResponse { status_with_count: status_map, }, )) } #[cfg(feature = "v1")] pub async fn add_process_sync_task( db: &dyn StorageInterface, payment_attempt: &storage::PaymentAttempt, schedule_time: time::PrimitiveDateTime, ) -> CustomResult<(), errors::StorageError> { let tracking_data = api::PaymentsRetrieveRequest { force_sync: true, merchant_id: Some(payment_attempt.merchant_id.clone()), resource_id: api::PaymentIdType::PaymentAttemptId(payment_attempt.get_id().to_owned()), ..Default::default() }; let runner = storage::ProcessTrackerRunner::PaymentsSyncWorkflow; let task = "PAYMENTS_SYNC"; let tag = ["SYNC", "PAYMENT"]; let process_tracker_id = pt_utils::get_process_tracker_id( runner, task, payment_attempt.get_id(), &payment_attempt.merchant_id, ); let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, tracking_data, None, schedule_time, common_types::consts::API_VERSION, ) .map_err(errors::StorageError::from)?; db.insert_process(process_tracker_entry).await?; Ok(()) } #[cfg(feature = "v2")] pub async fn reset_process_sync_task( db: &dyn StorageInterface, payment_attempt: &storage::PaymentAttempt, schedule_time: time::PrimitiveDateTime, ) -> Result<(), errors::ProcessTrackerError> { todo!() } #[cfg(feature = "v1")] pub async fn reset_process_sync_task( db: &dyn StorageInterface, payment_attempt: &storage::PaymentAttempt, schedule_time: time::PrimitiveDateTime, ) -> Result<(), errors::ProcessTrackerError> { let runner = storage::ProcessTrackerRunner::PaymentsSyncWorkflow; let task = "PAYMENTS_SYNC"; let process_tracker_id = pt_utils::get_process_tracker_id( runner, task, payment_attempt.get_id(), &payment_attempt.merchant_id, ); let psync_process = db .find_process_by_id(&process_tracker_id) .await? .ok_or(errors::ProcessTrackerError::ProcessFetchingFailed)?; db.as_scheduler() .reset_process(psync_process, schedule_time) .await?; Ok(()) } #[cfg(feature = "v1")] pub fn update_straight_through_routing<F, D>( payment_data: &mut D, request_straight_through: serde_json::Value, ) -> CustomResult<(), errors::ParsingError> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let _: api_models::routing::StaticRoutingAlgorithm = request_straight_through .clone() .parse_value("RoutingAlgorithm") .attach_printable("Invalid straight through routing rules format")?; payment_data.set_straight_through_algorithm_in_payment_attempt(request_straight_through); Ok(()) } #[cfg(feature = "v1")] pub fn is_pre_network_tokenization_enabled( state: &SessionState, business_profile: &domain::Profile, customer_acceptance: Option<Secret<serde_json::Value>>, connector_name: enums::Connector, ) -> bool { let ntid_supported_connectors = &state .conf .network_transaction_id_supported_connectors .connector_list; let is_nt_supported_connector = ntid_supported_connectors.contains(&connector_name); business_profile.is_network_tokenization_enabled && business_profile.is_pre_network_tokenization_enabled && customer_acceptance.is_some() && is_nt_supported_connector } #[cfg(feature = "v1")] pub async fn get_vault_operation_for_pre_network_tokenization( state: &SessionState, customer_id: id_type::CustomerId, card_data: &hyperswitch_domain_models::payment_method_data::Card, ) -> payments::VaultOperation { let pre_tokenization_response = tokenization::pre_payment_tokenization(state, customer_id, card_data) .await .ok(); match pre_tokenization_response { Some((Some(token_response), Some(token_ref))) => { let token_data = domain::NetworkTokenData::from(token_response); let network_token_data_for_vault = payments::NetworkTokenDataForVault { network_token_data: token_data.clone(), network_token_req_ref_id: token_ref, }; payments::VaultOperation::SaveCardAndNetworkTokenData(Box::new( payments::CardAndNetworkTokenDataForVault { card_data: card_data.clone(), network_token: network_token_data_for_vault.clone(), }, )) } Some((None, Some(token_ref))) => { payments::VaultOperation::SaveCardData(payments::CardDataForVault { card_data: card_data.clone(), network_token_req_ref_id: Some(token_ref), }) } _ => payments::VaultOperation::SaveCardData(payments::CardDataForVault { card_data: card_data.clone(), network_token_req_ref_id: None, }), } } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn get_connector_choice<F, Req, D>( operation: &BoxedOperation<'_, F, Req, D>, state: &SessionState, req: &Req, merchant_context: &domain::MerchantContext, business_profile: &domain::Profile, payment_data: &mut D, eligible_connectors: Option<Vec<enums::RoutableConnectors>>, mandate_type: Option<api::MandateTransactionType>, ) -> RouterResult<Option<ConnectorCallType>> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let connector_choice = operation .to_domain()? .get_connector( merchant_context, &state.clone(), req, payment_data.get_payment_intent(), ) .await?; let connector = if should_call_connector(operation, payment_data) { Some(match connector_choice { api::ConnectorChoice::SessionMultiple(connectors) => { let routing_output = perform_session_token_routing( state.clone(), merchant_context, business_profile, payment_data, connectors, ) .await?; ConnectorCallType::SessionMultiple(routing_output) } api::ConnectorChoice::StraightThrough(straight_through) => { connector_selection( state, merchant_context, business_profile, payment_data, Some(straight_through), eligible_connectors, mandate_type, ) .await? } api::ConnectorChoice::Decide => { connector_selection( state, merchant_context, business_profile, payment_data, None, eligible_connectors, mandate_type, ) .await? } }) } else if let api::ConnectorChoice::StraightThrough(algorithm) = connector_choice { update_straight_through_routing(payment_data, algorithm) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update straight through routing algorithm")?; None } else { None }; Ok(connector) } async fn get_eligible_connector_for_nti<T: core_routing::GetRoutableConnectorsForChoice, F, D>( state: &SessionState, key_store: &domain::MerchantKeyStore, payment_data: &D, connector_choice: T, business_profile: &domain::Profile, ) -> RouterResult<( api_models::payments::MandateReferenceId, hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId, api::ConnectorData, )> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { // Since this flow will only be used in the MIT flow, recurring details are mandatory. let recurring_payment_details = payment_data .get_recurring_details() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("Failed to fetch recurring details for mit")?; let (mandate_reference_id, card_details_for_network_transaction_id)= hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId::get_nti_and_card_details_for_mit_flow(recurring_payment_details.clone()).get_required_value("network transaction id and card details").attach_printable("Failed to fetch network transaction id and card details for mit")?; helpers::validate_card_expiry( &card_details_for_network_transaction_id.card_exp_month, &card_details_for_network_transaction_id.card_exp_year, )?; let network_transaction_id_supported_connectors = &state .conf .network_transaction_id_supported_connectors .connector_list .iter() .map(|value| value.to_string()) .collect::<HashSet<_>>(); let eligible_connector_data_list = connector_choice .get_routable_connectors(&*state.store, business_profile) .await? .filter_network_transaction_id_flow_supported_connectors( network_transaction_id_supported_connectors.to_owned(), ) .construct_dsl_and_perform_eligibility_analysis( state, key_store, payment_data, business_profile.get_id(), ) .await .attach_printable("Failed to fetch eligible connector data")?; let eligible_connector_data = eligible_connector_data_list .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable( "No eligible connector found for the network transaction id based mit flow", )?; Ok(( mandate_reference_id, card_details_for_network_transaction_id, eligible_connector_data.clone(), )) } pub async fn set_eligible_connector_for_nti_in_payment_data<F, D>( state: &SessionState, business_profile: &domain::Profile, key_store: &domain::MerchantKeyStore, payment_data: &mut D, connector_choice: api::ConnectorChoice, ) -> RouterResult<api::ConnectorData> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let (mandate_reference_id, card_details_for_network_transaction_id, eligible_connector_data) = match connector_choice { api::ConnectorChoice::StraightThrough(straight_through) => { get_eligible_connector_for_nti( state, key_store, payment_data, core_routing::StraightThroughAlgorithmTypeSingle(straight_through), business_profile, ) .await? } api::ConnectorChoice::Decide => { get_eligible_connector_for_nti( state, key_store, payment_data, core_routing::DecideConnector, business_profile, ) .await? } api::ConnectorChoice::SessionMultiple(_) => { Err(errors::ApiErrorResponse::InternalServerError).attach_printable( "Invalid routing rule configured for nti and card details based mit flow", )? } }; // Set the eligible connector in the attempt payment_data .set_connector_in_payment_attempt(Some(eligible_connector_data.connector_name.to_string())); // Set `NetworkMandateId` as the MandateId payment_data.set_mandate_id(payments_api::MandateIds { mandate_id: None, mandate_reference_id: Some(mandate_reference_id), }); // Set the card details received in the recurring details within the payment method data. payment_data.set_payment_method_data(Some( hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardDetailsForNetworkTransactionId(card_details_for_network_transaction_id), )); Ok(eligible_connector_data) } #[cfg(feature = "v1")] #[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<serde_json::Value>, 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, { let request_straight_through: Option<api::routing::StraightThroughAlgorithm> = request_straight_through .map(|val| val.parse_value("RoutingAlgorithm")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid straight through routing rules format")?; 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(), algorithm: request_straight_through.clone(), routing_info: payment_data .get_payment_attempt() .straight_through_algorithm .clone() .map(|val| val.parse_value("PaymentRoutingInfo")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid straight through algorithm format found in payment attempt")? .unwrap_or(storage::PaymentRoutingInfo { algorithm: None, pre_routing_results: None, }), }; let decided_connector = decide_connector( state.clone(), merchant_context, business_profile, payment_data, request_straight_through, &mut routing_data, eligible_connectors, mandate_type, ) .await?; let encoded_info = routing_data .routing_info .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error serializing payment routing info to serde value")?; payment_data.set_connector_in_payment_attempt(routing_data.routed_through); payment_data.set_merchant_connector_id_in_attempt(routing_data.merchant_connector_id); payment_data.set_straight_through_algorithm_in_payment_attempt(encoded_info); Ok(decided_connector) } #[cfg(feature = "v2")] #[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, mandate_type: Option<api::MandateTransactionType>, ) -> RouterResult<ConnectorCallType> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { 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)] #[cfg(feature = "v1")] pub async fn decide_connector<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, { // 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. if let Some(ref connector_name) = payment_data.get_payment_attempt().connector { // Connector was already decided previously, use the same connector let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, payment_data .get_payment_attempt() .merchant_connector_id .clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received in 'routed_through'")?; routing_data.routed_through = Some(connector_name.clone()); logger::debug!("euclid_routing: predetermined connector present in attempt"); return Ok(ConnectorCallType::PreDetermined(connector_data.into())); } if let Some(mandate_connector_details) = payment_data.get_mandate_connector().as_ref() { let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &mandate_connector_details.connector, api::GetToken::Connector, mandate_connector_details.merchant_connector_id.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received in 'routed_through'")?; routing_data.routed_through = Some(mandate_connector_details.connector.clone()); routing_data .merchant_connector_id .clone_from(&mandate_connector_details.merchant_connector_id); logger::debug!("euclid_routing: predetermined mandate connector"); return Ok(ConnectorCallType::PreDetermined(connector_data.into())); } if let Some((pre_routing_results, storage_pm_type)) = routing_data.routing_info.pre_routing_results.as_ref().zip( payment_data .get_payment_attempt() .payment_method_type .as_ref(), ) { if let (Some(routable_connector_choice), None) = ( pre_routing_results.get(storage_pm_type), &payment_data.get_token_data(), ) { 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() } }; let mut pre_routing_connector_data_list = vec![]; let first_routable_connector = routable_connector_list .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?; routing_data.routed_through = Some(first_routable_connector.connector.to_string()); routing_data .merchant_connector_id .clone_from(&first_routable_connector.merchant_connector_id); for connector_choice in routable_connector_list.clone() { let connector_data = 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")? .into(); pre_routing_connector_data_list.push(connector_data); } #[cfg(feature = "retry")] let should_do_retry = retry::config_should_call_gsm( &*state.store, merchant_context.get_merchant_account().get_id(), business_profile, ) .await; #[cfg(feature = "retry")] if payment_data.get_payment_attempt().payment_method_type == Some(storage_enums::PaymentMethodType::ApplePay) && should_do_retry { let retryable_connector_data = helpers::get_apple_pay_retryable_connectors( &state, merchant_context, payment_data, &pre_routing_connector_data_list, first_routable_connector .merchant_connector_id .clone() .as_ref(), business_profile.clone(), ) .await?; if let Some(connector_data_list) = retryable_connector_data { if connector_data_list.len() > 1 { logger::info!("Constructed apple pay retryable connector list"); return Ok(ConnectorCallType::Retryable(connector_data_list)); } } } logger::debug!("euclid_routing: pre-routing connector present"); let first_pre_routing_connector_data_list = pre_routing_connector_data_list .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?; helpers::override_setup_future_usage_to_on_session(&*state.store, payment_data).await?; return Ok(ConnectorCallType::PreDetermined( first_pre_routing_connector_data_list.clone(), )); } } if let Some(routing_algorithm) = request_straight_through { let (mut connectors, check_eligibility) = routing::perform_straight_through_routing( &routing_algorithm, payment_data.get_creds_identifier(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed execution of straight through routing")?; payment_data.set_routing_approach_in_attempt(Some( common_enums::RoutingApproach::StraightThroughRouting, )); if check_eligibility { let transaction_data = core_routing::PaymentsDslInput::new( 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(), ); connectors = routing::perform_eligibility_analysis_with_fallback( &state.clone(), merchant_context.get_merchant_key_store(), connectors, &TransactionData::Payment(transaction_data), eligible_connectors, business_profile, ) .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")?; logger::debug!("euclid_routing: straight through connector present"); 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 (mut connectors, check_eligibility) = routing::perform_straight_through_routing( routing_algorithm, payment_data.get_creds_identifier(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed execution of straight through routing")?; if check_eligibility { let transaction_data = core_routing::PaymentsDslInput::new( 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(), ); connectors = routing::perform_eligibility_analysis_with_fallback( &state, merchant_context.get_merchant_key_store(), connectors, &TransactionData::Payment(transaction_data), eligible_connectors, business_profile, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed eligibility analysis and fallback")?; } logger::debug!("euclid_routing: single connector present in algorithm data"); 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(); 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(), ); route_connector_v1_for_payments( &state, merchant_context, business_profile, payment_data, transaction_data, routing_data, eligible_connectors, mandate_type, ) .await } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] 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::ConnectorRoutingData>, mandate_type: Option<api::MandateTransactionType>, is_connector_agnostic_mit_enabled: Option<bool>, is_network_tokenization_enabled: bool, ) -> RouterResult<ConnectorCallType> where D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { match ( payment_data.get_payment_intent().setup_future_usage, payment_data.get_token_data().as_ref(), payment_data.get_recurring_details().as_ref(), payment_data.get_payment_intent().off_session, mandate_type, ) { ( Some(storage_enums::FutureUsage::OffSession), Some(_), None, None, Some(api::MandateTransactionType::RecurringMandateTransaction), ) | ( None, None, Some(RecurringDetails::PaymentMethodId(_)), Some(true), Some(api::MandateTransactionType::RecurringMandateTransaction), ) | (None, Some(_), None, Some(true), _) => { logger::debug!("euclid_routing: performing routing for token-based MIT flow"); let payment_method_info = payment_data .get_payment_method_info() .get_required_value("payment_method_info")? .clone(); let retryable_connectors = join_all(connectors.into_iter().map(|connector_routing_data| { let payment_method = payment_method_info.clone(); async move { let action_types = get_all_action_types( state, is_connector_agnostic_mit_enabled, is_network_tokenization_enabled, &payment_method.clone(), connector_routing_data.connector_data.clone(), ) .await; action_types .into_iter() .map(|action_type| api::ConnectorRoutingData { connector_data: connector_routing_data.connector_data.clone(), action_type: Some(action_type), network: connector_routing_data.network.clone(), }) .collect::<Vec<_>>() } })) .await .into_iter() .flatten() .collect::<Vec<_>>(); let chosen_connector_routing_data = retryable_connectors .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("no eligible connector found for token-based MIT payment")?; let mandate_reference_id = get_mandate_reference_id( chosen_connector_routing_data.action_type.clone(), chosen_connector_routing_data.clone(), payment_data, &payment_method_info, )?; routing_data.routed_through = Some( chosen_connector_routing_data .connector_data .connector_name .to_string(), ); routing_data.merchant_connector_id.clone_from( &chosen_connector_routing_data .connector_data .merchant_connector_id, ); payment_data.set_mandate_id(payments_api::MandateIds { mandate_id: None, mandate_reference_id, }); Ok(ConnectorCallType::Retryable(retryable_connectors)) } ( None, None, Some(RecurringDetails::ProcessorPaymentToken(_token)), Some(true), Some(api::MandateTransactionType::RecurringMandateTransaction), ) => { if let Some(connector) = connectors.first() { let connector = &connector.connector_data; routing_data.routed_through = Some(connector.connector_name.clone().to_string()); routing_data .merchant_connector_id .clone_from(&connector.merchant_connector_id); Ok(ConnectorCallType::PreDetermined( api::ConnectorData { connector: connector.connector.clone(), connector_name: connector.connector_name, get_token: connector.get_token.clone(), merchant_connector_id: connector.merchant_connector_id.clone(), } .into(), )) } else { logger::error!( "euclid_routing: no eligible connector found for the ppt_mandate payment" ); Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration.into()) } } _ => { helpers::override_setup_future_usage_to_on_session(&*state.store, payment_data).await?; let first_choice = connectors .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("no eligible connector found for payment")? .clone(); routing_data.routed_through = Some(first_choice.connector_data.connector_name.to_string()); routing_data.merchant_connector_id = first_choice.connector_data.merchant_connector_id; Ok(ConnectorCallType::Retryable(connectors)) } } } #[cfg(feature = "v1")] pub fn get_mandate_reference_id<F: Clone, D>( action_type: Option<ActionType>, connector_routing_data: api::ConnectorRoutingData, payment_data: &mut D, payment_method_info: &domain::PaymentMethod, ) -> RouterResult<Option<api_models::payments::MandateReferenceId>> where D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let mandate_reference_id = match action_type { Some(ActionType::NetworkTokenWithNetworkTransactionId(network_token_data)) => { logger::info!("using network token with network_transaction_id for MIT flow"); Some(payments_api::MandateReferenceId::NetworkTokenWithNTI( network_token_data.into(), )) } Some(ActionType::CardWithNetworkTransactionId(network_transaction_id)) => { logger::info!("using card with network_transaction_id for MIT flow"); Some(payments_api::MandateReferenceId::NetworkMandateId( network_transaction_id, )) } Some(ActionType::ConnectorMandate(connector_mandate_details)) => { logger::info!("using connector_mandate_id for MIT flow"); let merchant_connector_id = connector_routing_data .connector_data .merchant_connector_id .as_ref() .ok_or_else(|| { report!(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("No eligible connector found for token-based MIT flow: no connector mandate details") })?; let mandate_reference_record = connector_mandate_details .get(merchant_connector_id) .ok_or_else(|| { report!(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("No mandate record found for merchant connector ID") })?; if let Some(mandate_currency) = mandate_reference_record.original_payment_authorized_currency { if mandate_currency != payment_data.get_currency() { return Err(report!(errors::ApiErrorResponse::MandateValidationFailed { reason: "Cross currency mandates not supported".into(), })); } } payment_data.set_recurring_mandate_payment_data(mandate_reference_record.into()); Some(payments_api::MandateReferenceId::ConnectorMandateId( api_models::payments::ConnectorMandateReferenceId::new( Some(mandate_reference_record.connector_mandate_id.clone()), Some(payment_method_info.get_id().clone()), None, mandate_reference_record.mandate_metadata.clone(), mandate_reference_record .connector_mandate_request_reference_id .clone(), ), )) } None => None, }; Ok(mandate_reference_id) } #[cfg(feature = "v1")] #[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::ConnectorRoutingData>, is_connector_agnostic_mit_enabled: Option<bool>, payment_method_info: &domain::PaymentMethod, ) -> RouterResult<ConnectorCallType> where D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let connector_common_mandate_details = payment_method_info .get_common_mandate_reference() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the common mandate reference")?; let connector_mandate_details = connector_common_mandate_details.payments.clone(); let mut connector_choice = None; for connector_info in connectors { let connector_data = connector_info.connector_data; let merchant_connector_id = connector_data .merchant_connector_id .as_ref() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to find the merchant connector id")?; if connector_mandate_details .clone() .map(|connector_mandate_details| { connector_mandate_details.contains_key(merchant_connector_id) }) .unwrap_or(false) { logger::info!("euclid_routing: using connector_mandate_id for MIT flow"); if let Some(merchant_connector_id) = connector_data.merchant_connector_id.as_ref() { if let Some(mandate_reference_record) = connector_mandate_details.clone() .get_required_value("connector_mandate_details") .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("no eligible connector found for token-based MIT flow since there were no connector mandate details")? .get(merchant_connector_id) { common_utils::fp_utils::when( mandate_reference_record .original_payment_authorized_currency .map(|mandate_currency| mandate_currency != payment_data.get_currency()) .unwrap_or(false), || { Err(report!(errors::ApiErrorResponse::MandateValidationFailed { reason: "cross currency mandates not supported".into() })) }, )?; let mandate_reference_id = Some(payments_api::MandateReferenceId::ConnectorMandateId( api_models::payments::ConnectorMandateReferenceId::new( Some(mandate_reference_record.connector_mandate_id.clone()), Some(payment_method_info.get_id().clone()), // update_history None, mandate_reference_record.mandate_metadata.clone(), mandate_reference_record.connector_mandate_request_reference_id.clone(), ) )); payment_data.set_recurring_mandate_payment_data( mandate_reference_record.into(), ); connector_choice = Some((connector_data, mandate_reference_id.clone())); break; } } } else if is_network_transaction_id_flow( state, is_connector_agnostic_mit_enabled, connector_data.connector_name, payment_method_info, ) { logger::info!("using network_transaction_id for MIT flow"); let network_transaction_id = payment_method_info .network_transaction_id .as_ref() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch the network transaction id")?; let mandate_reference_id = Some(payments_api::MandateReferenceId::NetworkMandateId( network_transaction_id.to_string(), )); connector_choice = Some((connector_data, mandate_reference_id.clone())); break; } else { continue; } } let (chosen_connector_data, mandate_reference_id) = connector_choice .get_required_value("connector_choice") .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("no eligible connector found for token-based MIT payment")?; routing_data.routed_through = Some(chosen_connector_data.connector_name.to_string()); routing_data .merchant_connector_id .clone_from(&chosen_connector_data.merchant_connector_id); payment_data.set_mandate_id(payments_api::MandateIds { mandate_id: None, mandate_reference_id, }); Ok(ConnectorCallType::PreDetermined( chosen_connector_data.into(), )) } pub fn filter_ntid_supported_connectors( connectors: Vec<api::ConnectorRoutingData>, ntid_supported_connectors: &HashSet<enums::Connector>, ) -> Vec<api::ConnectorRoutingData> { connectors .into_iter() .filter(|data| ntid_supported_connectors.contains(&data.connector_data.connector_name)) .collect() } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NetworkTokenExpiry { pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NTWithNTIRef { pub network_transaction_id: String, pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } impl From<NTWithNTIRef> for payments_api::NetworkTokenWithNTIRef { fn from(network_token_data: NTWithNTIRef) -> Self { Self { network_transaction_id: network_token_data.network_transaction_id, token_exp_month: network_token_data.token_exp_month, token_exp_year: network_token_data.token_exp_year, } } } // This represents the recurring details of a connector which will be used for retries #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum ActionType { NetworkTokenWithNetworkTransactionId(NTWithNTIRef), CardWithNetworkTransactionId(String), // Network Transaction Id #[cfg(feature = "v1")] ConnectorMandate(hyperswitch_domain_models::mandates::PaymentsMandateReference), } pub fn filter_network_tokenization_supported_connectors( connectors: Vec<api::ConnectorRoutingData>, network_tokenization_supported_connectors: &HashSet<enums::Connector>, ) -> Vec<api::ConnectorRoutingData> { connectors .into_iter() .filter(|data| { network_tokenization_supported_connectors.contains(&data.connector_data.connector_name) }) .collect() } #[cfg(feature = "v1")] #[derive(Default)] pub struct ActionTypesBuilder { action_types: Vec<ActionType>, } #[cfg(feature = "v1")] impl ActionTypesBuilder { pub fn new() -> Self { Self { action_types: Vec::new(), } } pub fn with_mandate_flow( mut self, is_mandate_flow: bool, connector_mandate_details: Option< hyperswitch_domain_models::mandates::PaymentsMandateReference, >, ) -> Self { if is_mandate_flow { self.action_types.extend( connector_mandate_details .map(|details| ActionType::ConnectorMandate(details.to_owned())), ); } self } pub async fn with_network_tokenization( mut self, state: &SessionState, is_network_token_with_ntid_flow: IsNtWithNtiFlow, is_nt_with_ntid_supported_connector: bool, payment_method_info: &domain::PaymentMethod, ) -> Self { match is_network_token_with_ntid_flow { IsNtWithNtiFlow::NtWithNtiSupported(network_transaction_id) if is_nt_with_ntid_supported_connector => { self.action_types.extend( network_tokenization::do_status_check_for_network_token( state, payment_method_info, ) .await .inspect_err(|e| { logger::error!("Status check for network token failed: {:?}", e) }) .ok() .map(|(token_exp_month, token_exp_year)| { ActionType::NetworkTokenWithNetworkTransactionId(NTWithNTIRef { token_exp_month, token_exp_year, network_transaction_id, }) }), ); } _ => (), } self } pub fn with_card_network_transaction_id( mut self, is_card_with_ntid_flow: bool, payment_method_info: &domain::PaymentMethod, ) -> Self { if is_card_with_ntid_flow { self.action_types.extend( payment_method_info .network_transaction_id .as_ref() .map(|ntid| ActionType::CardWithNetworkTransactionId(ntid.clone())), ); } self } pub fn build(self) -> Vec<ActionType> { self.action_types } } #[cfg(feature = "v1")] pub async fn get_all_action_types( state: &SessionState, is_connector_agnostic_mit_enabled: Option<bool>, is_network_tokenization_enabled: bool, payment_method_info: &domain::PaymentMethod, connector: api::ConnectorData, ) -> Vec<ActionType> { let merchant_connector_id = connector.merchant_connector_id.as_ref(); //fetch connectors that support ntid flow let ntid_supported_connectors = &state .conf .network_transaction_id_supported_connectors .connector_list; //fetch connectors that support network tokenization flow let network_tokenization_supported_connectors = &state .conf .network_tokenization_supported_connectors .connector_list; let is_network_token_with_ntid_flow = is_network_token_with_network_transaction_id_flow( is_connector_agnostic_mit_enabled, is_network_tokenization_enabled, payment_method_info, ); let is_card_with_ntid_flow = is_network_transaction_id_flow( state, is_connector_agnostic_mit_enabled, connector.connector_name, payment_method_info, ); let payments_mandate_reference = payment_method_info .get_common_mandate_reference() .map_err(|err| { logger::warn!("Error getting connector mandate details: {:?}", err); err }) .ok() .and_then(|details| details.payments); let is_mandate_flow = payments_mandate_reference .clone() .zip(merchant_connector_id) .map(|(details, merchant_connector_id)| details.contains_key(merchant_connector_id)) .unwrap_or(false); let is_nt_with_ntid_supported_connector = ntid_supported_connectors .contains(&connector.connector_name) && network_tokenization_supported_connectors.contains(&connector.connector_name); ActionTypesBuilder::new() .with_mandate_flow(is_mandate_flow, payments_mandate_reference) .with_network_tokenization( state, is_network_token_with_ntid_flow, is_nt_with_ntid_supported_connector, payment_method_info, ) .await .with_card_network_transaction_id(is_card_with_ntid_flow, payment_method_info) .build() } pub fn is_network_transaction_id_flow( state: &SessionState, is_connector_agnostic_mit_enabled: Option<bool>, connector: enums::Connector, payment_method_info: &domain::PaymentMethod, ) -> bool { let ntid_supported_connectors = &state .conf .network_transaction_id_supported_connectors .connector_list; is_connector_agnostic_mit_enabled == Some(true) && payment_method_info.get_payment_method_type() == Some(storage_enums::PaymentMethod::Card) && ntid_supported_connectors.contains(&connector) && payment_method_info.network_transaction_id.is_some() } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub enum IsNtWithNtiFlow { NtWithNtiSupported(String), //Network token with Network transaction id supported flow NTWithNTINotSupported, //Network token with Network transaction id not supported } pub fn is_network_token_with_network_transaction_id_flow( is_connector_agnostic_mit_enabled: Option<bool>, is_network_tokenization_enabled: bool, payment_method_info: &domain::PaymentMethod, ) -> IsNtWithNtiFlow { match ( is_connector_agnostic_mit_enabled, is_network_tokenization_enabled, payment_method_info.get_payment_method_type(), payment_method_info.network_transaction_id.clone(), payment_method_info.network_token_locker_id.is_some(), payment_method_info .network_token_requestor_reference_id .is_some(), ) { ( Some(true), true, Some(storage_enums::PaymentMethod::Card), Some(network_transaction_id), true, true, ) => IsNtWithNtiFlow::NtWithNtiSupported(network_transaction_id), _ => IsNtWithNtiFlow::NTWithNTINotSupported, } } pub fn should_add_task_to_process_tracker<F: Clone, D: OperationSessionGetters<F>>( payment_data: &D, ) -> bool { let connector = payment_data.get_payment_attempt().connector.as_deref(); !matches!( ( payment_data.get_payment_attempt().get_payment_method(), connector ), ( Some(storage_enums::PaymentMethod::BankTransfer), Some("stripe") ) ) } #[cfg(feature = "v1")] pub async fn perform_session_token_routing<F, D>( state: SessionState, merchant_context: &domain::MerchantContext, business_profile: &domain::Profile, payment_data: &mut D, connectors: api::SessionConnectorDatas, ) -> RouterResult<api::SessionConnectorDatas> where F: Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F>, { let chosen = connectors.apply_filter_for_session_routing(); let sfr = SessionFlowRoutingInput { state: &state, country: payment_data .get_address() .get_payment_method_billing() .and_then(|address| address.address.as_ref()) .and_then(|details| details.country), key_store: merchant_context.get_merchant_key_store(), merchant_account: merchant_context.get_merchant_account(), payment_attempt: payment_data.get_payment_attempt(), payment_intent: payment_data.get_payment_intent(), chosen, }; let (result, routing_approach) = self_routing::perform_session_flow_routing( sfr, business_profile, &enums::TransactionType::Payment, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error performing session flow routing")?; payment_data.set_routing_approach_in_attempt(routing_approach); let final_list = connectors.filter_and_validate_for_session_flow(&result)?; Ok(final_list) } pub struct SessionTokenRoutingResult { pub final_result: api::SessionConnectorDatas, pub routing_result: FxHashMap<common_enums::PaymentMethodType, Vec<api::routing::SessionRoutingChoice>>, } #[cfg(feature = "v2")] pub async fn perform_session_token_routing<F, D>( state: SessionState, business_profile: &domain::Profile, merchant_context: domain::MerchantContext, payment_data: &D, connectors: api::SessionConnectorDatas, ) -> RouterResult<SessionTokenRoutingResult> where F: Clone, D: OperationSessionGetters<F>, { let chosen = connectors.apply_filter_for_session_routing(); let sfr = SessionFlowRoutingInput { country: payment_data .get_payment_intent() .billing_address .as_ref() .and_then(|address| address.get_inner().address.as_ref()) .and_then(|details| details.country), payment_intent: payment_data.get_payment_intent(), chosen, }; let result = self_routing::perform_session_flow_routing( &state, merchant_context.get_merchant_key_store(), sfr, business_profile, &enums::TransactionType::Payment, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error performing session flow routing")?; let final_list = connectors.filter_and_validate_for_session_flow(&result)?; Ok(SessionTokenRoutingResult { final_result: final_list, routing_result: result, }) } #[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::IncorrectPaymentMethodConfiguration)? .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>( state: &SessionState, merchant_context: &domain::MerchantContext, business_profile: &domain::Profile, payment_data: &mut D, transaction_data: core_routing::PaymentsDslInput<'_>, 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, { let routing_algorithm_id = { let routing_algorithm = business_profile.routing_algorithm.clone(); let algorithm_ref = routing_algorithm .map(|ra| ra.parse_value::<api::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not decode merchant routing algorithm ref")? .unwrap_or_default(); algorithm_ref.algorithm_id }; let (connectors, routing_approach) = routing::perform_static_routing_v1( state, merchant_context.get_merchant_account().get_id(), routing_algorithm_id.as_ref(), business_profile, &TransactionData::Payment(transaction_data.clone()), ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; payment_data.set_routing_approach_in_attempt(routing_approach); #[cfg(all(feature = "v1", feature = "dynamic_routing"))] let payment_attempt = transaction_data.payment_attempt.clone(); let connectors = routing::perform_eligibility_analysis_with_fallback( &state.clone(), merchant_context.get_merchant_key_store(), connectors, &TransactionData::Payment(transaction_data), eligible_connectors, business_profile, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed eligibility analysis and fallback")?; // dynamic success based connector selection #[cfg(all(feature = "v1", feature = "dynamic_routing"))] let connectors = if let Some(algo) = business_profile.dynamic_routing_algorithm.clone() { let dynamic_routing_config: api_models::routing::DynamicRoutingAlgorithmRef = algo .parse_value("DynamicRoutingAlgorithmRef") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?; let dynamic_split = api_models::routing::RoutingVolumeSplit { routing_type: api_models::routing::RoutingType::Dynamic, split: dynamic_routing_config .dynamic_routing_volume_split .unwrap_or_default(), }; let static_split: api_models::routing::RoutingVolumeSplit = api_models::routing::RoutingVolumeSplit { routing_type: api_models::routing::RoutingType::Static, split: consts::DYNAMIC_ROUTING_MAX_VOLUME - dynamic_routing_config .dynamic_routing_volume_split .unwrap_or_default(), }; let volume_split_vec = vec![dynamic_split, static_split]; let routing_choice = routing::perform_dynamic_routing_volume_split(volume_split_vec, None) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to perform volume split on routing type")?; if routing_choice.routing_type.is_dynamic_routing() { if state.conf.open_router.dynamic_routing_enabled { routing::perform_dynamic_routing_with_open_router( state, connectors.clone(), business_profile, payment_attempt, payment_data, ) .await .map_err(|e| logger::error!(open_routing_error=?e)) .unwrap_or(connectors) } else { let dynamic_routing_config_params_interpolator = routing_helpers::DynamicRoutingConfigParamsInterpolator::new( payment_data.get_payment_attempt().payment_method, payment_data.get_payment_attempt().payment_method_type, payment_data.get_payment_attempt().authentication_type, payment_data.get_payment_attempt().currency, payment_data .get_billing_address() .and_then(|address| address.address) .and_then(|address| address.country), payment_data .get_payment_attempt() .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|card| card.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()), payment_data .get_payment_attempt() .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|card| card.get("card")) .and_then(|data| data.as_object()) .and_then(|card| card.get("card_isin")) .and_then(|card_isin| card_isin.as_str()) .map(|card_isin| card_isin.to_string()), ); routing::perform_dynamic_routing_with_intelligent_router( state, connectors.clone(), business_profile, dynamic_routing_config_params_interpolator, payment_data, ) .await .map_err(|e| logger::error!(dynamic_routing_error=?e)) .unwrap_or(connectors) } } else { connectors } } else { connectors }; 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")?; 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 } #[cfg(feature = "payouts")] #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn route_connector_v1_for_payouts( state: &SessionState, merchant_context: &domain::MerchantContext, business_profile: &domain::Profile, transaction_data: &payouts::PayoutData, routing_data: &mut storage::RoutingData, eligible_connectors: Option<Vec<enums::RoutableConnectors>>, ) -> RouterResult<ConnectorCallType> { todo!() } #[cfg(feature = "payouts")] #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn route_connector_v1_for_payouts( state: &SessionState, merchant_context: &domain::MerchantContext, business_profile: &domain::Profile, transaction_data: &payouts::PayoutData, routing_data: &mut storage::RoutingData, eligible_connectors: Option<Vec<enums::RoutableConnectors>>, ) -> RouterResult<ConnectorCallType> { let routing_algorithm_id = { let routing_algorithm = business_profile.payout_routing_algorithm.clone(); let algorithm_ref = routing_algorithm .map(|ra| ra.parse_value::<api::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not decode merchant routing algorithm ref")? .unwrap_or_default(); algorithm_ref.algorithm_id }; let (connectors, _) = routing::perform_static_routing_v1( state, merchant_context.get_merchant_account().get_id(), routing_algorithm_id.as_ref(), business_profile, &TransactionData::Payout(transaction_data), ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; let connectors = routing::perform_eligibility_analysis_with_fallback( &state.clone(), merchant_context.get_merchant_key_store(), connectors, &TransactionData::Payout(transaction_data), eligible_connectors, business_profile, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed eligibility analysis and fallback")?; let first_connector_choice = connectors .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("Empty connector list returned")? .clone(); 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")?; routing_data.routed_through = Some(first_connector_choice.connector.to_string()); routing_data.merchant_connector_id = first_connector_choice.merchant_connector_id; Ok(ConnectorCallType::Retryable(connector_data)) } #[cfg(feature = "v2")] pub async fn payment_external_authentication( _state: SessionState, _merchant_context: domain::MerchantContext, _req: api_models::payments::PaymentsExternalAuthenticationRequest, ) -> RouterResponse<api_models::payments::PaymentsExternalAuthenticationResponse> { todo!() } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn payment_external_authentication<F: Clone + Sync>( state: SessionState, merchant_context: domain::MerchantContext, req: api_models::payments::PaymentsExternalAuthenticationRequest, ) -> RouterResponse<api_models::payments::PaymentsExternalAuthenticationResponse> { use super::unified_authentication_service::types::ExternalAuthentication; use crate::core::unified_authentication_service::{ types::UnifiedAuthenticationService, utils::external_authentication_update_trackers, }; let db = &*state.store; let key_manager_state = &(&state).into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_id = req.payment_id; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, merchant_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, &attempt_id.clone(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; if payment_attempt.external_three_ds_authentication_attempted != Some(true) { Err(errors::ApiErrorResponse::PreconditionFailed { message: "You cannot authenticate this payment because payment_attempt.external_three_ds_authentication_attempted is false".to_owned(), })? } helpers::validate_payment_status_against_allowed_statuses( payment_intent.status, &[storage_enums::IntentStatus::RequiresCustomerAction], "authenticate", )?; let optional_customer = match &payment_intent.customer_id { Some(customer_id) => Some( state .store .find_customer_by_customer_id_merchant_id( key_manager_state, customer_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("error while finding customer with customer_id {customer_id:?}") })?, ), None => None, }; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let currency = payment_attempt.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount(); let shipping_address = helpers::create_or_find_address_for_payment_by_request( &state, None, payment_intent.shipping_address_id.as_deref(), merchant_id, payment_intent.customer_id.as_ref(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, storage_scheme, ) .await?; let billing_address = helpers::create_or_find_address_for_payment_by_request( &state, None, payment_attempt .payment_method_billing_address_id .as_deref() .or(payment_intent.billing_address_id.as_deref()), merchant_id, payment_intent.customer_id.as_ref(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, storage_scheme, ) .await?; let authentication_connector = payment_attempt .authentication_connector .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("authentication_connector not found in payment_attempt")?; let merchant_connector_account = helpers::get_merchant_connector_account( &state, merchant_id, None, merchant_context.get_merchant_key_store(), profile_id, authentication_connector.as_str(), None, ) .await?; let authentication = db .find_authentication_by_merchant_id_authentication_id( merchant_id, &payment_attempt .authentication_id .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing authentication_id in payment_attempt")?, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while fetching authentication record")?; let business_profile = state .store .find_business_profile_by_profile_id( key_manager_state, merchant_context.get_merchant_key_store(), profile_id, ) .await .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let payment_method_details = helpers::get_payment_method_details_from_payment_token( &state, &payment_attempt, &payment_intent, merchant_context.get_merchant_key_store(), storage_scheme, ) .await? .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing payment_method_details")?; let browser_info: Option<BrowserInformation> = payment_attempt .browser_info .clone() .map(|browser_information| browser_information.parse_value("BrowserInformation")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; let payment_connector_name = payment_attempt .connector .as_ref() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing connector in payment_attempt")?; let return_url = Some(helpers::create_authorize_url( &state.base_url, &payment_attempt.clone(), payment_connector_name, )); let mca_id_option = merchant_connector_account.get_mca_id(); // Bind temporary value let merchant_connector_account_id_or_connector_name = mca_id_option .as_ref() .map(|mca_id| mca_id.get_string_repr()) .unwrap_or(&authentication_connector); let webhook_url = helpers::create_webhook_url( &state.base_url, merchant_id, merchant_connector_account_id_or_connector_name, ); let authentication_details = business_profile .authentication_connector_details .clone() .get_required_value("authentication_connector_details") .attach_printable("authentication_connector_details not configured by the merchant")?; let authentication_response = if helpers::is_merchant_eligible_authentication_service( merchant_context.get_merchant_account().get_id(), &state, ) .await? { let auth_response = <ExternalAuthentication as UnifiedAuthenticationService>::authentication( &state, &business_profile, &payment_method_details.1, browser_info, Some(amount), Some(currency), authentication::MessageCategory::Payment, req.device_channel, authentication.clone(), return_url, req.sdk_information, req.threeds_method_comp_ind, optional_customer.and_then(|customer| customer.email.map(pii::Email::from)), webhook_url, &merchant_connector_account, &authentication_connector, Some(payment_intent.payment_id), ) .await?; let authentication = external_authentication_update_trackers( &state, auth_response, authentication.clone(), None, merchant_context.get_merchant_key_store(), None, None, None, None, ) .await?; authentication::AuthenticationResponse::try_from(authentication)? } else { Box::pin(authentication_core::perform_authentication( &state, business_profile.merchant_id, authentication_connector, payment_method_details.0, payment_method_details.1, billing_address .as_ref() .map(|address| address.into()) .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "billing_address", })?, shipping_address.as_ref().map(|address| address.into()), browser_info, merchant_connector_account, Some(amount), Some(currency), authentication::MessageCategory::Payment, req.device_channel, authentication, return_url, req.sdk_information, req.threeds_method_comp_ind, optional_customer.and_then(|customer| customer.email.map(pii::Email::from)), webhook_url, authentication_details.three_ds_requestor_url.clone(), payment_intent.psd2_sca_exemption_type, payment_intent.payment_id, payment_intent.force_3ds_challenge_trigger.unwrap_or(false), merchant_context.get_merchant_key_store(), )) .await? }; Ok(services::ApplicationResponse::Json( api_models::payments::PaymentsExternalAuthenticationResponse { transaction_status: authentication_response.trans_status, acs_url: authentication_response .acs_url .as_ref() .map(ToString::to_string), challenge_request: authentication_response.challenge_request, // If challenge_request_key is None, we send "creq" as a static value which is standard 3DS challenge form field name challenge_request_key: authentication_response .challenge_request_key .or(Some(consts::CREQ_CHALLENGE_REQUEST_KEY.to_string())), acs_reference_number: authentication_response.acs_reference_number, acs_trans_id: authentication_response.acs_trans_id, three_dsserver_trans_id: authentication_response.three_dsserver_trans_id, acs_signed_content: authentication_response.acs_signed_content, three_ds_requestor_url: authentication_details.three_ds_requestor_url, three_ds_requestor_app_url: authentication_details.three_ds_requestor_app_url, }, )) } #[instrument(skip_all)] #[cfg(feature = "v2")] pub async fn payment_start_redirection( state: SessionState, merchant_context: domain::MerchantContext, req: api_models::payments::PaymentStartRedirectionRequest, ) -> RouterResponse<serde_json::Value> { let db = &*state.store; let key_manager_state = &(&state).into(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_intent = db .find_payment_intent_by_id( key_manager_state, &req.id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; //TODO: send valid html error pages in this case, or atleast redirect to valid html error pages utils::when( payment_intent.status != storage_enums::IntentStatus::RequiresCustomerAction, || { Err(errors::ApiErrorResponse::PaymentUnexpectedState { current_flow: "PaymentStartRedirection".to_string(), field_name: "status".to_string(), current_value: payment_intent.status.to_string(), states: ["requires_customer_action".to_string()].join(", "), }) }, )?; let payment_attempt = db .find_payment_attempt_by_id( key_manager_state, merchant_context.get_merchant_key_store(), payment_intent .active_attempt_id .as_ref() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing active attempt in payment_intent")?, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while fetching payment_attempt")?; let redirection_data = payment_attempt .redirection_data .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing authentication_data in payment_attempt")?; Ok(services::ApplicationResponse::Form(Box::new( services::RedirectionFormData { redirect_form: redirection_data, payment_method_data: None, amount: payment_attempt.amount_details.get_net_amount().to_string(), currency: payment_intent.amount_details.currency.to_string(), }, ))) } #[instrument(skip_all)] pub async fn get_extended_card_info( state: SessionState, merchant_id: id_type::MerchantId, payment_id: id_type::PaymentId, ) -> RouterResponse<payments_api::ExtendedCardInfoResponse> { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let key = helpers::get_redis_key_for_extended_card_info(&merchant_id, &payment_id); let payload = redis_conn .get_key::<String>(&key.into()) .await .change_context(errors::ApiErrorResponse::ExtendedCardInfoNotFound)?; Ok(services::ApplicationResponse::Json( payments_api::ExtendedCardInfoResponse { payload }, )) } #[cfg(all(feature = "olap", feature = "v1"))] pub async fn payments_manual_update( state: SessionState, req: api_models::payments::PaymentsManualUpdateRequest, ) -> RouterResponse<api_models::payments::PaymentsManualUpdateResponse> { let api_models::payments::PaymentsManualUpdateRequest { payment_id, attempt_id, merchant_id, attempt_status, error_code, error_message, error_reason, connector_transaction_id, } = req; 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(errors::ApiErrorResponse::MerchantAccountNotFound) .attach_printable("Error while fetching the key store by merchant_id")?; let merchant_account = state .store .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) .attach_printable("Error while fetching the merchant_account by merchant_id")?; let payment_attempt = state .store .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_id, &merchant_id, &attempt_id.clone(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable( "Error while fetching the payment_attempt by payment_id, merchant_id and attempt_id", )?; let payment_intent = state .store .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, merchant_account.get_id(), &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Error while fetching the payment_intent by payment_id, merchant_id")?; let option_gsm = if let Some(((code, message), connector_name)) = error_code .as_ref() .zip(error_message.as_ref()) .zip(payment_attempt.connector.as_ref()) { helpers::get_gsm_record( &state, Some(code.to_string()), Some(message.to_string()), connector_name.to_string(), // We need to get the unified_code and unified_message of the Authorize flow "Authorize".to_string(), ) .await } else { None }; // Update the payment_attempt let attempt_update = storage::PaymentAttemptUpdate::ManualUpdate { status: attempt_status, error_code, error_message, error_reason, updated_by: merchant_account.storage_scheme.to_string(), unified_code: option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone()), unified_message: option_gsm.and_then(|gsm| gsm.unified_message), connector_transaction_id, }; let updated_payment_attempt = state .store .update_payment_attempt_with_attempt_id( payment_attempt.clone(), attempt_update, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Error while updating the payment_attempt")?; // If the payment_attempt is active attempt for an intent, update the intent status if payment_intent.active_attempt.get_id() == payment_attempt.attempt_id { let intent_status = enums::IntentStatus::foreign_from(updated_payment_attempt.status); let payment_intent_update = storage::PaymentIntentUpdate::ManualUpdate { status: Some(intent_status), updated_by: merchant_account.storage_scheme.to_string(), }; state .store .update_payment_intent( key_manager_state, payment_intent, payment_intent_update, &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Error while updating payment_intent")?; } Ok(services::ApplicationResponse::Json( api_models::payments::PaymentsManualUpdateResponse { payment_id: updated_payment_attempt.payment_id, attempt_id: updated_payment_attempt.attempt_id, merchant_id: updated_payment_attempt.merchant_id, attempt_status: updated_payment_attempt.status, error_code: updated_payment_attempt.error_code, error_message: updated_payment_attempt.error_message, error_reason: updated_payment_attempt.error_reason, connector_transaction_id: updated_payment_attempt.connector_transaction_id, }, )) } // Trait for Eligibility Checks #[cfg(feature = "v1")] #[async_trait::async_trait] trait EligibilityCheck { type Output; // Determine if the check should be run based on the runtime checks async fn should_run( &self, state: &SessionState, merchant_context: &domain::MerchantContext, ) -> CustomResult<bool, errors::ApiErrorResponse>; // Run the actual check and return the SDK Next Action if applicable async fn execute_check( &self, state: &SessionState, merchant_context: &domain::MerchantContext, payment_elgibility_data: &PaymentEligibilityData, business_profile: &domain::Profile, ) -> CustomResult<Self::Output, errors::ApiErrorResponse>; fn transform(output: Self::Output) -> Option<api_models::payments::SdkNextAction>; } // Result of an Eligibility Check #[cfg(feature = "v1")] #[derive(Debug, Clone)] pub enum CheckResult { Allow, Deny { message: String }, } #[cfg(feature = "v1")] impl From<CheckResult> for Option<api_models::payments::SdkNextAction> { fn from(result: CheckResult) -> Self { match result { CheckResult::Allow => None, CheckResult::Deny { message } => Some(api_models::payments::SdkNextAction { next_action: api_models::payments::NextActionCall::Deny { message }, }), } } } // Perform Blocklist Check for the Card Number provided in Payment Method Data #[cfg(feature = "v1")] struct BlockListCheck; #[cfg(feature = "v1")] #[async_trait::async_trait] impl EligibilityCheck for BlockListCheck { type Output = CheckResult; async fn should_run( &self, state: &SessionState, merchant_context: &domain::MerchantContext, ) -> CustomResult<bool, errors::ApiErrorResponse> { let merchant_id = merchant_context.get_merchant_account().get_id(); let blocklist_enabled_key = merchant_id.get_blocklist_guard_key(); let blocklist_guard_enabled = state .store .find_config_by_key_unwrap_or(&blocklist_enabled_key, Some("false".to_string())) .await; Ok(match blocklist_guard_enabled { Ok(config) => serde_json::from_str(&config.config).unwrap_or(false), // If it is not present in db we are defaulting it to false Err(inner) => { if !inner.current_context().is_db_not_found() { logger::error!("Error fetching guard blocklist enabled config {:?}", inner); } false } }) } async fn execute_check( &self, state: &SessionState, merchant_context: &domain::MerchantContext, payment_elgibility_data: &PaymentEligibilityData, _business_profile: &domain::Profile, ) -> CustomResult<CheckResult, errors::ApiErrorResponse> { let should_payment_be_blocked = blocklist_utils::should_payment_be_blocked( state, merchant_context, &payment_elgibility_data.payment_method_data, ) .await?; if should_payment_be_blocked { Ok(CheckResult::Deny { message: "Card number is blocklisted".to_string(), }) } else { Ok(CheckResult::Allow) } } fn transform(output: CheckResult) -> Option<api_models::payments::SdkNextAction> { output.into() } } // Perform Card Testing Gaurd Check #[cfg(feature = "v1")] struct CardTestingCheck; #[cfg(feature = "v1")] #[async_trait::async_trait] impl EligibilityCheck for CardTestingCheck { type Output = CheckResult; async fn should_run( &self, _state: &SessionState, _merchant_context: &domain::MerchantContext, ) -> CustomResult<bool, errors::ApiErrorResponse> { // This check is always run as there is no runtime config enablement Ok(true) } async fn execute_check( &self, state: &SessionState, _merchant_context: &domain::MerchantContext, payment_elgibility_data: &PaymentEligibilityData, business_profile: &domain::Profile, ) -> CustomResult<CheckResult, errors::ApiErrorResponse> { match &payment_elgibility_data.payment_method_data { Some(domain::PaymentMethodData::Card(card)) => { match card_testing_guard_utils::validate_card_testing_guard_checks( state, payment_elgibility_data .browser_info .as_ref() .map(|browser_info| browser_info.peek()), card.card_number.clone(), &payment_elgibility_data.payment_intent.customer_id, business_profile, ) .await { // If validation succeeds, allow the payment Ok(_) => Ok(CheckResult::Allow), // If validation fails, check the error type Err(e) => match e.current_context() { // If it's a PreconditionFailed error, deny with message errors::ApiErrorResponse::PreconditionFailed { message } => { Ok(CheckResult::Deny { message: message.to_string(), }) } // For any other error, propagate it _ => Err(e), }, } } // If payment method is not card, allow _ => Ok(CheckResult::Allow), } } fn transform(output: CheckResult) -> Option<api_models::payments::SdkNextAction> { output.into() } } // Eligibility Pipeline to run all the eligibility checks in sequence #[cfg(feature = "v1")] pub struct EligibilityHandler { state: SessionState, merchant_context: domain::MerchantContext, payment_eligibility_data: PaymentEligibilityData, business_profile: domain::Profile, } #[cfg(feature = "v1")] impl EligibilityHandler { fn new( state: SessionState, merchant_context: domain::MerchantContext, payment_eligibility_data: PaymentEligibilityData, business_profile: domain::Profile, ) -> Self { Self { state, merchant_context, payment_eligibility_data, business_profile, } } async fn run_check<C: EligibilityCheck>( &self, check: C, ) -> CustomResult<Option<api_models::payments::SdkNextAction>, errors::ApiErrorResponse> { let should_run = check .should_run(&self.state, &self.merchant_context) .await?; Ok(match should_run { true => check .execute_check( &self.state, &self.merchant_context, &self.payment_eligibility_data, &self.business_profile, ) .await .map(C::transform)?, false => None, }) } } #[cfg(all(feature = "oltp", feature = "v1"))] pub async fn payments_submit_eligibility( state: SessionState, merchant_context: domain::MerchantContext, req: api_models::payments::PaymentsEligibilityRequest, payment_id: id_type::PaymentId, ) -> RouterResponse<api_models::payments::PaymentsEligibilityResponse> { let key_manager_state = &(&state).into(); let payment_eligibility_data = PaymentEligibilityData::from_request(&state, &merchant_context, &req).await?; let profile_id = payment_eligibility_data .payment_intent .profile_id .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; 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 eligibility_handler = EligibilityHandler::new( state, merchant_context, payment_eligibility_data, business_profile, ); // Run the checks in sequence, short-circuiting on the first that returns a next action let sdk_next_action = eligibility_handler .run_check(BlockListCheck) .await .transpose() .async_or_else(|| async { eligibility_handler .run_check(CardTestingCheck) .await .transpose() }) .await .transpose()? .unwrap_or(api_models::payments::SdkNextAction { next_action: api_models::payments::NextActionCall::Confirm, }); Ok(services::ApplicationResponse::Json( api_models::payments::PaymentsEligibilityResponse { payment_id, sdk_next_action, }, )) } pub trait PaymentMethodChecker<F> { fn should_update_in_post_update_tracker(&self) -> bool; fn should_update_in_update_tracker(&self) -> bool; } #[cfg(feature = "v1")] impl<F: Clone> PaymentMethodChecker<F> for PaymentData<F> { fn should_update_in_post_update_tracker(&self) -> bool { let payment_method_type = self .payment_intent .tax_details .as_ref() .and_then(|tax_details| tax_details.payment_method_type.as_ref().map(|pmt| pmt.pmt)); matches!( payment_method_type, Some(storage_enums::PaymentMethodType::Paypal) ) } fn should_update_in_update_tracker(&self) -> bool { let payment_method_type = self .payment_intent .tax_details .as_ref() .and_then(|tax_details| tax_details.payment_method_type.as_ref().map(|pmt| pmt.pmt)); matches!( payment_method_type, Some(storage_enums::PaymentMethodType::ApplePay) | Some(storage_enums::PaymentMethodType::GooglePay) ) } } 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>>; fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod>; fn get_payment_method_token(&self) -> Option<&PaymentMethodToken>; fn get_mandate_id(&self) -> Option<&payments_api::MandateIds>; fn get_address(&self) -> &PaymentAddress; fn get_creds_identifier(&self) -> Option<&str>; fn get_token(&self) -> Option<&str>; fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData>; fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse>; fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey>; fn get_setup_mandate(&self) -> Option<&MandateData>; fn get_poll_config(&self) -> Option<router_types::PollConfig>; fn get_authentication( &self, ) -> Option<&hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore>; fn get_frm_message(&self) -> Option<FraudCheck>; fn get_refunds(&self) -> Vec<diesel_refund::Refund>; fn get_disputes(&self) -> Vec<storage::Dispute>; fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization>; fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>>; fn get_recurring_details(&self) -> Option<&RecurringDetails>; // TODO: this should be a mandatory field, should we throw an error instead of returning an Option? fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId>; fn get_currency(&self) -> storage_enums::Currency; fn get_amount(&self) -> api::Amount; fn get_payment_attempt_connector(&self) -> Option<&str>; fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address>; fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData>; fn get_sessions_token(&self) -> Vec<api::SessionToken>; fn get_token_data(&self) -> Option<&storage::PaymentTokenData>; fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails>; fn get_force_sync(&self) -> Option<bool>; #[cfg(feature = "v1")] 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 = "v2")] fn get_merchant_connector_details( &self, ) -> Option<common_types::domain::MerchantConnectorAuthDetails>; fn get_connector_customer_id(&self) -> Option<String>; #[cfg(feature = "v1")] fn get_whole_connector_response(&self) -> Option<Secret<String>>; #[cfg(feature = "v1")] fn get_vault_operation(&self) -> Option<&domain_payments::VaultOperation>; #[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>>; #[cfg(feature = "v2")] fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails>; #[cfg(feature = "v1")] fn get_click_to_pay_service_details(&self) -> Option<&api_models::payments::CtpServiceDetails>; #[cfg(feature = "v1")] fn get_is_manual_retry_enabled(&self) -> Option<bool>; } pub trait OperationSessionSetters<F> { // Setter functions for PaymentData fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent); #[cfg(feature = "v2")] fn set_client_secret(&mut self, client_secret: Option<Secret<String>>); fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt); fn set_payment_method_data(&mut self, payment_method_data: Option<domain::PaymentMethodData>); fn set_payment_method_token(&mut self, payment_method_token: Option<PaymentMethodToken>); fn set_email_if_not_present(&mut self, email: pii::Email); fn set_payment_method_id_in_attempt(&mut self, payment_method_id: Option<String>); fn set_pm_token(&mut self, token: String); fn set_connector_customer_id(&mut self, customer_id: Option<String>); fn push_sessions_token(&mut self, token: api::SessionToken); fn set_surcharge_details(&mut self, surcharge_details: Option<types::SurchargeDetails>); fn set_merchant_connector_id_in_attempt( &mut self, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ); fn set_card_network(&mut self, card_network: enums::CardNetwork); fn set_co_badged_card_data( &mut self, debit_routing_output: &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); fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus); fn set_authentication_type_in_attempt( &mut self, authentication_type: Option<enums::AuthenticationType>, ); fn set_recurring_mandate_payment_data( &mut self, recurring_mandate_payment_data: hyperswitch_domain_models::router_data::RecurringMandatePaymentData, ); fn set_mandate_id(&mut self, mandate_id: api_models::payments::MandateIds); fn set_setup_future_usage_in_payment_intent( &mut self, setup_future_usage: storage_enums::FutureUsage, ); #[cfg(feature = "v1")] fn set_straight_through_algorithm_in_payment_attempt( &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")] fn set_vault_operation(&mut self, vault_operation: domain_payments::VaultOperation); #[cfg(feature = "v2")] fn set_connector_request_reference_id(&mut self, reference_id: Option<String>); fn set_connector_response_reference_id(&mut self, reference_id: Option<String>); #[cfg(feature = "v2")] fn set_vault_session_details( &mut self, external_vault_session_details: Option<api::VaultSessionDetails>, ); fn set_routing_approach_in_attempt(&mut self, routing_approach: Option<enums::RoutingApproach>); fn set_connector_request_reference_id_in_payment_attempt( &mut self, connector_request_reference_id: String, ); #[cfg(feature = "v2")] fn set_cancellation_reason(&mut self, cancellation_reason: Option<String>); } #[cfg(feature = "v1")] impl<F: Clone> OperationSessionGetters<F> for PaymentData<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt { &self.payment_attempt } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> { self.payment_method_info.as_ref() } fn get_payment_method_token(&self) -> Option<&PaymentMethodToken> { self.payment_method_token.as_ref() } fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> { self.mandate_id.as_ref() } // what is this address find out and not required remove this fn get_address(&self) -> &PaymentAddress { &self.address } fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId> { self.payment_attempt.merchant_connector_id.clone() } fn get_creds_identifier(&self) -> Option<&str> { self.creds_identifier.as_deref() } fn get_token(&self) -> Option<&str> { self.token.as_deref() } fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData> { self.multiple_capture_data.as_ref() } fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse> { self.payment_link_data.clone() } fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey> { self.ephemeral_key.clone() } fn get_setup_mandate(&self) -> Option<&MandateData> { self.setup_mandate.as_ref() } fn get_poll_config(&self) -> Option<router_types::PollConfig> { self.poll_config.clone() } fn get_authentication( &self, ) -> Option<&hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore> { self.authentication.as_ref() } fn get_frm_message(&self) -> Option<FraudCheck> { self.frm_message.clone() } fn get_refunds(&self) -> Vec<diesel_refund::Refund> { self.refunds.clone() } fn get_disputes(&self) -> Vec<storage::Dispute> { self.disputes.clone() } fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization> { self.authorizations.clone() } fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>> { self.attempts.clone() } fn get_recurring_details(&self) -> Option<&RecurringDetails> { self.recurring_details.as_ref() } #[cfg(feature = "v1")] fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId> { self.payment_intent.profile_id.as_ref() } #[cfg(feature = "v2")] fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId> { Some(&self.payment_intent.profile_id) } fn get_currency(&self) -> storage_enums::Currency { self.currency } fn get_amount(&self) -> api::Amount { self.amount } fn get_payment_attempt_connector(&self) -> Option<&str> { self.payment_attempt.connector.as_deref() } fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address> { self.address.get_payment_method_billing().cloned() } fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData> { self.payment_method_data.as_ref() } fn get_sessions_token(&self) -> Vec<api::SessionToken> { self.sessions_token.clone() } fn get_token_data(&self) -> Option<&storage::PaymentTokenData> { self.token_data.as_ref() } fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails> { self.mandate_connector.as_ref() } fn get_force_sync(&self) -> Option<bool> { self.force_sync } fn get_all_keys_required(&self) -> Option<bool> { self.all_keys_required } fn get_whole_connector_response(&self) -> Option<Secret<String>> { self.whole_connector_response.clone() } #[cfg(feature = "v1")] fn get_capture_method(&self) -> Option<enums::CaptureMethod> { self.payment_attempt.capture_method } #[cfg(feature = "v1")] fn get_vault_operation(&self) -> Option<&domain_payments::VaultOperation> { self.vault_operation.as_ref() } fn get_connector_customer_id(&self) -> Option<String> { self.connector_customer_id.clone() } fn get_click_to_pay_service_details(&self) -> Option<&api_models::payments::CtpServiceDetails> { self.service_details.as_ref() } fn get_is_manual_retry_enabled(&self) -> Option<bool> { self.is_manual_retry_enabled } // #[cfg(feature = "v2")] // fn get_capture_method(&self) -> Option<enums::CaptureMethod> { // Some(self.payment_intent.capture_method) // } // #[cfg(feature = "v2")] // fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> { // todo!(); // } } #[cfg(feature = "v1")] impl<F: Clone> OperationSessionSetters<F> for PaymentData<F> { // Setters Implementation fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = payment_attempt; } fn set_payment_method_data(&mut self, payment_method_data: Option<domain::PaymentMethodData>) { self.payment_method_data = payment_method_data; } fn set_payment_method_token(&mut self, payment_method_token: Option<PaymentMethodToken>) { self.payment_method_token = payment_method_token; } fn set_payment_method_id_in_attempt(&mut self, payment_method_id: Option<String>) { self.payment_attempt.payment_method_id = payment_method_id; } fn set_email_if_not_present(&mut self, email: pii::Email) { self.email = self.email.clone().or(Some(email)); } fn set_pm_token(&mut self, token: String) { self.pm_token = Some(token); } fn set_connector_customer_id(&mut self, customer_id: Option<String>) { self.connector_customer_id = customer_id; } fn push_sessions_token(&mut self, token: api::SessionToken) { self.sessions_token.push(token); } fn set_surcharge_details(&mut self, surcharge_details: Option<types::SurchargeDetails>) { self.surcharge_details = surcharge_details; } fn set_merchant_connector_id_in_attempt( &mut self, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ) { self.payment_attempt.merchant_connector_id = merchant_connector_id; } fn set_card_network(&mut self, card_network: enums::CardNetwork) { match &mut self.payment_method_data { Some(domain::PaymentMethodData::Card(card)) => { logger::debug!("Setting card network: {:?}", card_network); card.card_network = Some(card_network); } Some(domain::PaymentMethodData::Wallet(wallet_data)) => match wallet_data { hyperswitch_domain_models::payment_method_data::WalletData::ApplePay(wallet) => { logger::debug!("Setting Apple Pay card network: {:?}", card_network); wallet.payment_method.network = card_network.to_string(); } _ => { logger::debug!("Wallet type does not support setting card network."); } }, _ => { logger::warn!("Payment method data does not support setting card network."); } } } fn set_co_badged_card_data( &mut self, debit_routing_output: &api_models::open_router::DebitRoutingOutput, ) { let co_badged_card_data = api_models::payment_methods::CoBadgedCardData::from(debit_routing_output); let card_type = debit_routing_output .card_type .clone() .to_string() .to_uppercase(); if let Some(domain::PaymentMethodData::Card(card)) = &mut self.payment_method_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 data"); }; } #[cfg(feature = "v1")] fn set_capture_method_in_attempt(&mut self, capture_method: enums::CaptureMethod) { self.payment_attempt.capture_method = Some(capture_method); } fn set_frm_message(&mut self, frm_message: FraudCheck) { self.frm_message = Some(frm_message); } fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus) { self.payment_intent.status = status; } fn set_authentication_type_in_attempt( &mut self, authentication_type: Option<enums::AuthenticationType>, ) { self.payment_attempt.authentication_type = authentication_type; } fn set_recurring_mandate_payment_data( &mut self, recurring_mandate_payment_data: hyperswitch_domain_models::router_data::RecurringMandatePaymentData, ) { self.recurring_mandate_payment_data = Some(recurring_mandate_payment_data); } fn set_mandate_id(&mut self, mandate_id: api_models::payments::MandateIds) { self.mandate_id = Some(mandate_id); } #[cfg(feature = "v1")] fn set_setup_future_usage_in_payment_intent( &mut self, setup_future_usage: storage_enums::FutureUsage, ) { self.payment_intent.setup_future_usage = Some(setup_future_usage); } #[cfg(feature = "v2")] fn set_setup_future_usage_in_payment_intent( &mut self, setup_future_usage: storage_enums::FutureUsage, ) { self.payment_intent.setup_future_usage = setup_future_usage; } #[cfg(feature = "v1")] fn set_straight_through_algorithm_in_payment_attempt( &mut self, straight_through_algorithm: serde_json::Value, ) { self.payment_attempt.straight_through_algorithm = Some(straight_through_algorithm); } fn set_connector_in_payment_attempt(&mut self, connector: Option<String>) { self.payment_attempt.connector = connector; } fn set_vault_operation(&mut self, vault_operation: domain_payments::VaultOperation) { self.vault_operation = Some(vault_operation); } fn set_routing_approach_in_attempt( &mut self, routing_approach: Option<enums::RoutingApproach>, ) { self.payment_attempt.routing_approach = routing_approach; } fn set_connector_response_reference_id(&mut self, reference_id: Option<String>) { self.payment_attempt.connector_response_reference_id = reference_id; } fn set_connector_request_reference_id_in_payment_attempt( &mut self, connector_request_reference_id: String, ) { self.payment_attempt.connector_request_reference_id = Some(connector_request_reference_id); } } #[cfg(feature = "v2")] 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 } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> { todo!() } fn get_payment_method_token(&self) -> Option<&PaymentMethodToken> { 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> { todo!() } 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<diesel_refund::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> { Some(&self.payment_intent.profile_id) } fn get_currency(&self) -> storage_enums::Currency { self.payment_intent.amount_details.currency } 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> { self.connector_customer_id.clone() } fn get_merchant_connector_details( &self, ) -> Option<common_types::domain::MerchantConnectorAuthDetails> { 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> { self.sessions_token.clone() } 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!() } fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> { todo!(); } fn get_pre_routing_result( &self, ) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> { None } fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> { self.vault_session_details.clone() } } #[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; } fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) { self.client_secret = client_secret; } fn set_payment_attempt(&mut self, _payment_attempt: storage::PaymentAttempt) { todo!() } fn set_payment_method_data(&mut self, _payment_method_data: Option<domain::PaymentMethodData>) { todo!() } fn set_payment_method_token(&mut self, _payment_method_token: Option<PaymentMethodToken>) { todo!() } fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) { todo!() } fn set_card_network(&mut self, card_network: enums::CardNetwork) { todo!() } fn set_co_badged_card_data( &mut self, debit_routing_output: &api_models::open_router::DebitRoutingOutput, ) { todo!() } fn set_email_if_not_present(&mut self, _email: pii::Email) { todo!() } fn set_pm_token(&mut self, _token: String) { todo!() } fn set_connector_customer_id(&mut self, customer_id: Option<String>) { self.connector_customer_id = customer_id; } fn push_sessions_token(&mut self, token: api::SessionToken) { self.sessions_token.push(token); } fn set_surcharge_details(&mut self, _surcharge_details: Option<types::SurchargeDetails>) { todo!() } fn set_merchant_connector_id_in_attempt( &mut self, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ) { todo!() } fn set_frm_message(&mut self, _frm_message: FraudCheck) { todo!() } fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus) { self.payment_intent.status = status; } fn set_authentication_type_in_attempt( &mut self, _authentication_type: Option<enums::AuthenticationType>, ) { todo!() } fn set_recurring_mandate_payment_data( &mut self, _recurring_mandate_payment_data: hyperswitch_domain_models::router_data::RecurringMandatePaymentData, ) { todo!() } fn set_mandate_id(&mut self, _mandate_id: api_models::payments::MandateIds) { todo!() } fn set_setup_future_usage_in_payment_intent( &mut self, setup_future_usage: storage_enums::FutureUsage, ) { self.payment_intent.setup_future_usage = setup_future_usage; } fn set_connector_in_payment_attempt(&mut self, _connector: Option<String>) { todo!() } fn set_connector_request_reference_id(&mut self, reference_id: Option<String>) { todo!() } fn set_connector_response_reference_id(&mut self, reference_id: Option<String>) { todo!() } fn set_vault_session_details( &mut self, vault_session_details: Option<api::VaultSessionDetails>, ) { self.vault_session_details = vault_session_details; } fn set_routing_approach_in_attempt( &mut self, routing_approach: Option<enums::RoutingApproach>, ) { todo!() } fn set_connector_request_reference_id_in_payment_attempt( &mut self, connector_request_reference_id: String, ) { todo!() } fn set_cancellation_reason(&mut self, cancellation_reason: Option<String>) { todo!() } } #[cfg(feature = "v2")] 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!() } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } fn get_merchant_connector_details( &self, ) -> Option<common_types::domain::MerchantConnectorAuthDetails> { self.merchant_connector_details.clone() } fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> { todo!() } fn get_payment_method_token(&self) -> Option<&PaymentMethodToken> { todo!() } fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> { todo!() } fn get_address(&self) -> &PaymentAddress { &self.payment_address } 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<diesel_refund::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> { Some(&self.payment_intent.profile_id) } fn get_currency(&self) -> storage_enums::Currency { self.payment_intent.amount_details.currency } fn get_amount(&self) -> api::Amount { todo!() } fn get_payment_attempt_connector(&self) -> Option<&str> { self.payment_attempt.connector.as_deref() } fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId> { self.payment_attempt.merchant_connector_id.clone() } 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> { self.payment_method_data.as_ref() } 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!() } fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> { Some(&self.payment_attempt) } 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) } fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> { todo!() } } #[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; } fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) { todo!() } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = payment_attempt; } fn set_payment_method_data(&mut self, _payment_method_data: Option<domain::PaymentMethodData>) { todo!() } fn set_payment_method_token(&mut self, _payment_method_token: Option<PaymentMethodToken>) { todo!() } fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) { todo!() } fn set_email_if_not_present(&mut self, _email: pii::Email) { todo!() } fn set_pm_token(&mut self, _token: String) { todo!() } fn set_connector_customer_id(&mut self, _customer_id: Option<String>) { // TODO: handle this case. Should we add connector_customer_id in paymentConfirmData? } fn push_sessions_token(&mut self, _token: api::SessionToken) { todo!() } fn set_card_network(&mut self, card_network: enums::CardNetwork) { todo!() } fn set_co_badged_card_data( &mut self, debit_routing_output: &api_models::open_router::DebitRoutingOutput, ) { todo!() } fn set_surcharge_details(&mut self, _surcharge_details: Option<types::SurchargeDetails>) { todo!() } #[track_caller] fn set_merchant_connector_id_in_attempt( &mut self, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ) { self.payment_attempt.merchant_connector_id = merchant_connector_id; } fn set_frm_message(&mut self, _frm_message: FraudCheck) { todo!() } fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus) { self.payment_intent.status = status; } fn set_authentication_type_in_attempt( &mut self, _authentication_type: Option<enums::AuthenticationType>, ) { todo!() } fn set_recurring_mandate_payment_data( &mut self, _recurring_mandate_payment_data: hyperswitch_domain_models::router_data::RecurringMandatePaymentData, ) { todo!() } fn set_mandate_id(&mut self, _mandate_id: api_models::payments::MandateIds) { todo!() } fn set_setup_future_usage_in_payment_intent( &mut self, setup_future_usage: storage_enums::FutureUsage, ) { self.payment_intent.setup_future_usage = setup_future_usage; } fn set_connector_in_payment_attempt(&mut self, connector: Option<String>) { self.payment_attempt.connector = connector; } fn set_connector_request_reference_id(&mut self, reference_id: Option<String>) { self.payment_attempt.connector_request_reference_id = reference_id; } fn set_connector_response_reference_id(&mut self, reference_id: Option<String>) { self.payment_attempt.connector_response_reference_id = reference_id; } fn set_vault_session_details( &mut self, external_vault_session_details: Option<api::VaultSessionDetails>, ) { todo!() } fn set_routing_approach_in_attempt( &mut self, routing_approach: Option<enums::RoutingApproach>, ) { todo!() } fn set_connector_request_reference_id_in_payment_attempt( &mut self, connector_request_reference_id: String, ) { todo!() } fn set_cancellation_reason(&mut self, cancellation_reason: Option<String>) { todo!() } } #[cfg(feature = "v2")] impl<F: Clone> OperationSessionGetters<F> for PaymentStatusData<F> { #[track_caller] 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!() } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } fn get_merchant_connector_details( &self, ) -> Option<common_types::domain::MerchantConnectorAuthDetails> { self.merchant_connector_details.clone() } fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> { todo!() } fn get_payment_method_token(&self) -> Option<&PaymentMethodToken> { todo!() } fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> { todo!() } fn get_address(&self) -> &PaymentAddress { &self.payment_address } 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<diesel_refund::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> { Some(&self.payment_intent.profile_id) } fn get_currency(&self) -> storage_enums::Currency { self.payment_intent.amount_details.currency } 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!() } fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> { Some(&self.payment_attempt) } fn get_pre_routing_result( &self, ) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> { None } fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> { todo!() } } #[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; } fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) { todo!() } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = payment_attempt; } fn set_payment_method_data(&mut self, _payment_method_data: Option<domain::PaymentMethodData>) { todo!() } fn set_payment_method_token(&mut self, _payment_method_token: Option<PaymentMethodToken>) { todo!() } fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) { todo!() } fn set_email_if_not_present(&mut self, _email: pii::Email) { todo!() } fn set_card_network(&mut self, card_network: enums::CardNetwork) { todo!() } fn set_co_badged_card_data( &mut self, debit_routing_output: &api_models::open_router::DebitRoutingOutput, ) { todo!() } fn set_pm_token(&mut self, _token: String) { todo!() } fn set_connector_customer_id(&mut self, _customer_id: Option<String>) { // TODO: handle this case. Should we add connector_customer_id in paymentConfirmData? } fn push_sessions_token(&mut self, _token: api::SessionToken) { todo!() } fn set_surcharge_details(&mut self, _surcharge_details: Option<types::SurchargeDetails>) { todo!() } #[track_caller] fn set_merchant_connector_id_in_attempt( &mut self, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ) { todo!() } fn set_frm_message(&mut self, _frm_message: FraudCheck) { todo!() } fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus) { self.payment_intent.status = status; } fn set_authentication_type_in_attempt( &mut self, _authentication_type: Option<enums::AuthenticationType>, ) { todo!() } fn set_recurring_mandate_payment_data( &mut self, _recurring_mandate_payment_data: hyperswitch_domain_models::router_data::RecurringMandatePaymentData, ) { todo!() } fn set_mandate_id(&mut self, _mandate_id: api_models::payments::MandateIds) { todo!() } fn set_setup_future_usage_in_payment_intent( &mut self, setup_future_usage: storage_enums::FutureUsage, ) { self.payment_intent.setup_future_usage = setup_future_usage; } fn set_connector_in_payment_attempt(&mut self, connector: Option<String>) { self.payment_attempt.connector = connector; } fn set_connector_request_reference_id(&mut self, reference_id: Option<String>) { todo!() } fn set_connector_response_reference_id(&mut self, reference_id: Option<String>) { todo!() } fn set_vault_session_details( &mut self, external_vault_session_details: Option<api::VaultSessionDetails>, ) { todo!() } fn set_routing_approach_in_attempt( &mut self, routing_approach: Option<enums::RoutingApproach>, ) { todo!() } fn set_connector_request_reference_id_in_payment_attempt( &mut self, connector_request_reference_id: String, ) { todo!() } fn set_cancellation_reason(&mut self, cancellation_reason: Option<String>) { todo!() } } #[cfg(feature = "v2")] impl<F: Clone> OperationSessionGetters<F> for PaymentCaptureData<F> { #[track_caller] 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!() } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } fn get_merchant_connector_details( &self, ) -> Option<common_types::domain::MerchantConnectorAuthDetails> { todo!() } fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> { todo!() } fn get_payment_method_token(&self) -> Option<&PaymentMethodToken> { 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<diesel_refund::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> { Some(&self.payment_intent.profile_id) } fn get_currency(&self) -> storage_enums::Currency { self.payment_intent.amount_details.currency } 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> { Some(&self.payment_attempt) } fn get_pre_routing_result( &self, ) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> { None } fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> { todo!() } } #[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; } fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) { todo!() } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = payment_attempt; } fn set_payment_method_data(&mut self, _payment_method_data: Option<domain::PaymentMethodData>) { todo!() } fn set_payment_method_token(&mut self, _payment_method_token: Option<PaymentMethodToken>) { todo!() } fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) { todo!() } fn set_card_network(&mut self, card_network: enums::CardNetwork) { todo!() } fn set_co_badged_card_data( &mut self, debit_routing_output: &api_models::open_router::DebitRoutingOutput, ) { todo!() } fn set_email_if_not_present(&mut self, _email: pii::Email) { todo!() } fn set_pm_token(&mut self, _token: String) { todo!() } fn set_connector_customer_id(&mut self, _customer_id: Option<String>) { // TODO: handle this case. Should we add connector_customer_id in paymentConfirmData? } fn push_sessions_token(&mut self, _token: api::SessionToken) { todo!() } fn set_surcharge_details(&mut self, _surcharge_details: Option<types::SurchargeDetails>) { todo!() } #[track_caller] fn set_merchant_connector_id_in_attempt( &mut self, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ) { todo!() } fn set_frm_message(&mut self, _frm_message: FraudCheck) { todo!() } fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus) { self.payment_intent.status = status; } fn set_authentication_type_in_attempt( &mut self, _authentication_type: Option<enums::AuthenticationType>, ) { todo!() } fn set_recurring_mandate_payment_data( &mut self, _recurring_mandate_payment_data: hyperswitch_domain_models::router_data::RecurringMandatePaymentData, ) { todo!() } fn set_mandate_id(&mut self, _mandate_id: api_models::payments::MandateIds) { todo!() } fn set_setup_future_usage_in_payment_intent( &mut self, setup_future_usage: storage_enums::FutureUsage, ) { self.payment_intent.setup_future_usage = setup_future_usage; } fn set_connector_in_payment_attempt(&mut self, connector: Option<String>) { todo!() } fn set_connector_request_reference_id(&mut self, reference_id: Option<String>) { todo!() } fn set_connector_response_reference_id(&mut self, reference_id: Option<String>) { todo!() } fn set_vault_session_details( &mut self, external_vault_session_details: Option<api::VaultSessionDetails>, ) { todo!() } fn set_routing_approach_in_attempt( &mut self, routing_approach: Option<enums::RoutingApproach>, ) { todo!() } fn set_connector_request_reference_id_in_payment_attempt( &mut self, connector_request_reference_id: String, ) { todo!() } fn set_cancellation_reason(&mut self, cancellation_reason: Option<String>) { 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_payment_method_token(&self) -> Option<&PaymentMethodToken> { 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<diesel_refund::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_pre_routing_result( &self, ) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> { None } fn get_merchant_connector_details( &self, ) -> Option<common_types::domain::MerchantConnectorAuthDetails> { todo!() } fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> { todo!() } } #[cfg(feature = "v2")] impl<F: Clone> OperationSessionGetters<F> for PaymentCancelData<F> { #[track_caller] fn get_payment_attempt(&self) -> &storage::PaymentAttempt { &self.payment_attempt } fn list_payments_attempts(&self) -> &Vec<storage::PaymentAttempt> { todo!() } fn get_client_secret(&self) -> &Option<Secret<String>> { todo!() } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } fn get_merchant_connector_details( &self, ) -> Option<common_types::domain::MerchantConnectorAuthDetails> { todo!() } fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> { todo!() } fn get_payment_method_token(&self) -> Option<&PaymentMethodToken> { 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<diesel_refund::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!() } fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> { None } fn get_pre_routing_result( &self, ) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> { None } fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> { todo!() } } #[cfg(feature = "v2")] impl<F: Clone> OperationSessionSetters<F> for PaymentCancelData<F> { fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } fn set_client_secret(&mut self, _client_secret: Option<Secret<String>>) { todo!() } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = payment_attempt; } fn set_payment_method_data(&mut self, _payment_method_data: Option<domain::PaymentMethodData>) { todo!() } fn set_payment_method_token(&mut self, _payment_method_token: Option<PaymentMethodToken>) { todo!() } fn set_email_if_not_present(&mut self, _email: pii::Email) { todo!() } fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) { todo!() } fn set_pm_token(&mut self, _token: String) { !todo!() } fn set_connector_customer_id(&mut self, _customer_id: Option<String>) { // TODO: handle this case. Should we add connector_customer_id in PaymentCancelData? } fn push_sessions_token(&mut self, _token: api::SessionToken) { todo!() } fn set_surcharge_details(&mut self, _surcharge_details: Option<types::SurchargeDetails>) { todo!() } fn set_merchant_connector_id_in_attempt( &mut self, _merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ) { todo!() } fn set_card_network(&mut self, _card_network: enums::CardNetwork) { todo!() } fn set_co_badged_card_data( &mut self, _debit_routing_output: &api_models::open_router::DebitRoutingOutput, ) { todo!() } fn set_frm_message(&mut self, _frm_message: FraudCheck) { todo!() } fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus) { self.payment_intent.status = status; } fn set_authentication_type_in_attempt( &mut self, _authentication_type: Option<enums::AuthenticationType>, ) { todo!() } fn set_recurring_mandate_payment_data( &mut self, _recurring_mandate_payment_data: hyperswitch_domain_models::router_data::RecurringMandatePaymentData, ) { todo!() } fn set_mandate_id(&mut self, _mandate_id: api_models::payments::MandateIds) { todo!() } fn set_setup_future_usage_in_payment_intent( &mut self, setup_future_usage: storage_enums::FutureUsage, ) { todo!() } fn set_prerouting_algorithm_in_payment_intent( &mut self, prerouting_algorithm: storage::PaymentRoutingInfo, ) { self.payment_intent.prerouting_algorithm = Some(prerouting_algorithm); } fn set_connector_in_payment_attempt(&mut self, _connector: Option<String>) { todo!() } fn set_connector_request_reference_id(&mut self, _reference_id: Option<String>) { todo!() } fn set_connector_response_reference_id(&mut self, _reference_id: Option<String>) { todo!() } fn set_vault_session_details( &mut self, _external_vault_session_details: Option<api::VaultSessionDetails>, ) { todo!() } fn set_routing_approach_in_attempt( &mut self, _routing_approach: Option<enums::RoutingApproach>, ) { todo!() } fn set_connector_request_reference_id_in_payment_attempt( &mut self, _connector_request_reference_id: String, ) { todo!() } fn set_cancellation_reason(&mut self, cancellation_reason: Option<String>) { self.payment_attempt.cancellation_reason = cancellation_reason; } }
{ "crate": "router", "file": "crates/router/src/core/payments.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 5, "num_tables": null, "score": null, "total_crates": null }
file_router_9097432587682119913
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/unified_connector_service.rs // Contains: 1 structs, 0 enums use std::{str::FromStr, time::Instant}; use api_models::admin; #[cfg(feature = "v2")] use base64::Engine; use common_enums::{ connector_enums::Connector, AttemptStatus, ConnectorIntegrationType, ExecutionMode, ExecutionPath, GatewaySystem, PaymentMethodType, ShadowRolloutAvailability, UcsAvailability, }; #[cfg(feature = "v2")] use common_utils::consts::BASE64_ENGINE; use common_utils::{ consts::X_FLOW_NAME, errors::CustomResult, ext_traits::ValueExt, request::{Method, RequestBuilder, RequestContent}, }; use diesel_models::types::FeatureMetadata; use error_stack::ResultExt; use external_services::{ grpc_client::{ unified_connector_service::{ConnectorAuthMetadata, UnifiedConnectorServiceError}, LineageIds, }, http_client, }; use hyperswitch_connectors::utils::CardData; #[cfg(feature = "v2")] use hyperswitch_domain_models::merchant_connector_account::{ ExternalVaultConnectorMetadata, MerchantConnectorAccountTypeDetails, }; use hyperswitch_domain_models::{ merchant_context::MerchantContext, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_response_types::PaymentsResponseData, }; use masking::{ExposeInterface, PeekInterface, Secret}; use router_env::{instrument, logger, tracing}; use unified_connector_service_cards::CardNumber; use unified_connector_service_client::payments::{ self as payments_grpc, payment_method::PaymentMethod, CardDetails, CardPaymentMethodType, PaymentServiceAuthorizeResponse, RewardPaymentMethodType, }; #[cfg(feature = "v2")] use crate::types::api::enums as api_enums; use crate::{ consts, core::{ errors::{self, RouterResult}, payments::{ helpers::{ is_ucs_enabled, should_execute_based_on_rollout, MerchantConnectorAccountType, }, OperationSessionGetters, OperationSessionSetters, }, utils::get_flow_name, }, events::connector_api_logs::ConnectorEvent, headers::{CONTENT_TYPE, X_REQUEST_ID}, routes::SessionState, types::transformers::ForeignTryFrom, }; pub mod transformers; // Re-export webhook transformer types for easier access pub use transformers::WebhookTransformData; /// Type alias for return type used by unified connector service response handlers type UnifiedConnectorServiceResult = CustomResult< ( Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>, u16, ), UnifiedConnectorServiceError, >; /// Checks if the Unified Connector Service (UCS) is available for use async fn check_ucs_availability(state: &SessionState) -> UcsAvailability { let is_client_available = state.grpc_client.unified_connector_service_client.is_some(); let is_enabled = is_ucs_enabled(state, consts::UCS_ENABLED).await; match (is_client_available, is_enabled) { (true, true) => { router_env::logger::debug!("UCS is available and enabled"); UcsAvailability::Enabled } _ => { router_env::logger::debug!( "UCS client is {} and UCS is {} in configuration", if is_client_available { "available" } else { "not available" }, if is_enabled { "enabled" } else { "not enabled" } ); UcsAvailability::Disabled } } } /// Determines the connector integration type based on UCS configuration or on both async fn determine_connector_integration_type( state: &SessionState, connector: Connector, config_key: &str, ) -> RouterResult<ConnectorIntegrationType> { match state.conf.grpc_client.unified_connector_service.as_ref() { Some(ucs_config) => { let is_ucs_only = ucs_config.ucs_only_connectors.contains(&connector); let is_rollout_enabled = should_execute_based_on_rollout(state, config_key).await?; if is_ucs_only || is_rollout_enabled { router_env::logger::debug!( connector = ?connector, ucs_only_list = is_ucs_only, rollout_enabled = is_rollout_enabled, "Using UcsConnector" ); Ok(ConnectorIntegrationType::UcsConnector) } else { router_env::logger::debug!( connector = ?connector, "Using DirectConnector - not in ucs_only_list and rollout not enabled" ); Ok(ConnectorIntegrationType::DirectConnector) } } None => { router_env::logger::debug!( connector = ?connector, "UCS config not present, using DirectConnector" ); Ok(ConnectorIntegrationType::DirectConnector) } } } pub async fn should_call_unified_connector_service<F: Clone, T, D>( state: &SessionState, merchant_context: &MerchantContext, router_data: &RouterData<F, T, PaymentsResponseData>, payment_data: Option<&D>, ) -> RouterResult<ExecutionPath> where D: OperationSessionGetters<F>, { // Extract context information let merchant_id = merchant_context .get_merchant_account() .get_id() .get_string_repr(); let connector_name = &router_data.connector; let connector_enum = Connector::from_str(connector_name) .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven) .attach_printable_lazy(|| format!("Failed to parse connector name: {}", connector_name))?; let payment_method = router_data.payment_method.to_string(); let flow_name = get_flow_name::<F>()?; // Check UCS availability using idiomatic helper let ucs_availability = check_ucs_availability(state).await; // Build rollout keys let rollout_key = format!( "{}_{}_{}_{}_{}", consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX, merchant_id, connector_name, payment_method, flow_name ); // Determine connector integration type let connector_integration_type = determine_connector_integration_type(state, connector_enum, &rollout_key).await?; // Extract previous gateway from payment data let previous_gateway = payment_data.and_then(extract_gateway_system_from_payment_intent); let shadow_rollout_key = format!("{}_shadow", rollout_key); let shadow_rollout_availability = if should_execute_based_on_rollout(state, &shadow_rollout_key).await? { ShadowRolloutAvailability::IsAvailable } else { ShadowRolloutAvailability::NotAvailable }; // Single decision point using pattern matching let (gateway_system, execution_path) = if ucs_availability == UcsAvailability::Disabled { router_env::logger::debug!("UCS is disabled, using Direct gateway"); (GatewaySystem::Direct, ExecutionPath::Direct) } else { // UCS is enabled, call decide function decide_execution_path( connector_integration_type, previous_gateway, shadow_rollout_availability, )? }; router_env::logger::info!( "Payment gateway decision: gateway={:?}, execution_path={:?} - merchant_id={}, connector={}, payment_method={}, flow={}", gateway_system, execution_path, merchant_id, connector_name, payment_method, flow_name ); Ok(execution_path) } fn decide_execution_path( connector_type: ConnectorIntegrationType, previous_gateway: Option<GatewaySystem>, shadow_rollout_enabled: ShadowRolloutAvailability, ) -> RouterResult<(GatewaySystem, ExecutionPath)> { match (connector_type, previous_gateway, shadow_rollout_enabled) { // Case 1: DirectConnector with no previous gateway and no shadow rollout // This is a fresh payment request for a direct connector - use direct gateway ( ConnectorIntegrationType::DirectConnector, None, ShadowRolloutAvailability::NotAvailable, ) => Ok((GatewaySystem::Direct, ExecutionPath::Direct)), // Case 2: DirectConnector previously used Direct gateway, no shadow rollout // Continue using the same direct gateway for consistency ( ConnectorIntegrationType::DirectConnector, Some(GatewaySystem::Direct), ShadowRolloutAvailability::NotAvailable, ) => Ok((GatewaySystem::Direct, ExecutionPath::Direct)), // Case 3: DirectConnector previously used UCS, but now switching back to Direct (no shadow) // Migration scenario: UCS was used before, but now we're reverting to Direct ( ConnectorIntegrationType::DirectConnector, Some(GatewaySystem::UnifiedConnectorService), ShadowRolloutAvailability::NotAvailable, ) => Ok((GatewaySystem::Direct, ExecutionPath::Direct)), // Case 4: UcsConnector configuration, but previously used Direct gateway (no shadow) // Maintain Direct for backward compatibility - don't switch mid-transaction ( ConnectorIntegrationType::UcsConnector, Some(GatewaySystem::Direct), ShadowRolloutAvailability::NotAvailable, ) => Ok((GatewaySystem::Direct, ExecutionPath::Direct)), // Case 5: DirectConnector with no previous gateway, shadow rollout enabled // Use Direct as primary, but also execute UCS in shadow mode for comparison ( ConnectorIntegrationType::DirectConnector, None, ShadowRolloutAvailability::IsAvailable, ) => Ok(( GatewaySystem::Direct, ExecutionPath::ShadowUnifiedConnectorService, )), // Case 6: DirectConnector previously used Direct, shadow rollout enabled // Continue with Direct as primary, execute UCS in shadow mode for testing ( ConnectorIntegrationType::DirectConnector, Some(GatewaySystem::Direct), ShadowRolloutAvailability::IsAvailable, ) => Ok(( GatewaySystem::Direct, ExecutionPath::ShadowUnifiedConnectorService, )), // Case 7: DirectConnector previously used UCS, shadow rollout enabled // Revert to Direct as primary, but keep UCS in shadow mode for comparison ( ConnectorIntegrationType::DirectConnector, Some(GatewaySystem::UnifiedConnectorService), ShadowRolloutAvailability::IsAvailable, ) => Ok(( GatewaySystem::Direct, ExecutionPath::ShadowUnifiedConnectorService, )), // Case 8: UcsConnector configuration, previously used Direct, shadow rollout enabled // Maintain Direct as primary for transaction consistency, shadow UCS for testing ( ConnectorIntegrationType::UcsConnector, Some(GatewaySystem::Direct), ShadowRolloutAvailability::IsAvailable, ) => Ok(( GatewaySystem::Direct, ExecutionPath::ShadowUnifiedConnectorService, )), // Case 9: UcsConnector with no previous gateway (regardless of shadow rollout) // Fresh payment for a UCS-enabled connector - use UCS as primary (ConnectorIntegrationType::UcsConnector, None, _) => Ok(( GatewaySystem::UnifiedConnectorService, ExecutionPath::UnifiedConnectorService, )), // Case 10: UcsConnector previously used UCS (regardless of shadow rollout) // Continue using UCS for consistency in the payment flow ( ConnectorIntegrationType::UcsConnector, Some(GatewaySystem::UnifiedConnectorService), _, ) => Ok(( GatewaySystem::UnifiedConnectorService, ExecutionPath::UnifiedConnectorService, )), } } /// Extracts the gateway system from the payment intent's feature metadata /// Returns None if metadata is missing, corrupted, or doesn't contain gateway_system fn extract_gateway_system_from_payment_intent<F: Clone, D>( payment_data: &D, ) -> Option<GatewaySystem> where D: OperationSessionGetters<F>, { #[cfg(feature = "v1")] { payment_data .get_payment_intent() .feature_metadata .as_ref() .and_then(|metadata| { // Try to parse the JSON value as FeatureMetadata // Log errors but don't fail the flow for corrupted metadata match serde_json::from_value::<FeatureMetadata>(metadata.clone()) { Ok(feature_metadata) => feature_metadata.gateway_system, Err(err) => { router_env::logger::warn!( "Failed to parse feature_metadata for gateway_system extraction: {}", err ); None } } }) } #[cfg(feature = "v2")] { None // V2 does not use feature metadata for gateway system tracking } } /// Updates the payment intent's feature metadata to track the gateway system being used #[cfg(feature = "v1")] pub fn update_gateway_system_in_feature_metadata<F: Clone, D>( payment_data: &mut D, gateway_system: GatewaySystem, ) -> RouterResult<()> where D: OperationSessionGetters<F> + OperationSessionSetters<F>, { let mut payment_intent = payment_data.get_payment_intent().clone(); let existing_metadata = payment_intent.feature_metadata.as_ref(); let mut feature_metadata = existing_metadata .and_then(|metadata| serde_json::from_value::<FeatureMetadata>(metadata.clone()).ok()) .unwrap_or_default(); feature_metadata.gateway_system = Some(gateway_system); let updated_metadata = serde_json::to_value(feature_metadata) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize feature metadata")?; payment_intent.feature_metadata = Some(updated_metadata.clone()); payment_data.set_payment_intent(payment_intent); Ok(()) } pub async fn should_call_unified_connector_service_for_webhooks( state: &SessionState, merchant_context: &MerchantContext, connector_name: &str, ) -> RouterResult<bool> { if state.grpc_client.unified_connector_service_client.is_none() { logger::debug!( connector = connector_name.to_string(), "Unified Connector Service client is not available for webhooks" ); return Ok(false); } let ucs_config_key = consts::UCS_ENABLED; if !is_ucs_enabled(state, ucs_config_key).await { return Ok(false); } let merchant_id = merchant_context .get_merchant_account() .get_id() .get_string_repr(); let config_key = format!( "{}_{}_{}_Webhooks", consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX, merchant_id, connector_name ); let should_execute = should_execute_based_on_rollout(state, &config_key).await?; Ok(should_execute) } pub fn build_unified_connector_service_payment_method( payment_method_data: hyperswitch_domain_models::payment_method_data::PaymentMethodData, payment_method_type: PaymentMethodType, ) -> CustomResult<payments_grpc::PaymentMethod, UnifiedConnectorServiceError> { match payment_method_data { hyperswitch_domain_models::payment_method_data::PaymentMethodData::Card(card) => { let card_exp_month = card .get_card_expiry_month_2_digit() .attach_printable("Failed to extract 2-digit expiry month from card") .change_context(UnifiedConnectorServiceError::InvalidDataFormat { field_name: "card_exp_month", })? .peek() .to_string(); let card_network = card .card_network .clone() .map(payments_grpc::CardNetwork::foreign_try_from) .transpose()?; let card_details = CardDetails { card_number: Some( CardNumber::from_str(&card.card_number.get_card_no()).change_context( UnifiedConnectorServiceError::RequestEncodingFailedWithReason( "Failed to parse card number".to_string(), ), )?, ), card_exp_month: Some(card_exp_month.into()), card_exp_year: Some(card.get_expiry_year_4_digit().expose().into()), card_cvc: Some(card.card_cvc.expose().into()), card_holder_name: card.card_holder_name.map(|name| name.expose().into()), card_issuer: card.card_issuer.clone(), card_network: card_network.map(|card_network| card_network.into()), card_type: card.card_type.clone(), bank_code: card.bank_code.clone(), nick_name: card.nick_name.map(|n| n.expose()), card_issuing_country_alpha2: card.card_issuing_country.clone(), }; let grpc_card_type = match payment_method_type { PaymentMethodType::Credit => { payments_grpc::card_payment_method_type::CardType::Credit(card_details) } PaymentMethodType::Debit => { payments_grpc::card_payment_method_type::CardType::Debit(card_details) } _ => { return Err(UnifiedConnectorServiceError::NotImplemented(format!( "Unimplemented payment method subtype: {payment_method_type:?}" )) .into()); } }; Ok(payments_grpc::PaymentMethod { payment_method: Some(PaymentMethod::Card(CardPaymentMethodType { card_type: Some(grpc_card_type), })), }) } hyperswitch_domain_models::payment_method_data::PaymentMethodData::Upi(upi_data) => { let upi_type = match upi_data { hyperswitch_domain_models::payment_method_data::UpiData::UpiCollect( upi_collect_data, ) => { let upi_details = payments_grpc::UpiCollect { vpa_id: upi_collect_data.vpa_id.map(|vpa| vpa.expose().into()), }; PaymentMethod::UpiCollect(upi_details) } hyperswitch_domain_models::payment_method_data::UpiData::UpiIntent(_) => { let upi_details = payments_grpc::UpiIntent { app_name: None }; PaymentMethod::UpiIntent(upi_details) } hyperswitch_domain_models::payment_method_data::UpiData::UpiQr(_) => { let upi_details = payments_grpc::UpiQr {}; PaymentMethod::UpiQr(upi_details) } }; Ok(payments_grpc::PaymentMethod { payment_method: Some(upi_type), }) } hyperswitch_domain_models::payment_method_data::PaymentMethodData::Reward => { match payment_method_type { PaymentMethodType::ClassicReward => Ok(payments_grpc::PaymentMethod { payment_method: Some(PaymentMethod::Reward(RewardPaymentMethodType { reward_type: 1, })), }), PaymentMethodType::Evoucher => Ok(payments_grpc::PaymentMethod { payment_method: Some(PaymentMethod::Reward(RewardPaymentMethodType { reward_type: 2, })), }), _ => Err(UnifiedConnectorServiceError::NotImplemented(format!( "Unimplemented payment method subtype: {payment_method_type:?}" )) .into()), } } _ => Err(UnifiedConnectorServiceError::NotImplemented(format!( "Unimplemented payment method: {payment_method_data:?}" )) .into()), } } pub fn build_unified_connector_service_payment_method_for_external_proxy( payment_method_data: hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData, payment_method_type: PaymentMethodType, ) -> CustomResult<payments_grpc::PaymentMethod, UnifiedConnectorServiceError> { match payment_method_data { hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::Card( external_vault_card, ) => { let card_network = external_vault_card .card_network .clone() .map(payments_grpc::CardNetwork::foreign_try_from) .transpose()?; let card_details = CardDetails { card_number: Some(CardNumber::from_str(external_vault_card.card_number.peek()).change_context( UnifiedConnectorServiceError::RequestEncodingFailedWithReason("Failed to parse card number".to_string()) )?), card_exp_month: Some(external_vault_card.card_exp_month.expose().into()), card_exp_year: Some(external_vault_card.card_exp_year.expose().into()), card_cvc: Some(external_vault_card.card_cvc.expose().into()), card_holder_name: external_vault_card.card_holder_name.map(|name| name.expose().into()), card_issuer: external_vault_card.card_issuer.clone(), card_network: card_network.map(|card_network| card_network.into()), card_type: external_vault_card.card_type.clone(), bank_code: external_vault_card.bank_code.clone(), nick_name: external_vault_card.nick_name.map(|n| n.expose()), card_issuing_country_alpha2: external_vault_card.card_issuing_country.clone(), }; let grpc_card_type = match payment_method_type { PaymentMethodType::Credit => { payments_grpc::card_payment_method_type::CardType::CreditProxy(card_details) } PaymentMethodType::Debit => { payments_grpc::card_payment_method_type::CardType::DebitProxy(card_details) } _ => { return Err(UnifiedConnectorServiceError::NotImplemented(format!( "Unimplemented payment method subtype: {payment_method_type:?}" )) .into()); } }; Ok(payments_grpc::PaymentMethod { payment_method: Some(PaymentMethod::Card(CardPaymentMethodType { card_type: Some(grpc_card_type), })), }) } hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::VaultToken(_) => { Err(UnifiedConnectorServiceError::NotImplemented(format!( "Unimplemented payment method subtype: {payment_method_type:?}" )) .into()) } } } pub fn build_unified_connector_service_auth_metadata( #[cfg(feature = "v1")] merchant_connector_account: MerchantConnectorAccountType, #[cfg(feature = "v2")] merchant_connector_account: MerchantConnectorAccountTypeDetails, merchant_context: &MerchantContext, ) -> CustomResult<ConnectorAuthMetadata, UnifiedConnectorServiceError> { #[cfg(feature = "v1")] let auth_type: ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(UnifiedConnectorServiceError::FailedToObtainAuthType) .attach_printable("Failed while parsing value for ConnectorAuthType")?; #[cfg(feature = "v2")] let auth_type: ConnectorAuthType = merchant_connector_account .get_connector_account_details() .change_context(UnifiedConnectorServiceError::FailedToObtainAuthType) .attach_printable("Failed to obtain ConnectorAuthType")?; let connector_name = { #[cfg(feature = "v1")] { merchant_connector_account .get_connector_name() .ok_or(UnifiedConnectorServiceError::MissingConnectorName) .attach_printable("Missing connector name")? } #[cfg(feature = "v2")] { merchant_connector_account .get_connector_name() .map(|connector| connector.to_string()) .ok_or(UnifiedConnectorServiceError::MissingConnectorName) .attach_printable("Missing connector name")? } }; let merchant_id = merchant_context .get_merchant_account() .get_id() .get_string_repr(); match &auth_type { ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Ok(ConnectorAuthMetadata { connector_name, auth_type: consts::UCS_AUTH_SIGNATURE_KEY.to_string(), api_key: Some(api_key.clone()), key1: Some(key1.clone()), api_secret: Some(api_secret.clone()), auth_key_map: None, merchant_id: Secret::new(merchant_id.to_string()), }), ConnectorAuthType::BodyKey { api_key, key1 } => Ok(ConnectorAuthMetadata { connector_name, auth_type: consts::UCS_AUTH_BODY_KEY.to_string(), api_key: Some(api_key.clone()), key1: Some(key1.clone()), api_secret: None, auth_key_map: None, merchant_id: Secret::new(merchant_id.to_string()), }), ConnectorAuthType::HeaderKey { api_key } => Ok(ConnectorAuthMetadata { connector_name, auth_type: consts::UCS_AUTH_HEADER_KEY.to_string(), api_key: Some(api_key.clone()), key1: None, api_secret: None, auth_key_map: None, merchant_id: Secret::new(merchant_id.to_string()), }), ConnectorAuthType::CurrencyAuthKey { auth_key_map } => Ok(ConnectorAuthMetadata { connector_name, auth_type: consts::UCS_AUTH_CURRENCY_AUTH_KEY.to_string(), api_key: None, key1: None, api_secret: None, auth_key_map: Some(auth_key_map.clone()), merchant_id: Secret::new(merchant_id.to_string()), }), _ => Err(UnifiedConnectorServiceError::FailedToObtainAuthType) .attach_printable("Unsupported ConnectorAuthType for header injection"), } } #[cfg(feature = "v2")] pub fn build_unified_connector_service_external_vault_proxy_metadata( external_vault_merchant_connector_account: MerchantConnectorAccountTypeDetails, ) -> CustomResult<String, UnifiedConnectorServiceError> { let external_vault_metadata = external_vault_merchant_connector_account .get_metadata() .ok_or(UnifiedConnectorServiceError::ParsingFailed) .attach_printable("Failed to obtain ConnectorMetadata")?; let connector_name = external_vault_merchant_connector_account .get_connector_name() .map(|connector| connector.to_string()) .ok_or(UnifiedConnectorServiceError::MissingConnectorName) .attach_printable("Missing connector name")?; // always get the connector name from this call let external_vault_connector = api_enums::VaultConnectors::from_str(&connector_name) .change_context(UnifiedConnectorServiceError::InvalidConnectorName) .attach_printable("Failed to parse Vault connector")?; let unified_service_vault_metdata = match external_vault_connector { api_enums::VaultConnectors::Vgs => { let vgs_metadata: ExternalVaultConnectorMetadata = external_vault_metadata .expose() .parse_value("ExternalVaultConnectorMetadata") .change_context(UnifiedConnectorServiceError::ParsingFailed) .attach_printable("Failed to parse Vgs connector metadata")?; Some(external_services::grpc_client::unified_connector_service::ExternalVaultProxyMetadata::VgsMetadata( external_services::grpc_client::unified_connector_service::VgsMetadata { proxy_url: vgs_metadata.proxy_url, certificate: vgs_metadata.certificate, } )) } api_enums::VaultConnectors::HyperswitchVault | api_enums::VaultConnectors::Tokenex => None, }; match unified_service_vault_metdata { Some(metdata) => { let external_vault_metadata_bytes = serde_json::to_vec(&metdata) .change_context(UnifiedConnectorServiceError::ParsingFailed) .attach_printable("Failed to convert External vault metadata to bytes")?; Ok(BASE64_ENGINE.encode(&external_vault_metadata_bytes)) } None => Err(UnifiedConnectorServiceError::NotImplemented( "External vault proxy metadata is not supported for {connector_name}".to_string(), ) .into()), } } pub fn handle_unified_connector_service_response_for_payment_authorize( response: PaymentServiceAuthorizeResponse, ) -> UnifiedConnectorServiceResult { let status_code = transformers::convert_connector_service_status_code(response.status_code)?; let router_data_response = Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(response)?; Ok((router_data_response, status_code)) } pub fn handle_unified_connector_service_response_for_payment_register( response: payments_grpc::PaymentServiceRegisterResponse, ) -> UnifiedConnectorServiceResult { let status_code = transformers::convert_connector_service_status_code(response.status_code)?; let router_data_response = Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(response)?; Ok((router_data_response, status_code)) } pub fn handle_unified_connector_service_response_for_payment_repeat( response: payments_grpc::PaymentServiceRepeatEverythingResponse, ) -> UnifiedConnectorServiceResult { let status_code = transformers::convert_connector_service_status_code(response.status_code)?; let router_data_response = Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(response)?; Ok((router_data_response, status_code)) } pub fn build_webhook_secrets_from_merchant_connector_account( #[cfg(feature = "v1")] merchant_connector_account: &MerchantConnectorAccountType, #[cfg(feature = "v2")] merchant_connector_account: &MerchantConnectorAccountTypeDetails, ) -> CustomResult<Option<payments_grpc::WebhookSecrets>, UnifiedConnectorServiceError> { // Extract webhook credentials from merchant connector account // This depends on how webhook secrets are stored in the merchant connector account #[cfg(feature = "v1")] let webhook_details = merchant_connector_account .get_webhook_details() .map_err(|_| UnifiedConnectorServiceError::FailedToObtainAuthType)?; #[cfg(feature = "v2")] let webhook_details = match merchant_connector_account { MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(mca) => { mca.connector_webhook_details.as_ref() } MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => None, }; match webhook_details { Some(details) => { // Parse the webhook details JSON to extract secrets let webhook_details: admin::MerchantConnectorWebhookDetails = details .clone() .parse_value("MerchantConnectorWebhookDetails") .change_context(UnifiedConnectorServiceError::FailedToObtainAuthType) .attach_printable("Failed to parse MerchantConnectorWebhookDetails")?; // Build gRPC WebhookSecrets from parsed details Ok(Some(payments_grpc::WebhookSecrets { secret: webhook_details.merchant_secret.expose().to_string(), additional_secret: webhook_details .additional_secret .map(|secret| secret.expose().to_string()), })) } None => Ok(None), } } /// High-level abstraction for calling UCS webhook transformation /// This provides a clean interface similar to payment flow UCS calls pub async fn call_unified_connector_service_for_webhook( state: &SessionState, merchant_context: &MerchantContext, connector_name: &str, body: &actix_web::web::Bytes, request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>, merchant_connector_account: Option< &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, >, ) -> RouterResult<( api_models::webhooks::IncomingWebhookEvent, bool, WebhookTransformData, )> { let ucs_client = state .grpc_client .unified_connector_service_client .as_ref() .ok_or_else(|| { error_stack::report!(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("UCS client is not available for webhook processing") })?; // Build webhook secrets from merchant connector account let webhook_secrets = merchant_connector_account.and_then(|mca| { #[cfg(feature = "v1")] let mca_type = MerchantConnectorAccountType::DbVal(Box::new(mca.clone())); #[cfg(feature = "v2")] let mca_type = MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(mca.clone())); build_webhook_secrets_from_merchant_connector_account(&mca_type) .map_err(|e| { logger::warn!( build_error=?e, connector_name=connector_name, "Failed to build webhook secrets from merchant connector account in call_unified_connector_service_for_webhook" ); e }) .ok() .flatten() }); // Build UCS transform request using new webhook transformers let transform_request = transformers::build_webhook_transform_request( body, request_details, webhook_secrets, merchant_context .get_merchant_account() .get_id() .get_string_repr(), connector_name, )?; // Build connector auth metadata let connector_auth_metadata = merchant_connector_account .map(|mca| { #[cfg(feature = "v1")] let mca_type = MerchantConnectorAccountType::DbVal(Box::new(mca.clone())); #[cfg(feature = "v2")] let mca_type = MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new( mca.clone(), )); build_unified_connector_service_auth_metadata(mca_type, merchant_context) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to build UCS auth metadata")? .ok_or_else(|| { error_stack::report!(errors::ApiErrorResponse::InternalServerError).attach_printable( "Missing merchant connector account for UCS webhook transformation", ) })?; let profile_id = merchant_connector_account .as_ref() .map(|mca| mca.profile_id.clone()) .unwrap_or(consts::PROFILE_ID_UNAVAILABLE.clone()); // Build gRPC headers let grpc_headers = state .get_grpc_headers_ucs(ExecutionMode::Primary) .lineage_ids(LineageIds::new( merchant_context.get_merchant_account().get_id().clone(), profile_id, )) .external_vault_proxy_metadata(None) .merchant_reference_id(None) .build(); // Make UCS call - client availability already verified match ucs_client .transform_incoming_webhook(transform_request, connector_auth_metadata, grpc_headers) .await { Ok(response) => { let transform_response = response.into_inner(); let transform_data = transformers::transform_ucs_webhook_response(transform_response)?; // UCS handles everything internally - event type, source verification, decoding Ok(( transform_data.event_type, transform_data.source_verified, transform_data, )) } Err(err) => { // When UCS is configured, we don't fall back to direct connector processing Err(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable(format!("UCS webhook processing failed: {err}")) } } } /// Extract webhook content from UCS response for further processing /// This provides a helper function to extract specific data from UCS responses pub fn extract_webhook_content_from_ucs_response( transform_data: &WebhookTransformData, ) -> Option<&unified_connector_service_client::payments::WebhookResponseContent> { transform_data.webhook_content.as_ref() } /// UCS Event Logging Wrapper Function /// This function wraps UCS calls with comprehensive event logging. /// It logs the actual gRPC request/response data, timing, and error information. #[instrument(skip_all, fields(connector_name, flow_type, payment_id))] pub async fn ucs_logging_wrapper<T, F, Fut, Req, Resp, GrpcReq, GrpcResp>( router_data: RouterData<T, Req, Resp>, state: &SessionState, grpc_request: GrpcReq, grpc_header_builder: external_services::grpc_client::GrpcHeadersUcsBuilderFinal, handler: F, ) -> RouterResult<RouterData<T, Req, Resp>> where T: std::fmt::Debug + Clone + Send + 'static, Req: std::fmt::Debug + Clone + Send + Sync + 'static, Resp: std::fmt::Debug + Clone + Send + Sync + 'static, GrpcReq: serde::Serialize, GrpcResp: serde::Serialize, F: FnOnce( RouterData<T, Req, Resp>, GrpcReq, external_services::grpc_client::GrpcHeadersUcs, ) -> Fut + Send, Fut: std::future::Future<Output = RouterResult<(RouterData<T, Req, Resp>, GrpcResp)>> + Send, { tracing::Span::current().record("connector_name", &router_data.connector); tracing::Span::current().record("flow_type", std::any::type_name::<T>()); tracing::Span::current().record("payment_id", &router_data.payment_id); // Capture request data for logging let connector_name = router_data.connector.clone(); let payment_id = router_data.payment_id.clone(); let merchant_id = router_data.merchant_id.clone(); let refund_id = router_data.refund_id.clone(); let dispute_id = router_data.dispute_id.clone(); let grpc_header = grpc_header_builder.build(); // Log the actual gRPC request with masking let grpc_request_body = masking::masked_serialize(&grpc_request) .unwrap_or_else(|_| serde_json::json!({"error": "failed_to_serialize_grpc_request"})); // Update connector call count metrics for UCS operations crate::routes::metrics::CONNECTOR_CALL_COUNT.add( 1, router_env::metric_attributes!( ("connector", connector_name.clone()), ( "flow", std::any::type_name::<T>() .split("::") .last() .unwrap_or_default() ), ), ); // Execute UCS function and measure timing let start_time = Instant::now(); let result = handler(router_data, grpc_request, grpc_header).await; let external_latency = start_time.elapsed().as_millis(); // Create and emit connector event after UCS call let (status_code, response_body, router_result) = match result { Ok((updated_router_data, grpc_response)) => { let status = updated_router_data .connector_http_status_code .unwrap_or(200); // Log the actual gRPC response let grpc_response_body = serde_json::to_value(&grpc_response).unwrap_or_else( |_| serde_json::json!({"error": "failed_to_serialize_grpc_response"}), ); (status, Some(grpc_response_body), Ok(updated_router_data)) } Err(error) => { // Update error metrics for UCS calls crate::routes::metrics::CONNECTOR_ERROR_RESPONSE_COUNT.add( 1, router_env::metric_attributes!(("connector", connector_name.clone(),)), ); let error_body = serde_json::json!({ "error": error.to_string(), "error_type": "ucs_call_failed" }); (500, Some(error_body), Err(error)) } }; let mut connector_event = ConnectorEvent::new( state.tenant.tenant_id.clone(), connector_name, std::any::type_name::<T>(), grpc_request_body, "grpc://unified-connector-service".to_string(), Method::Post, payment_id, merchant_id, state.request_id.as_ref(), external_latency, refund_id, dispute_id, status_code, ); // Set response body based on status code if let Some(body) = response_body { match status_code { 400..=599 => { connector_event.set_error_response_body(&body); } _ => { connector_event.set_response_body(&body); } } } // Emit event state.event_handler.log_event(&connector_event); router_result } #[derive(serde::Serialize)] pub struct ComparisonData { pub hyperswitch_data: Secret<serde_json::Value>, pub unified_connector_service_data: Secret<serde_json::Value>, } /// Sends router data comparison to external service pub async fn send_comparison_data( state: &SessionState, comparison_data: ComparisonData, ) -> RouterResult<()> { // Check if comparison service is enabled let comparison_config = match state.conf.comparison_service.as_ref() { Some(comparison_config) => comparison_config, None => { tracing::warn!( "Comparison service configuration missing, skipping comparison data send" ); return Ok(()); } }; let mut request = RequestBuilder::new() .method(Method::Post) .url(comparison_config.url.get_string_repr()) .header(CONTENT_TYPE, "application/json") .header(X_FLOW_NAME, "router-data") .set_body(RequestContent::Json(Box::new(comparison_data))) .build(); if let Some(req_id) = &state.request_id { request.add_header(X_REQUEST_ID, masking::Maskable::Normal(req_id.to_string())); } let _ = http_client::send_request(&state.conf.proxy, request, comparison_config.timeout_secs) .await .map_err(|e| { tracing::debug!("Error sending comparison data: {:?}", e); }); Ok(()) }
{ "crate": "router", "file": "crates/router/src/core/unified_connector_service.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-8936069190441352951
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/api_keys.rs // Contains: 1 structs, 0 enums use common_utils::date_time; #[cfg(feature = "email")] use diesel_models::{api_keys::ApiKey, enums as storage_enums}; use error_stack::{report, ResultExt}; use masking::{PeekInterface, StrongSecret}; use router_env::{instrument, tracing}; use crate::{ configs::settings, consts, core::errors::{self, RouterResponse, StorageErrorExt}, db::domain, routes::{metrics, SessionState}, services::{authentication, ApplicationResponse}, types::{api, storage, transformers::ForeignInto}, }; #[cfg(feature = "email")] const API_KEY_EXPIRY_TAG: &str = "API_KEY"; #[cfg(feature = "email")] const API_KEY_EXPIRY_NAME: &str = "API_KEY_EXPIRY"; #[cfg(feature = "email")] const API_KEY_EXPIRY_RUNNER: diesel_models::ProcessTrackerRunner = diesel_models::ProcessTrackerRunner::ApiKeyExpiryWorkflow; static HASH_KEY: once_cell::sync::OnceCell<StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> = once_cell::sync::OnceCell::new(); impl settings::ApiKeys { pub fn get_hash_key( &self, ) -> errors::RouterResult<&'static StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> { HASH_KEY.get_or_try_init(|| { <[u8; PlaintextApiKey::HASH_KEY_LEN]>::try_from( hex::decode(self.hash_key.peek()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("API key hash key has invalid hexadecimal data")? .as_slice(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("The API hashing key has incorrect length") .map(StrongSecret::new) }) } } // Defining new types `PlaintextApiKey` and `HashedApiKey` in the hopes of reducing the possibility // of plaintext API key being stored in the data store. pub struct PlaintextApiKey(StrongSecret<String>); #[derive(Debug, PartialEq, Eq)] pub struct HashedApiKey(String); impl PlaintextApiKey { const HASH_KEY_LEN: usize = 32; const PREFIX_LEN: usize = 12; pub fn new(length: usize) -> Self { let env = router_env::env::prefix_for_env(); let key = common_utils::crypto::generate_cryptographically_secure_random_string(length); Self(format!("{env}_{key}").into()) } pub fn new_key_id() -> common_utils::id_type::ApiKeyId { let env = router_env::env::prefix_for_env(); common_utils::id_type::ApiKeyId::generate_key_id(env) } pub fn prefix(&self) -> String { self.0.peek().chars().take(Self::PREFIX_LEN).collect() } pub fn peek(&self) -> &str { self.0.peek() } pub fn keyed_hash(&self, key: &[u8; Self::HASH_KEY_LEN]) -> HashedApiKey { /* Decisions regarding API key hashing algorithm chosen: - Since API key hash verification would be done for each request, there is a requirement for the hashing to be quick. - Password hashing algorithms would not be suitable for this purpose as they're designed to prevent brute force attacks, considering that the same password could be shared across multiple sites by the user. - Moreover, password hash verification happens once per user session, so the delay involved is negligible, considering the security benefits it provides. While with API keys (assuming uniqueness of keys across the application), the delay involved in hashing (with the use of a password hashing algorithm) becomes significant, considering that it must be done per request. - Since we are the only ones generating API keys and are able to guarantee their uniqueness, a simple hash algorithm is sufficient for this purpose. Hash algorithms considered: - Password hashing algorithms: Argon2id and PBKDF2 - Simple hashing algorithms: HMAC-SHA256, HMAC-SHA512, BLAKE3 After benchmarking the simple hashing algorithms, we decided to go with the BLAKE3 keyed hashing algorithm, with a randomly generated key for the hash key. */ HashedApiKey( blake3::keyed_hash(key, self.0.peek().as_bytes()) .to_hex() .to_string(), ) } } #[instrument(skip_all)] pub async fn create_api_key( state: SessionState, api_key: api::CreateApiKeyRequest, key_store: domain::MerchantKeyStore, ) -> RouterResponse<api::CreateApiKeyResponse> { let api_key_config = state.conf.api_keys.get_inner(); let store = state.store.as_ref(); let merchant_id = key_store.merchant_id.clone(); let hash_key = api_key_config.get_hash_key()?; let plaintext_api_key = PlaintextApiKey::new(consts::API_KEY_LENGTH); let api_key = storage::ApiKeyNew { key_id: PlaintextApiKey::new_key_id(), merchant_id: merchant_id.to_owned(), name: api_key.name, description: api_key.description, hashed_api_key: plaintext_api_key.keyed_hash(hash_key.peek()).into(), prefix: plaintext_api_key.prefix(), created_at: date_time::now(), expires_at: api_key.expiration.into(), last_used: None, }; let api_key = store .insert_api_key(api_key) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to insert new API key")?; let state_inner = state.clone(); let hashed_api_key = api_key.hashed_api_key.clone(); let merchant_id_inner = merchant_id.clone(); let key_id = api_key.key_id.clone(); let expires_at = api_key.expires_at; authentication::decision::spawn_tracked_job( async move { authentication::decision::add_api_key( &state_inner, hashed_api_key.into_inner().into(), merchant_id_inner, key_id, expires_at.map(authentication::decision::convert_expiry), ) .await }, authentication::decision::ADD, ); metrics::API_KEY_CREATED.add( 1, router_env::metric_attributes!(("merchant", merchant_id.clone())), ); // Add process to process_tracker for email reminder, only if expiry is set to future date // If the `api_key` is set to expire in less than 7 days, the merchant is not notified about it's expiry #[cfg(feature = "email")] { if api_key.expires_at.is_some() { let expiry_reminder_days = state.conf.api_keys.get_inner().expiry_reminder_days.clone(); add_api_key_expiry_task(store, &api_key, expiry_reminder_days) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to insert API key expiry reminder to process tracker")?; } } Ok(ApplicationResponse::Json( (api_key, plaintext_api_key).foreign_into(), )) } // Add api_key_expiry task to the process_tracker table. // Construct ProcessTrackerNew struct with all required fields, and schedule the first email. // After first email has been sent, update the schedule_time based on retry_count in execute_workflow(). // A task is not scheduled if the time for the first email is in the past. #[cfg(feature = "email")] #[instrument(skip_all)] pub async fn add_api_key_expiry_task( store: &dyn crate::db::StorageInterface, api_key: &ApiKey, expiry_reminder_days: Vec<u8>, ) -> Result<(), errors::ProcessTrackerError> { let current_time = date_time::now(); let schedule_time = expiry_reminder_days .first() .and_then(|expiry_reminder_day| { api_key.expires_at.map(|expires_at| { expires_at.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day))) }) }) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to obtain initial process tracker schedule time")?; if schedule_time <= current_time { return Ok(()); } let api_key_expiry_tracker = storage::ApiKeyExpiryTrackingData { key_id: api_key.key_id.clone(), merchant_id: api_key.merchant_id.clone(), api_key_name: api_key.name.clone(), prefix: api_key.prefix.clone(), // We need API key expiry too, because we need to decide on the schedule_time in // execute_workflow() where we won't be having access to the Api key object. api_key_expiry: api_key.expires_at, expiry_reminder_days: expiry_reminder_days.clone(), }; let process_tracker_id = generate_task_id_for_api_key_expiry_workflow(&api_key.key_id); let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, API_KEY_EXPIRY_NAME, API_KEY_EXPIRY_RUNNER, [API_KEY_EXPIRY_TAG], api_key_expiry_tracker, None, schedule_time, common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct API key expiry process tracker task")?; store .insert_process(process_tracker_entry) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while inserting API key expiry reminder to process_tracker: {:?}", api_key.key_id ) })?; metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "ApiKeyExpiry"))); Ok(()) } #[instrument(skip_all)] pub async fn retrieve_api_key( state: SessionState, merchant_id: common_utils::id_type::MerchantId, key_id: common_utils::id_type::ApiKeyId, ) -> RouterResponse<api::RetrieveApiKeyResponse> { let store = state.store.as_ref(); let api_key = store .find_api_key_by_merchant_id_key_id_optional(&merchant_id, &key_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed .attach_printable("Failed to retrieve API key")? .ok_or(report!(errors::ApiErrorResponse::ApiKeyNotFound))?; // If retrieve returned `None` Ok(ApplicationResponse::Json(api_key.foreign_into())) } #[instrument(skip_all)] pub async fn update_api_key( state: SessionState, api_key: api::UpdateApiKeyRequest, ) -> RouterResponse<api::RetrieveApiKeyResponse> { let merchant_id = api_key.merchant_id.clone(); let key_id = api_key.key_id.clone(); let store = state.store.as_ref(); let api_key = store .update_api_key( merchant_id.to_owned(), key_id.to_owned(), api_key.foreign_into(), ) .await .to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound)?; let state_inner = state.clone(); let hashed_api_key = api_key.hashed_api_key.clone(); let key_id_inner = api_key.key_id.clone(); let expires_at = api_key.expires_at; authentication::decision::spawn_tracked_job( async move { authentication::decision::add_api_key( &state_inner, hashed_api_key.into_inner().into(), merchant_id.clone(), key_id_inner, expires_at.map(authentication::decision::convert_expiry), ) .await }, authentication::decision::ADD, ); #[cfg(feature = "email")] { let expiry_reminder_days = state.conf.api_keys.get_inner().expiry_reminder_days.clone(); let task_id = generate_task_id_for_api_key_expiry_workflow(&key_id); // In order to determine how to update the existing process in the process_tracker table, // we need access to the current entry in the table. let existing_process_tracker_task = store .find_process_by_id(task_id.as_str()) .await .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed .attach_printable( "Failed to retrieve API key expiry reminder task from process tracker", )?; // If process exist if existing_process_tracker_task.is_some() { if api_key.expires_at.is_some() { // Process exist in process, update the process with new schedule_time update_api_key_expiry_task(store, &api_key, expiry_reminder_days) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to update API key expiry reminder task in process tracker", )?; } // If an expiry is set to 'never' else { // Process exist in process, revoke it revoke_api_key_expiry_task(store, &key_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to revoke API key expiry reminder task in process tracker", )?; } } // This case occurs if the expiry for an API key is set to 'never' during its creation. If so, // process in tracker was not created. else if api_key.expires_at.is_some() { // Process doesn't exist in process_tracker table, so create new entry with // schedule_time based on new expiry set. add_api_key_expiry_task(store, &api_key, expiry_reminder_days) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to insert API key expiry reminder task to process tracker", )?; } } Ok(ApplicationResponse::Json(api_key.foreign_into())) } // Update api_key_expiry task in the process_tracker table. // Construct Update variant of ProcessTrackerUpdate with new tracking_data. // A task is not scheduled if the time for the first email is in the past. #[cfg(feature = "email")] #[instrument(skip_all)] pub async fn update_api_key_expiry_task( store: &dyn crate::db::StorageInterface, api_key: &ApiKey, expiry_reminder_days: Vec<u8>, ) -> Result<(), errors::ProcessTrackerError> { let current_time = date_time::now(); let schedule_time = expiry_reminder_days .first() .and_then(|expiry_reminder_day| { api_key.expires_at.map(|expires_at| { expires_at.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day))) }) }); if let Some(schedule_time) = schedule_time { if schedule_time <= current_time { return Ok(()); } } let task_id = generate_task_id_for_api_key_expiry_workflow(&api_key.key_id); let task_ids = vec![task_id.clone()]; let updated_tracking_data = &storage::ApiKeyExpiryTrackingData { key_id: api_key.key_id.clone(), merchant_id: api_key.merchant_id.clone(), api_key_name: api_key.name.clone(), prefix: api_key.prefix.clone(), api_key_expiry: api_key.expires_at, expiry_reminder_days, }; let updated_api_key_expiry_workflow_model = serde_json::to_value(updated_tracking_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("unable to serialize API key expiry tracker: {updated_tracking_data:?}") })?; let updated_process_tracker_data = storage::ProcessTrackerUpdate::Update { name: None, retry_count: Some(0), schedule_time, tracking_data: Some(updated_api_key_expiry_workflow_model), business_status: Some(String::from( diesel_models::process_tracker::business_status::PENDING, )), status: Some(storage_enums::ProcessTrackerStatus::New), updated_at: Some(current_time), }; store .process_tracker_update_process_status_by_ids(task_ids, updated_process_tracker_data) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; Ok(()) } #[instrument(skip_all)] pub async fn revoke_api_key( state: SessionState, merchant_id: common_utils::id_type::MerchantId, key_id: &common_utils::id_type::ApiKeyId, ) -> RouterResponse<api::RevokeApiKeyResponse> { let store = state.store.as_ref(); let api_key = store .find_api_key_by_merchant_id_key_id_optional(&merchant_id, key_id) .await .to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound)?; let revoked = store .revoke_api_key(&merchant_id, key_id) .await .to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound)?; if let Some(api_key) = api_key { let hashed_api_key = api_key.hashed_api_key; let state = state.clone(); authentication::decision::spawn_tracked_job( async move { authentication::decision::revoke_api_key(&state, hashed_api_key.into_inner().into()) .await }, authentication::decision::REVOKE, ); } metrics::API_KEY_REVOKED.add(1, &[]); #[cfg(feature = "email")] { let task_id = generate_task_id_for_api_key_expiry_workflow(key_id); // In order to determine how to update the existing process in the process_tracker table, // we need access to the current entry in the table. let existing_process_tracker_task = store .find_process_by_id(task_id.as_str()) .await .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed .attach_printable( "Failed to retrieve API key expiry reminder task from process tracker", )?; // If process exist, then revoke it if existing_process_tracker_task.is_some() { revoke_api_key_expiry_task(store, key_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to revoke API key expiry reminder task in process tracker", )?; } } Ok(ApplicationResponse::Json(api::RevokeApiKeyResponse { merchant_id: merchant_id.to_owned(), key_id: key_id.to_owned(), revoked, })) } // Function to revoke api_key_expiry task in the process_tracker table when API key is revoked. // Construct StatusUpdate variant of ProcessTrackerUpdate by setting status to 'finish'. #[cfg(feature = "email")] #[instrument(skip_all)] pub async fn revoke_api_key_expiry_task( store: &dyn crate::db::StorageInterface, key_id: &common_utils::id_type::ApiKeyId, ) -> Result<(), errors::ProcessTrackerError> { let task_id = generate_task_id_for_api_key_expiry_workflow(key_id); let task_ids = vec![task_id]; let updated_process_tracker_data = storage::ProcessTrackerUpdate::StatusUpdate { status: storage_enums::ProcessTrackerStatus::Finish, business_status: Some(String::from(diesel_models::business_status::REVOKED)), }; store .process_tracker_update_process_status_by_ids(task_ids, updated_process_tracker_data) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; Ok(()) } #[instrument(skip_all)] pub async fn list_api_keys( state: SessionState, merchant_id: common_utils::id_type::MerchantId, limit: Option<i64>, offset: Option<i64>, ) -> RouterResponse<Vec<api::RetrieveApiKeyResponse>> { let store = state.store.as_ref(); let api_keys = store .list_api_keys_by_merchant_id(&merchant_id, limit, offset) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to list merchant API keys")?; let api_keys = api_keys .into_iter() .map(ForeignInto::foreign_into) .collect(); Ok(ApplicationResponse::Json(api_keys)) } #[cfg(feature = "email")] fn generate_task_id_for_api_key_expiry_workflow( key_id: &common_utils::id_type::ApiKeyId, ) -> String { format!( "{API_KEY_EXPIRY_RUNNER}_{API_KEY_EXPIRY_NAME}_{}", key_id.get_string_repr() ) } impl From<&str> for PlaintextApiKey { fn from(s: &str) -> Self { Self(s.to_owned().into()) } } impl From<String> for PlaintextApiKey { fn from(s: String) -> Self { Self(s.into()) } } impl From<HashedApiKey> for storage::HashedApiKey { fn from(hashed_api_key: HashedApiKey) -> Self { hashed_api_key.0.into() } } impl From<storage::HashedApiKey> for HashedApiKey { fn from(hashed_api_key: storage::HashedApiKey) -> Self { Self(hashed_api_key.into_inner()) } } #[cfg(test)] mod tests { #![allow(clippy::expect_used, clippy::unwrap_used)] use super::*; #[tokio::test] async fn test_hashing_and_verification() { let settings = settings::Settings::new().expect("invalid settings"); let plaintext_api_key = PlaintextApiKey::new(consts::API_KEY_LENGTH); let hash_key = settings.api_keys.get_inner().get_hash_key().unwrap(); let hashed_api_key = plaintext_api_key.keyed_hash(hash_key.peek()); assert_ne!( plaintext_api_key.0.peek().as_bytes(), hashed_api_key.0.as_bytes() ); let new_hashed_api_key = plaintext_api_key.keyed_hash(hash_key.peek()); assert_eq!(hashed_api_key, new_hashed_api_key) } }
{ "crate": "router", "file": "crates/router/src/core/api_keys.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-1402859016926357582
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/errors.rs // Contains: 3 structs, 11 enums pub mod chat; pub mod customers_error_response; pub mod error_handlers; pub mod transformers; #[cfg(feature = "olap")] pub mod user; pub mod utils; use std::fmt::Display; pub use ::payment_methods::core::errors::VaultError; use actix_web::{body::BoxBody, ResponseError}; pub use common_utils::errors::{CustomResult, ParsingError, ValidationError}; use diesel_models::errors as storage_errors; pub use hyperswitch_domain_models::errors::api_error_response::{ ApiErrorResponse, ErrorType, NotImplementedMessage, }; pub use hyperswitch_interfaces::errors::ConnectorError; pub use redis_interface::errors::RedisError; use scheduler::errors as sch_errors; use storage_impl::errors as storage_impl_errors; #[cfg(feature = "olap")] pub use user::*; pub use self::{ customers_error_response::CustomersErrorResponse, sch_errors::*, storage_errors::*, storage_impl_errors::*, utils::{ConnectorErrorExt, StorageErrorExt}, }; use crate::services; pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>; pub type RouterResponse<T> = CustomResult<services::ApplicationResponse<T>, ApiErrorResponse>; pub type ApplicationResult<T> = error_stack::Result<T, ApplicationError>; pub type ApplicationResponse<T> = ApplicationResult<services::ApplicationResponse<T>>; pub type CustomerResponse<T> = CustomResult<services::ApplicationResponse<T>, CustomersErrorResponse>; macro_rules! impl_error_display { ($st: ident, $arg: tt) => { impl Display for $st { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( fmt, "{{ error_type: {:?}, error_description: {} }}", self, $arg ) } } }; } #[macro_export] macro_rules! capture_method_not_supported { ($connector:expr, $capture_method:expr) => { Err(errors::ConnectorError::NotSupported { message: format!("{} for selected payment method", $capture_method), connector: $connector, } .into()) }; ($connector:expr, $capture_method:expr, $payment_method_type:expr) => { Err(errors::ConnectorError::NotSupported { message: format!("{} for {}", $capture_method, $payment_method_type), connector: $connector, } .into()) }; } #[macro_export] macro_rules! unimplemented_payment_method { ($payment_method:expr, $connector:expr) => { errors::ConnectorError::NotImplemented(format!( "{} through {}", $payment_method, $connector )) }; ($payment_method:expr, $flow:expr, $connector:expr) => { errors::ConnectorError::NotImplemented(format!( "{} {} through {}", $payment_method, $flow, $connector )) }; } macro_rules! impl_error_type { ($name: ident, $arg: tt) => { #[derive(Debug)] pub struct $name; impl_error_display!($name, $arg); impl std::error::Error for $name {} }; } impl_error_type!(EncryptionError, "Encryption error"); impl From<ring::error::Unspecified> for EncryptionError { fn from(_: ring::error::Unspecified) -> Self { Self } } pub fn http_not_implemented() -> actix_web::HttpResponse<BoxBody> { ApiErrorResponse::NotImplemented { message: NotImplementedMessage::Default, } .error_response() } #[derive(Debug, thiserror::Error)] pub enum HealthCheckOutGoing { #[error("Outgoing call failed with error: {message}")] OutGoingFailed { message: String }, } #[derive(Debug, thiserror::Error)] pub enum AwsKmsError { #[error("Failed to base64 decode input data")] Base64DecodingFailed, #[error("Failed to AWS KMS decrypt input data")] DecryptionFailed, #[error("Missing plaintext AWS KMS decryption output")] MissingPlaintextDecryptionOutput, #[error("Failed to UTF-8 decode decryption output")] Utf8DecodingFailed, } #[derive(Debug, thiserror::Error, serde::Serialize)] pub enum WebhooksFlowError { #[error("Merchant webhook config not found")] MerchantConfigNotFound, #[error("Webhook details for merchant not configured")] MerchantWebhookDetailsNotFound, #[error("Merchant does not have a webhook URL configured")] MerchantWebhookUrlNotConfigured, #[error("Webhook event updation failed")] WebhookEventUpdationFailed, #[error("Outgoing webhook body signing failed")] OutgoingWebhookSigningFailed, #[error("Webhook api call to merchant failed")] CallToMerchantFailed, #[error("Webhook not received by merchant")] NotReceivedByMerchant, #[error("Dispute webhook status validation failed")] DisputeWebhookValidationFailed, #[error("Outgoing webhook body encoding failed")] OutgoingWebhookEncodingFailed, #[error("Failed to update outgoing webhook process tracker task")] OutgoingWebhookProcessTrackerTaskUpdateFailed, #[error("Failed to schedule retry attempt for outgoing webhook")] OutgoingWebhookRetrySchedulingFailed, #[error("Outgoing webhook response encoding failed")] OutgoingWebhookResponseEncodingFailed, #[error("ID generation failed")] IdGenerationFailed, } impl WebhooksFlowError { pub(crate) fn is_webhook_delivery_retryable_error(&self) -> bool { match self { Self::MerchantConfigNotFound | Self::MerchantWebhookDetailsNotFound | Self::MerchantWebhookUrlNotConfigured | Self::OutgoingWebhookResponseEncodingFailed => false, Self::WebhookEventUpdationFailed | Self::OutgoingWebhookSigningFailed | Self::CallToMerchantFailed | Self::NotReceivedByMerchant | Self::DisputeWebhookValidationFailed | Self::OutgoingWebhookEncodingFailed | Self::OutgoingWebhookProcessTrackerTaskUpdateFailed | Self::OutgoingWebhookRetrySchedulingFailed | Self::IdGenerationFailed => true, } } } #[derive(Debug, thiserror::Error)] pub enum ApplePayDecryptionError { #[error("Failed to base64 decode input data")] Base64DecodingFailed, #[error("Failed to decrypt input data")] DecryptionFailed, #[error("Certificate parsing failed")] CertificateParsingFailed, #[error("Certificate parsing failed")] MissingMerchantId, #[error("Key Deserialization failure")] KeyDeserializationFailed, #[error("Failed to Derive a shared secret key")] DerivingSharedSecretKeyFailed, } #[derive(Debug, thiserror::Error)] pub enum PazeDecryptionError { #[error("Failed to base64 decode input data")] Base64DecodingFailed, #[error("Failed to decrypt input data")] DecryptionFailed, #[error("Certificate parsing failed")] CertificateParsingFailed, } #[derive(Debug, thiserror::Error)] pub enum GooglePayDecryptionError { #[error("Invalid expiration time")] InvalidExpirationTime, #[error("Failed to base64 decode input data")] Base64DecodingFailed, #[error("Failed to decrypt input data")] DecryptionFailed, #[error("Failed to deserialize input data")] DeserializationFailed, #[error("Certificate parsing failed")] CertificateParsingFailed, #[error("Key deserialization failure")] KeyDeserializationFailed, #[error("Failed to derive a shared ephemeral key")] DerivingSharedEphemeralKeyFailed, #[error("Failed to derive a shared secret key")] DerivingSharedSecretKeyFailed, #[error("Failed to parse the tag")] ParsingTagError, #[error("HMAC verification failed")] HmacVerificationFailed, #[error("Failed to derive Elliptic Curve key")] DerivingEcKeyFailed, #[error("Failed to Derive Public key")] DerivingPublicKeyFailed, #[error("Failed to Derive Elliptic Curve group")] DerivingEcGroupFailed, #[error("Failed to allocate memory for big number")] BigNumAllocationFailed, #[error("Failed to get the ECDSA signature")] EcdsaSignatureFailed, #[error("Failed to verify the signature")] SignatureVerificationFailed, #[error("Invalid signature is provided")] InvalidSignature, #[error("Failed to parse the Signed Key")] SignedKeyParsingFailure, #[error("The Signed Key is expired")] SignedKeyExpired, #[error("Failed to parse the ECDSA signature")] EcdsaSignatureParsingFailed, #[error("Invalid intermediate signature is provided")] InvalidIntermediateSignature, #[error("Invalid protocol version")] InvalidProtocolVersion, #[error("Decrypted Token has expired")] DecryptedTokenExpired, #[error("Failed to parse the given value")] ParsingFailed, } #[cfg(feature = "detailed_errors")] pub mod error_stack_parsing { #[derive(serde::Deserialize)] pub struct NestedErrorStack<'a> { context: std::borrow::Cow<'a, str>, attachments: Vec<std::borrow::Cow<'a, str>>, sources: Vec<NestedErrorStack<'a>>, } #[derive(serde::Serialize, Debug)] struct LinearErrorStack<'a> { context: std::borrow::Cow<'a, str>, #[serde(skip_serializing_if = "Vec::is_empty")] attachments: Vec<std::borrow::Cow<'a, str>>, } #[derive(serde::Serialize, Debug)] pub struct VecLinearErrorStack<'a>(Vec<LinearErrorStack<'a>>); impl<'a> From<Vec<NestedErrorStack<'a>>> for VecLinearErrorStack<'a> { fn from(value: Vec<NestedErrorStack<'a>>) -> Self { let multi_layered_errors: Vec<_> = value .into_iter() .flat_map(|current_error| { [LinearErrorStack { context: current_error.context, attachments: current_error.attachments, }] .into_iter() .chain(Into::<VecLinearErrorStack<'a>>::into(current_error.sources).0) }) .collect(); Self(multi_layered_errors) } } } #[cfg(feature = "detailed_errors")] pub use error_stack_parsing::*; #[derive(Debug, Clone, thiserror::Error)] pub enum RoutingError { #[error("Merchant routing algorithm not found in cache")] CacheMiss, #[error("Final connector selection failed")] ConnectorSelectionFailed, #[error("[DSL] Missing required field in payment data: '{field_name}'")] DslMissingRequiredField { field_name: String }, #[error("The lock on the DSL cache is most probably poisoned")] DslCachePoisoned, #[error("Expected DSL to be saved in DB but did not find")] DslMissingInDb, #[error("Unable to parse DSL from JSON")] DslParsingError, #[error("Failed to initialize DSL backend")] DslBackendInitError, #[error("Error updating merchant with latest dsl cache contents")] DslMerchantUpdateError, #[error("Error executing the DSL")] DslExecutionError, #[error("Final connector selection failed")] DslFinalConnectorSelectionFailed, #[error("[DSL] Received incorrect selection algorithm as DSL output")] DslIncorrectSelectionAlgorithm, #[error("there was an error saving/retrieving values from the kgraph cache")] KgraphCacheFailure, #[error("failed to refresh the kgraph cache")] KgraphCacheRefreshFailed, #[error("there was an error during the kgraph analysis phase")] KgraphAnalysisError, #[error("'profile_id' was not provided")] ProfileIdMissing, #[error("the profile was not found in the database")] ProfileNotFound, #[error("failed to fetch the fallback config for the merchant")] FallbackConfigFetchFailed, #[error("Invalid connector name received: '{0}'")] InvalidConnectorName(String), #[error("The routing algorithm in merchant account had invalid structure")] InvalidRoutingAlgorithmStructure, #[error("Volume split failed")] VolumeSplitFailed, #[error("Unable to parse metadata")] MetadataParsingError, #[error("Unable to retrieve success based routing config")] SuccessBasedRoutingConfigError, #[error("Params not found in success based routing config")] SuccessBasedRoutingParamsNotFoundError, #[error("Unable to calculate success based routing config from dynamic routing service")] SuccessRateCalculationError, #[error("Success rate client from dynamic routing gRPC service not initialized")] SuccessRateClientInitializationError, #[error("Elimination client from dynamic routing gRPC service not initialized")] EliminationClientInitializationError, #[error("Unable to analyze elimination routing config from dynamic routing service")] EliminationRoutingCalculationError, #[error("Params not found in elimination based routing config")] EliminationBasedRoutingParamsNotFoundError, #[error("Unable to retrieve elimination based routing config")] EliminationRoutingConfigError, #[error( "Invalid elimination based connector label received from dynamic routing service: '{0}'" )] InvalidEliminationBasedConnectorLabel(String), #[error("Unable to convert from '{from}' to '{to}'")] GenericConversionError { from: String, to: String }, #[error("Invalid success based connector label received from dynamic routing service: '{0}'")] InvalidSuccessBasedConnectorLabel(String), #[error("unable to find '{field}'")] GenericNotFoundError { field: String }, #[error("Unable to deserialize from '{from}' to '{to}'")] DeserializationError { from: String, to: String }, #[error("Unable to retrieve contract based routing config")] ContractBasedRoutingConfigError, #[error("Params not found in contract based routing config")] ContractBasedRoutingParamsNotFoundError, #[error("Unable to calculate contract score from dynamic routing service: '{err}'")] ContractScoreCalculationError { err: String }, #[error("Unable to update contract score on dynamic routing service")] ContractScoreUpdationError, #[error("contract routing client from dynamic routing gRPC service not initialized")] ContractRoutingClientInitializationError, #[error("Invalid contract based connector label received from dynamic routing service: '{0}'")] InvalidContractBasedConnectorLabel(String), #[error("Failed to perform routing in open_router")] OpenRouterCallFailed, #[error("Error from open_router: {0}")] OpenRouterError(String), #[error("Decision engine responded with validation error: {0}")] 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)] pub enum ConditionalConfigError { #[error("failed to fetch the fallback config for the merchant")] FallbackConfigFetchFailed, #[error("The lock on the DSL cache is most probably poisoned")] DslCachePoisoned, #[error("Merchant routing algorithm not found in cache")] CacheMiss, #[error("Expected DSL to be saved in DB but did not find")] DslMissingInDb, #[error("Unable to parse DSL from JSON")] DslParsingError, #[error("Failed to initialize DSL backend")] DslBackendInitError, #[error("Error executing the DSL")] DslExecutionError, #[error("Error constructing the Input")] InputConstructionError, } #[derive(Debug, thiserror::Error)] pub enum NetworkTokenizationError { #[error("Failed to save network token in vault")] SaveNetworkTokenFailed, #[error("Failed to fetch network token details from vault")] FetchNetworkTokenFailed, #[error("Failed to encode network token vault request")] RequestEncodingFailed, #[error("Failed to deserialize network token service response")] ResponseDeserializationFailed, #[error("Failed to delete network token")] DeleteNetworkTokenFailed, #[error("Network token service not configured")] NetworkTokenizationServiceNotConfigured, #[error("Failed while calling Network Token Service API")] ApiError, #[error("Network Tokenization is not enabled for profile")] NetworkTokenizationNotEnabledForProfile, #[error("Network Tokenization is not supported for {message}")] NotSupported { message: String }, #[error("Failed to encrypt the NetworkToken payment method details")] NetworkTokenDetailsEncryptionFailed, } #[derive(Debug, thiserror::Error)] pub enum BulkNetworkTokenizationError { #[error("Failed to validate card details")] CardValidationFailed, #[error("Failed to validate payment method details")] PaymentMethodValidationFailed, #[error("Failed to assign a customer to the card")] CustomerAssignmentFailed, #[error("Failed to perform BIN lookup for the card")] BinLookupFailed, #[error("Failed to tokenize the card details with the network")] NetworkTokenizationFailed, #[error("Failed to store the card details in locker")] VaultSaveFailed, #[error("Failed to create a payment method entry")] PaymentMethodCreationFailed, #[error("Failed to update the payment method")] PaymentMethodUpdationFailed, } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] #[derive(Debug, thiserror::Error)] pub enum RevenueRecoveryError { #[error("Failed to fetch payment intent")] PaymentIntentFetchFailed, #[error("Failed to fetch payment attempt")] PaymentAttemptFetchFailed, #[error("Failed to fetch payment attempt")] PaymentAttemptIdNotFound, #[error("Failed to get revenue recovery invoice webhook")] InvoiceWebhookProcessingFailed, #[error("Failed to get revenue recovery invoice transaction")] TransactionWebhookProcessingFailed, #[error("Failed to create payment intent")] PaymentIntentCreateFailed, #[error("Source verification failed for billing connector")] WebhookAuthenticationFailed, #[error("Payment merchant connector account not found using account reference id")] PaymentMerchantConnectorAccountNotFound, #[error("Failed to fetch primitive date_time")] ScheduleTimeFetchFailed, #[error("Failed to create process tracker")] ProcessTrackerCreationError, #[error("Failed to get the response from process tracker")] ProcessTrackerResponseError, #[error("Billing connector psync call failed")] BillingConnectorPaymentsSyncFailed, #[error("Billing connector invoice sync call failed")] BillingConnectorInvoiceSyncFailed, #[error("Failed to fetch connector customer ID")] CustomerIdNotFound, #[error("Failed to get the retry count for payment intent")] 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, #[error("Failed to insert the revenue recovery payment method data in redis")] RevenueRecoveryRedisInsertFailed, }
{ "crate": "router", "file": "crates/router/src/core/errors.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 11, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_router_-1202885729092151010
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/customers.rs // Contains: 2 structs, 0 enums use common_utils::{ crypto::Encryptable, errors::ReportSwitchExt, ext_traits::AsyncExt, id_type, pii, type_name, types::{ keymanager::{Identifier, KeyManagerState, ToEncryptable}, Description, }, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::payment_methods as payment_methods_domain; use masking::{ExposeInterface, Secret, SwitchStrategy}; use payment_methods::controller::PaymentMethodsController; use router_env::{instrument, tracing}; #[cfg(feature = "v2")] use crate::core::payment_methods::cards::create_encrypted_data; #[cfg(feature = "v1")] use crate::utils::CustomerAddress; use crate::{ core::{ errors::{self, StorageErrorExt}, payment_methods::{cards, network_tokenization}, utils::{ self, customer_validation::{CUSTOMER_LIST_LOWER_LIMIT, CUSTOMER_LIST_UPPER_LIMIT}, }, }, db::StorageInterface, pii::PeekInterface, routes::{metrics, SessionState}, services, types::{ api::customers, domain::{self, types}, storage::{self, enums}, transformers::ForeignFrom, }, }; pub const REDACTED: &str = "Redacted"; #[instrument(skip(state))] pub async fn create_customer( state: SessionState, merchant_context: domain::MerchantContext, customer_data: customers::CustomerRequest, connector_customer_details: Option<Vec<payment_methods_domain::ConnectorCustomerDetails>>, ) -> errors::CustomerResponse<customers::CustomerResponse> { let db: &dyn StorageInterface = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_reference_id = customer_data.get_merchant_reference_id(); let merchant_id = merchant_context.get_merchant_account().get_id(); let merchant_reference_id_customer = MerchantReferenceIdForCustomer { merchant_reference_id: merchant_reference_id.as_ref(), merchant_id, merchant_account: merchant_context.get_merchant_account(), key_store: merchant_context.get_merchant_key_store(), key_manager_state, }; // We first need to validate whether the customer with the given customer id already exists // this may seem like a redundant db call, as the insert_customer will anyway return this error // // Consider a scenario where the address is inserted and then when inserting the customer, // it errors out, now the address that was inserted is not deleted merchant_reference_id_customer .verify_if_merchant_reference_not_present_by_optional_merchant_reference_id(db) .await?; let domain_customer = customer_data .create_domain_model_from_request( &connector_customer_details, db, &merchant_reference_id, &merchant_context, key_manager_state, &state, ) .await?; let customer = db .insert_customer( domain_customer, key_manager_state, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_duplicate_response(errors::CustomersErrorResponse::CustomerAlreadyExists)?; customer_data.generate_response(&customer) } #[async_trait::async_trait] trait CustomerCreateBridge { async fn create_domain_model_from_request<'a>( &'a self, connector_customer_details: &'a Option< Vec<payment_methods_domain::ConnectorCustomerDetails>, >, db: &'a dyn StorageInterface, merchant_reference_id: &'a Option<id_type::CustomerId>, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, state: &'a SessionState, ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse>; fn generate_response<'a>( &'a self, customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse>; } #[cfg(feature = "v1")] #[async_trait::async_trait] impl CustomerCreateBridge for customers::CustomerRequest { async fn create_domain_model_from_request<'a>( &'a self, connector_customer_details: &'a Option< Vec<payment_methods_domain::ConnectorCustomerDetails>, >, db: &'a dyn StorageInterface, merchant_reference_id: &'a Option<id_type::CustomerId>, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, state: &'a SessionState, ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> { // Setting default billing address to Db let address = self.get_address(); let merchant_id = merchant_context.get_merchant_account().get_id(); let key = merchant_context .get_merchant_key_store() .key .get_inner() .peek(); let customer_billing_address_struct = AddressStructForDbEntry { address: address.as_ref(), customer_data: self, merchant_id, customer_id: merchant_reference_id.as_ref(), storage_scheme: merchant_context.get_merchant_account().storage_scheme, key_store: merchant_context.get_merchant_key_store(), key_manager_state, state, }; let address_from_db = customer_billing_address_struct .encrypt_customer_address_and_set_to_db(db) .await?; let encrypted_data = types::crypto_operation( key_manager_state, type_name!(domain::Customer), types::CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableCustomer::to_encryptable( domain::FromRequestEncryptableCustomer { name: self.name.clone(), email: self.email.clone().map(|a| a.expose().switch_strategy()), phone: self.phone.clone(), tax_registration_id: self.tax_registration_id.clone(), }, ), ), Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), key, ) .await .and_then(|val| val.try_into_batchoperation()) .switch() .attach_printable("Failed while encrypting Customer")?; let encryptable_customer = domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::CustomersErrorResponse::InternalServerError)?; let connector_customer = connector_customer_details.as_ref().map(|details_vec| { let mut map = serde_json::Map::new(); for details in details_vec { let merchant_connector_id = details.merchant_connector_id.get_string_repr().to_string(); let connector_customer_id = details.connector_customer_id.clone(); map.insert(merchant_connector_id, connector_customer_id.into()); } pii::SecretSerdeValue::new(serde_json::Value::Object(map)) }); Ok(domain::Customer { customer_id: merchant_reference_id .to_owned() .ok_or(errors::CustomersErrorResponse::InternalServerError)?, merchant_id: merchant_id.to_owned(), name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), phone: encryptable_customer.phone, description: self.description.clone(), phone_country_code: self.phone_country_code.clone(), metadata: self.metadata.clone(), 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(), default_payment_method_id: None, updated_by: None, version: common_types::consts::API_VERSION, tax_registration_id: encryptable_customer.tax_registration_id, }) } fn generate_response<'a>( &'a self, customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse> { let address = self.get_address(); Ok(services::ApplicationResponse::Json( customers::CustomerResponse::foreign_from((customer.clone(), address)), )) } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl CustomerCreateBridge for customers::CustomerRequest { async fn create_domain_model_from_request<'a>( &'a self, connector_customer_details: &'a Option< Vec<payment_methods_domain::ConnectorCustomerDetails>, >, _db: &'a dyn StorageInterface, merchant_reference_id: &'a Option<id_type::CustomerId>, merchant_context: &'a domain::MerchantContext, key_state: &'a KeyManagerState, state: &'a SessionState, ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> { let default_customer_billing_address = self.get_default_customer_billing_address(); let encrypted_customer_billing_address = default_customer_billing_address .async_map(|billing_address| { create_encrypted_data( key_state, merchant_context.get_merchant_key_store(), billing_address, ) }) .await .transpose() .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("Unable to encrypt default customer billing address")?; let default_customer_shipping_address = self.get_default_customer_shipping_address(); let encrypted_customer_shipping_address = default_customer_shipping_address .async_map(|shipping_address| { create_encrypted_data( key_state, merchant_context.get_merchant_key_store(), shipping_address, ) }) .await .transpose() .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("Unable to encrypt default customer shipping address")?; let merchant_id = merchant_context.get_merchant_account().get_id().clone(); let key = merchant_context .get_merchant_key_store() .key .get_inner() .peek(); let encrypted_data = types::crypto_operation( key_state, type_name!(domain::Customer), types::CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableCustomer::to_encryptable( domain::FromRequestEncryptableCustomer { name: Some(self.name.clone()), email: Some(self.email.clone().expose().switch_strategy()), phone: self.phone.clone(), tax_registration_id: self.tax_registration_id.clone(), }, ), ), Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), key, ) .await .and_then(|val| val.try_into_batchoperation()) .switch() .attach_printable("Failed while encrypting Customer")?; let encryptable_customer = domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::CustomersErrorResponse::InternalServerError)?; let connector_customer = connector_customer_details.as_ref().map(|details_vec| { let map: std::collections::HashMap<_, _> = details_vec .iter() .map(|details| { ( details.merchant_connector_id.clone(), details.connector_customer_id.to_string(), ) }) .collect(); 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(), merchant_id, name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), phone: encryptable_customer.phone, description: self.description.clone(), phone_country_code: self.phone_country_code.clone(), metadata: self.metadata.clone(), connector_customer, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), default_payment_method_id: None, updated_by: None, default_billing_address: encrypted_customer_billing_address.map(Into::into), default_shipping_address: encrypted_customer_shipping_address.map(Into::into), version: common_types::consts::API_VERSION, status: common_enums::DeleteStatus::Active, tax_registration_id: encryptable_customer.tax_registration_id, }) } fn generate_response<'a>( &'a self, customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse> { Ok(services::ApplicationResponse::Json( customers::CustomerResponse::foreign_from(customer.clone()), )) } } #[cfg(feature = "v1")] struct AddressStructForDbEntry<'a> { address: Option<&'a api_models::payments::AddressDetails>, customer_data: &'a customers::CustomerRequest, merchant_id: &'a id_type::MerchantId, customer_id: Option<&'a id_type::CustomerId>, storage_scheme: common_enums::MerchantStorageScheme, key_store: &'a domain::MerchantKeyStore, key_manager_state: &'a KeyManagerState, state: &'a SessionState, } #[cfg(feature = "v1")] impl AddressStructForDbEntry<'_> { async fn encrypt_customer_address_and_set_to_db( &self, db: &dyn StorageInterface, ) -> errors::CustomResult<Option<domain::Address>, errors::CustomersErrorResponse> { let encrypted_customer_address = self .address .async_map(|addr| async { self.customer_data .get_domain_address( self.state, addr.clone(), self.merchant_id, self.customer_id .ok_or(errors::CustomersErrorResponse::InternalServerError)?, // should we raise error since in v1 appilcation is supposed to have this id or generate it at this point. self.key_store.key.get_inner().peek(), self.storage_scheme, ) .await .switch() .attach_printable("Failed while encrypting address") }) .await .transpose()?; encrypted_customer_address .async_map(|encrypt_add| async { db.insert_address_for_customers(self.key_manager_state, encrypt_add, self.key_store) .await .switch() .attach_printable("Failed while inserting new address") }) .await .transpose() } } struct MerchantReferenceIdForCustomer<'a> { merchant_reference_id: Option<&'a id_type::CustomerId>, merchant_id: &'a id_type::MerchantId, merchant_account: &'a domain::MerchantAccount, key_store: &'a domain::MerchantKeyStore, key_manager_state: &'a KeyManagerState, } #[cfg(feature = "v1")] impl<'a> MerchantReferenceIdForCustomer<'a> { async fn verify_if_merchant_reference_not_present_by_optional_merchant_reference_id( &self, db: &dyn StorageInterface, ) -> Result<Option<()>, error_stack::Report<errors::CustomersErrorResponse>> { self.merchant_reference_id .async_map(|cust| async { self.verify_if_merchant_reference_not_present_by_merchant_reference_id(cust, db) .await }) .await .transpose() } async fn verify_if_merchant_reference_not_present_by_merchant_reference_id( &self, cus: &'a id_type::CustomerId, db: &dyn StorageInterface, ) -> Result<(), error_stack::Report<errors::CustomersErrorResponse>> { match db .find_customer_by_customer_id_merchant_id( self.key_manager_state, cus, self.merchant_id, self.key_store, self.merchant_account.storage_scheme, ) .await { Err(err) => { if !err.current_context().is_db_not_found() { Err(err).switch() } else { Ok(()) } } Ok(_) => Err(report!( errors::CustomersErrorResponse::CustomerAlreadyExists )), } } } #[cfg(feature = "v2")] impl<'a> MerchantReferenceIdForCustomer<'a> { async fn verify_if_merchant_reference_not_present_by_optional_merchant_reference_id( &self, db: &dyn StorageInterface, ) -> Result<Option<()>, error_stack::Report<errors::CustomersErrorResponse>> { self.merchant_reference_id .async_map(|merchant_ref| async { self.verify_if_merchant_reference_not_present_by_merchant_reference( merchant_ref, db, ) .await }) .await .transpose() } async fn verify_if_merchant_reference_not_present_by_merchant_reference( &self, merchant_ref: &'a id_type::CustomerId, db: &dyn StorageInterface, ) -> Result<(), error_stack::Report<errors::CustomersErrorResponse>> { match db .find_customer_by_merchant_reference_id_merchant_id( self.key_manager_state, merchant_ref, self.merchant_id, self.key_store, self.merchant_account.storage_scheme, ) .await { Err(err) => { if !err.current_context().is_db_not_found() { Err(err).switch() } else { Ok(()) } } Ok(_) => Err(report!( errors::CustomersErrorResponse::CustomerAlreadyExists )), } } } #[cfg(feature = "v1")] #[instrument(skip(state))] pub async fn retrieve_customer( state: SessionState, merchant_context: domain::MerchantContext, _profile_id: Option<id_type::ProfileId>, customer_id: id_type::CustomerId, ) -> errors::CustomerResponse<customers::CustomerResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let response = db .find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_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, ) .await .switch()? .ok_or(errors::CustomersErrorResponse::CustomerNotFound)?; let address = match &response.address_id { Some(address_id) => Some(api_models::payments::AddressDetails::from( db.find_address_by_address_id( key_manager_state, address_id, merchant_context.get_merchant_key_store(), ) .await .switch()?, )), None => None, }; Ok(services::ApplicationResponse::Json( customers::CustomerResponse::foreign_from((response, address)), )) } #[cfg(feature = "v2")] #[instrument(skip(state))] pub async fn retrieve_customer( state: SessionState, merchant_context: domain::MerchantContext, id: id_type::GlobalCustomerId, ) -> errors::CustomerResponse<customers::CustomerResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let response = db .find_customer_by_global_id( key_manager_state, &id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .switch()?; Ok(services::ApplicationResponse::Json( customers::CustomerResponse::foreign_from(response), )) } #[instrument(skip(state))] pub async fn list_customers( state: SessionState, merchant_id: id_type::MerchantId, _profile_id_list: Option<Vec<id_type::ProfileId>>, key_store: domain::MerchantKeyStore, request: customers::CustomerListRequest, ) -> errors::CustomerResponse<Vec<customers::CustomerResponse>> { let db = state.store.as_ref(); let customer_list_constraints = crate::db::customers::CustomerListConstraints { limit: request .limit .unwrap_or(crate::consts::DEFAULT_LIST_API_LIMIT), offset: request.offset, customer_id: request.customer_id, time_range: None, }; let domain_customers = db .list_customers_by_merchant_id( &(&state).into(), &merchant_id, &key_store, customer_list_constraints, ) .await .switch()?; #[cfg(feature = "v1")] let customers = domain_customers .into_iter() .map(|domain_customer| customers::CustomerResponse::foreign_from((domain_customer, None))) .collect(); #[cfg(feature = "v2")] let customers = domain_customers .into_iter() .map(customers::CustomerResponse::foreign_from) .collect(); Ok(services::ApplicationResponse::Json(customers)) } #[instrument(skip(state))] pub async fn list_customers_with_count( state: SessionState, merchant_id: id_type::MerchantId, _profile_id_list: Option<Vec<id_type::ProfileId>>, key_store: domain::MerchantKeyStore, request: customers::CustomerListRequestWithConstraints, ) -> errors::CustomerResponse<customers::CustomerListResponse> { let db = state.store.as_ref(); let limit = utils::customer_validation::validate_customer_list_limit(request.limit) .change_context(errors::CustomersErrorResponse::InvalidRequestData { message: format!( "limit should be between {CUSTOMER_LIST_LOWER_LIMIT} and {CUSTOMER_LIST_UPPER_LIMIT}" ), })?; let customer_list_constraints = crate::db::customers::CustomerListConstraints { limit: request.limit.unwrap_or(limit), offset: request.offset, customer_id: request.customer_id, time_range: request.time_range, }; let domain_customers = db .list_customers_by_merchant_id_with_count( &(&state).into(), &merchant_id, &key_store, customer_list_constraints, ) .await .switch()?; #[cfg(feature = "v1")] let customers: Vec<customers::CustomerResponse> = domain_customers .0 .into_iter() .map(|domain_customer| customers::CustomerResponse::foreign_from((domain_customer, None))) .collect(); #[cfg(feature = "v2")] let customers: Vec<customers::CustomerResponse> = domain_customers .0 .into_iter() .map(customers::CustomerResponse::foreign_from) .collect(); Ok(services::ApplicationResponse::Json( customers::CustomerListResponse { data: customers.into_iter().map(|c| c.0).collect(), total_count: domain_customers.1, }, )) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn delete_customer( state: SessionState, merchant_context: domain::MerchantContext, id: id_type::GlobalCustomerId, ) -> errors::CustomerResponse<customers::CustomerDeleteResponse> { let db = &*state.store; let key_manager_state = &(&state).into(); id.redact_customer_details_and_generate_response( db, &merchant_context, key_manager_state, &state, ) .await } #[cfg(feature = "v2")] #[async_trait::async_trait] impl CustomerDeleteBridge for id_type::GlobalCustomerId { async fn redact_customer_details_and_generate_response<'a>( &'a self, db: &'a dyn StorageInterface, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, state: &'a SessionState, ) -> errors::CustomerResponse<customers::CustomerDeleteResponse> { let customer_orig = db .find_customer_by_global_id( key_manager_state, self, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .switch()?; let merchant_reference_id = customer_orig.merchant_reference_id.clone(); let customer_mandates = db.find_mandate_by_global_customer_id(self).await.switch()?; for mandate in customer_mandates.into_iter() { if mandate.mandate_status == enums::MandateStatus::Active { Err(errors::CustomersErrorResponse::MandateActive)? } } match db .find_payment_method_list_by_global_customer_id( key_manager_state, merchant_context.get_merchant_key_store(), self, None, ) .await { // check this in review Ok(customer_payment_methods) => { for pm in customer_payment_methods.into_iter() { if pm.get_payment_method_type() == Some(enums::PaymentMethod::Card) { cards::delete_card_by_locker_id( state, self, merchant_context.get_merchant_account().get_id(), ) .await .switch()?; } // No solution as of now, need to discuss this further with payment_method_v2 // db.delete_payment_method( // key_manager_state, // key_store, // pm, // ) // .await // .switch()?; } } Err(error) => { if error.current_context().is_db_not_found() { Ok(()) } else { Err(error) .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable( "failed find_payment_method_by_customer_id_merchant_id_list", ) }? } }; let key = merchant_context .get_merchant_key_store() .key .get_inner() .peek(); let identifier = Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ); let redacted_encrypted_value: Encryptable<Secret<_>> = types::crypto_operation( key_manager_state, type_name!(storage::Address), types::CryptoOperation::Encrypt(REDACTED.to_string().into()), identifier.clone(), key, ) .await .and_then(|val| val.try_into_operation()) .switch()?; let redacted_encrypted_email = Encryptable::new( redacted_encrypted_value .clone() .into_inner() .switch_strategy(), redacted_encrypted_value.clone().into_encrypted(), ); let updated_customer = storage::CustomerUpdate::Update(Box::new(storage::CustomerGeneralUpdate { name: Some(redacted_encrypted_value.clone()), email: Box::new(Some(redacted_encrypted_email)), phone: Box::new(Some(redacted_encrypted_value.clone())), description: Some(Description::from_str_unchecked(REDACTED)), phone_country_code: Some(REDACTED.to_string()), metadata: None, connector_customer: Box::new(None), default_billing_address: None, default_shipping_address: None, default_payment_method_id: None, status: Some(common_enums::DeleteStatus::Redacted), tax_registration_id: Some(redacted_encrypted_value), })); db.update_customer_by_global_id( key_manager_state, self, customer_orig, updated_customer, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .switch()?; let response = customers::CustomerDeleteResponse { id: self.clone(), merchant_reference_id, customer_deleted: true, address_deleted: true, payment_methods_deleted: true, }; metrics::CUSTOMER_REDACTED.add(1, &[]); Ok(services::ApplicationResponse::Json(response)) } } #[async_trait::async_trait] trait CustomerDeleteBridge { async fn redact_customer_details_and_generate_response<'a>( &'a self, db: &'a dyn StorageInterface, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, state: &'a SessionState, ) -> errors::CustomerResponse<customers::CustomerDeleteResponse>; } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn delete_customer( state: SessionState, merchant_context: domain::MerchantContext, customer_id: id_type::CustomerId, ) -> errors::CustomerResponse<customers::CustomerDeleteResponse> { let db = &*state.store; let key_manager_state = &(&state).into(); customer_id .redact_customer_details_and_generate_response( db, &merchant_context, key_manager_state, &state, ) .await } #[cfg(feature = "v1")] #[async_trait::async_trait] impl CustomerDeleteBridge for id_type::CustomerId { async fn redact_customer_details_and_generate_response<'a>( &'a self, db: &'a dyn StorageInterface, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, state: &'a SessionState, ) -> errors::CustomerResponse<customers::CustomerDeleteResponse> { let customer_orig = db .find_customer_by_customer_id_merchant_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, ) .await .switch()?; let customer_mandates = db .find_mandate_by_merchant_id_customer_id( merchant_context.get_merchant_account().get_id(), self, ) .await .switch()?; for mandate in customer_mandates.into_iter() { if mandate.mandate_status == enums::MandateStatus::Active { Err(errors::CustomersErrorResponse::MandateActive)? } } match db .find_payment_method_by_customer_id_merchant_id_list( key_manager_state, merchant_context.get_merchant_key_store(), self, merchant_context.get_merchant_account().get_id(), None, ) .await { // check this in review Ok(customer_payment_methods) => { for pm in customer_payment_methods.into_iter() { if pm.get_payment_method_type() == Some(enums::PaymentMethod::Card) { cards::PmCards { state, merchant_context, } .delete_card_from_locker( self, merchant_context.get_merchant_account().get_id(), pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), ) .await .switch()?; if let Some(network_token_ref_id) = pm.network_token_requestor_reference_id { network_tokenization::delete_network_token_from_locker_and_token_service( state, self, merchant_context.get_merchant_account().get_id(), pm.payment_method_id.clone(), pm.network_token_locker_id, network_token_ref_id, merchant_context, ) .await .switch()?; } } db.delete_payment_method_by_merchant_id_payment_method_id( key_manager_state, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().get_id(), &pm.payment_method_id, ) .await .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable( "failed to delete payment method while redacting customer details", )?; } } Err(error) => { if error.current_context().is_db_not_found() { Ok(()) } else { Err(error) .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable( "failed find_payment_method_by_customer_id_merchant_id_list", ) }? } }; let key = merchant_context .get_merchant_key_store() .key .get_inner() .peek(); let identifier = Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ); let redacted_encrypted_value: Encryptable<Secret<_>> = types::crypto_operation( key_manager_state, type_name!(storage::Address), types::CryptoOperation::Encrypt(REDACTED.to_string().into()), identifier.clone(), key, ) .await .and_then(|val| val.try_into_operation()) .switch()?; let redacted_encrypted_email = Encryptable::new( redacted_encrypted_value .clone() .into_inner() .switch_strategy(), redacted_encrypted_value.clone().into_encrypted(), ); let update_address = storage::AddressUpdate::Update { city: Some(REDACTED.to_string()), country: None, line1: Some(redacted_encrypted_value.clone()), line2: Some(redacted_encrypted_value.clone()), line3: Some(redacted_encrypted_value.clone()), state: Some(redacted_encrypted_value.clone()), zip: Some(redacted_encrypted_value.clone()), first_name: Some(redacted_encrypted_value.clone()), last_name: Some(redacted_encrypted_value.clone()), phone_number: Some(redacted_encrypted_value.clone()), country_code: Some(REDACTED.to_string()), updated_by: merchant_context .get_merchant_account() .storage_scheme .to_string(), email: Some(redacted_encrypted_email), origin_zip: Some(redacted_encrypted_value.clone()), }; match db .update_address_by_merchant_id_customer_id( key_manager_state, self, merchant_context.get_merchant_account().get_id(), update_address, merchant_context.get_merchant_key_store(), ) .await { Ok(_) => Ok(()), Err(error) => { if error.current_context().is_db_not_found() { Ok(()) } else { Err(error) .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("failed update_address_by_merchant_id_customer_id") } } }?; let updated_customer = storage::CustomerUpdate::Update { name: Some(redacted_encrypted_value.clone()), email: Some( types::crypto_operation( key_manager_state, type_name!(storage::Customer), types::CryptoOperation::Encrypt(REDACTED.to_string().into()), identifier, key, ) .await .and_then(|val| val.try_into_operation()) .switch()?, ), phone: Box::new(Some(redacted_encrypted_value.clone())), description: Some(Description::from_str_unchecked(REDACTED)), phone_country_code: Some(REDACTED.to_string()), metadata: Box::new(None), connector_customer: Box::new(None), address_id: None, tax_registration_id: Some(redacted_encrypted_value.clone()), }; db.update_customer_by_customer_id_merchant_id( key_manager_state, self.clone(), merchant_context.get_merchant_account().get_id().to_owned(), customer_orig, updated_customer, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .switch()?; let response = customers::CustomerDeleteResponse { customer_id: self.clone(), customer_deleted: true, address_deleted: true, payment_methods_deleted: true, }; metrics::CUSTOMER_REDACTED.add(1, &[]); Ok(services::ApplicationResponse::Json(response)) } } #[instrument(skip(state))] pub async fn update_customer( state: SessionState, merchant_context: domain::MerchantContext, update_customer: customers::CustomerUpdateRequestInternal, ) -> errors::CustomerResponse<customers::CustomerResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); //Add this in update call if customer can be updated anywhere else #[cfg(feature = "v1")] let verify_id_for_update_customer = VerifyIdForUpdateCustomer { merchant_reference_id: &update_customer.customer_id, merchant_account: merchant_context.get_merchant_account(), key_store: merchant_context.get_merchant_key_store(), key_manager_state, }; #[cfg(feature = "v2")] let verify_id_for_update_customer = VerifyIdForUpdateCustomer { id: &update_customer.id, merchant_account: merchant_context.get_merchant_account(), key_store: merchant_context.get_merchant_key_store(), key_manager_state, }; let customer = verify_id_for_update_customer .verify_id_and_get_customer_object(db) .await?; let updated_customer = update_customer .request .create_domain_model_from_request( &None, db, &merchant_context, key_manager_state, &state, &customer, ) .await?; update_customer.request.generate_response(&updated_customer) } #[async_trait::async_trait] trait CustomerUpdateBridge { async fn create_domain_model_from_request<'a>( &'a self, connector_customer_details: &'a Option< Vec<payment_methods_domain::ConnectorCustomerDetails>, >, db: &'a dyn StorageInterface, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, state: &'a SessionState, domain_customer: &'a domain::Customer, ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse>; fn generate_response<'a>( &'a self, customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse>; } #[cfg(feature = "v1")] struct AddressStructForDbUpdate<'a> { update_customer: &'a customers::CustomerUpdateRequest, merchant_account: &'a domain::MerchantAccount, key_store: &'a domain::MerchantKeyStore, key_manager_state: &'a KeyManagerState, state: &'a SessionState, domain_customer: &'a domain::Customer, } #[cfg(feature = "v1")] impl AddressStructForDbUpdate<'_> { async fn update_address_if_sent( &self, db: &dyn StorageInterface, ) -> errors::CustomResult<Option<domain::Address>, errors::CustomersErrorResponse> { let address = if let Some(addr) = &self.update_customer.address { match self.domain_customer.address_id.clone() { Some(address_id) => { let customer_address: api_models::payments::AddressDetails = addr.clone(); let update_address = self .update_customer .get_address_update( self.state, customer_address, self.key_store.key.get_inner().peek(), self.merchant_account.storage_scheme, self.merchant_account.get_id().clone(), ) .await .switch() .attach_printable("Failed while encrypting Address while Update")?; Some( db.update_address( self.key_manager_state, address_id, update_address, self.key_store, ) .await .switch() .attach_printable(format!( "Failed while updating address: merchant_id: {:?}, customer_id: {:?}", self.merchant_account.get_id(), self.domain_customer.customer_id ))?, ) } None => { let customer_address: api_models::payments::AddressDetails = addr.clone(); let address = self .update_customer .get_domain_address( self.state, customer_address, self.merchant_account.get_id(), &self.domain_customer.customer_id, self.key_store.key.get_inner().peek(), self.merchant_account.storage_scheme, ) .await .switch() .attach_printable("Failed while encrypting address")?; Some( db.insert_address_for_customers( self.key_manager_state, address, self.key_store, ) .await .switch() .attach_printable("Failed while inserting new address")?, ) } } } else { match &self.domain_customer.address_id { Some(address_id) => Some( db.find_address_by_address_id( self.key_manager_state, address_id, self.key_store, ) .await .switch()?, ), None => None, } }; Ok(address) } } #[cfg(feature = "v1")] #[derive(Debug)] struct VerifyIdForUpdateCustomer<'a> { merchant_reference_id: &'a id_type::CustomerId, merchant_account: &'a domain::MerchantAccount, key_store: &'a domain::MerchantKeyStore, key_manager_state: &'a KeyManagerState, } #[cfg(feature = "v2")] #[derive(Debug)] struct VerifyIdForUpdateCustomer<'a> { id: &'a id_type::GlobalCustomerId, merchant_account: &'a domain::MerchantAccount, key_store: &'a domain::MerchantKeyStore, key_manager_state: &'a KeyManagerState, } #[cfg(feature = "v1")] impl VerifyIdForUpdateCustomer<'_> { async fn verify_id_and_get_customer_object( &self, db: &dyn StorageInterface, ) -> Result<domain::Customer, error_stack::Report<errors::CustomersErrorResponse>> { let customer = db .find_customer_by_customer_id_merchant_id( self.key_manager_state, self.merchant_reference_id, self.merchant_account.get_id(), self.key_store, self.merchant_account.storage_scheme, ) .await .switch()?; Ok(customer) } } #[cfg(feature = "v2")] impl VerifyIdForUpdateCustomer<'_> { async fn verify_id_and_get_customer_object( &self, db: &dyn StorageInterface, ) -> Result<domain::Customer, error_stack::Report<errors::CustomersErrorResponse>> { let customer = db .find_customer_by_global_id( self.key_manager_state, self.id, self.key_store, self.merchant_account.storage_scheme, ) .await .switch()?; Ok(customer) } } #[cfg(feature = "v1")] #[async_trait::async_trait] impl CustomerUpdateBridge for customers::CustomerUpdateRequest { async fn create_domain_model_from_request<'a>( &'a self, _connector_customer_details: &'a Option< Vec<payment_methods_domain::ConnectorCustomerDetails>, >, db: &'a dyn StorageInterface, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, state: &'a SessionState, domain_customer: &'a domain::Customer, ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> { let update_address_for_update_customer = AddressStructForDbUpdate { update_customer: self, merchant_account: merchant_context.get_merchant_account(), key_store: merchant_context.get_merchant_key_store(), key_manager_state, state, domain_customer, }; let address = update_address_for_update_customer .update_address_if_sent(db) .await?; let key = merchant_context .get_merchant_key_store() .key .get_inner() .peek(); let encrypted_data = types::crypto_operation( key_manager_state, type_name!(domain::Customer), types::CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableCustomer::to_encryptable( domain::FromRequestEncryptableCustomer { name: self.name.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), phone: self.phone.clone(), tax_registration_id: self.tax_registration_id.clone(), }, ), ), Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), key, ) .await .and_then(|val| val.try_into_batchoperation()) .switch()?; let encryptable_customer = domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::CustomersErrorResponse::InternalServerError)?; let response = db .update_customer_by_customer_id_merchant_id( key_manager_state, domain_customer.customer_id.to_owned(), merchant_context.get_merchant_account().get_id().to_owned(), domain_customer.to_owned(), storage::CustomerUpdate::Update { name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), phone: Box::new(encryptable_customer.phone), tax_registration_id: encryptable_customer.tax_registration_id, phone_country_code: self.phone_country_code.clone(), metadata: Box::new(self.metadata.clone()), description: self.description.clone(), connector_customer: Box::new(None), address_id: address.clone().map(|addr| addr.address_id), }, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .switch()?; Ok(response) } fn generate_response<'a>( &'a self, customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse> { let address = self.get_address(); Ok(services::ApplicationResponse::Json( customers::CustomerResponse::foreign_from((customer.clone(), address)), )) } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl CustomerUpdateBridge for customers::CustomerUpdateRequest { async fn create_domain_model_from_request<'a>( &'a self, connector_customer_details: &'a Option< Vec<payment_methods_domain::ConnectorCustomerDetails>, >, db: &'a dyn StorageInterface, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, state: &'a SessionState, domain_customer: &'a domain::Customer, ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> { let default_billing_address = self.get_default_customer_billing_address(); let encrypted_customer_billing_address = default_billing_address .async_map(|billing_address| { create_encrypted_data( key_manager_state, merchant_context.get_merchant_key_store(), billing_address, ) }) .await .transpose() .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("Unable to encrypt default customer billing address")?; let default_shipping_address = self.get_default_customer_shipping_address(); let encrypted_customer_shipping_address = default_shipping_address .async_map(|shipping_address| { create_encrypted_data( key_manager_state, merchant_context.get_merchant_key_store(), shipping_address, ) }) .await .transpose() .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("Unable to encrypt default customer shipping address")?; let key = merchant_context .get_merchant_key_store() .key .get_inner() .peek(); let encrypted_data = types::crypto_operation( key_manager_state, type_name!(domain::Customer), types::CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableCustomer::to_encryptable( domain::FromRequestEncryptableCustomer { name: self.name.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), phone: self.phone.clone(), tax_registration_id: self.tax_registration_id.clone(), }, ), ), Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), key, ) .await .and_then(|val| val.try_into_batchoperation()) .switch()?; let encryptable_customer = domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::CustomersErrorResponse::InternalServerError)?; let response = db .update_customer_by_global_id( key_manager_state, &domain_customer.id, domain_customer.to_owned(), storage::CustomerUpdate::Update(Box::new(storage::CustomerGeneralUpdate { name: encryptable_customer.name, email: Box::new(encryptable_customer.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable })), phone: Box::new(encryptable_customer.phone), tax_registration_id: encryptable_customer.tax_registration_id, phone_country_code: self.phone_country_code.clone(), metadata: self.metadata.clone(), description: self.description.clone(), connector_customer: Box::new(None), default_billing_address: encrypted_customer_billing_address.map(Into::into), default_shipping_address: encrypted_customer_shipping_address.map(Into::into), default_payment_method_id: Some(self.default_payment_method_id.clone()), status: None, })), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .switch()?; Ok(response) } fn generate_response<'a>( &'a self, customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse> { Ok(services::ApplicationResponse::Json( customers::CustomerResponse::foreign_from(customer.clone()), )) } } pub async fn migrate_customers( state: SessionState, customers_migration: Vec<payment_methods_domain::PaymentMethodCustomerMigrate>, merchant_context: domain::MerchantContext, ) -> errors::CustomerResponse<()> { 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 => (), _ => return Err(e), }, } } Ok(services::ApplicationResponse::Json(())) }
{ "crate": "router", "file": "crates/router/src/core/customers.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_router_3301439133832433075
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/debit_routing.rs // Contains: 1 structs, 0 enums use std::{collections::HashSet, fmt::Debug}; use api_models::{enums as api_enums, open_router}; use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::ValueExt, id_type, types::keymanager::KeyManagerState, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; use super::{ payments::{OperationSessionGetters, OperationSessionSetters}, routing::TransactionData, }; use crate::{ core::{ errors, payments::{operations::BoxedOperation, routing}, }, logger, routes::SessionState, settings, types::{ api::{self, ConnectorCallType}, domain, }, utils::id_type::MerchantConnectorAccountId, }; pub struct DebitRoutingResult { pub debit_routing_connector_call_type: ConnectorCallType, pub debit_routing_output: open_router::DebitRoutingOutput, } pub async fn perform_debit_routing<F, Req, D>( operation: &BoxedOperation<'_, F, Req, D>, state: &SessionState, business_profile: &domain::Profile, payment_data: &mut D, connector: Option<ConnectorCallType>, ) -> ( Option<ConnectorCallType>, Option<open_router::DebitRoutingOutput>, ) where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let mut debit_routing_output = None; if should_execute_debit_routing(state, business_profile, operation, payment_data).await { let debit_routing_config = state.conf.debit_routing_config.clone(); let debit_routing_supported_connectors = debit_routing_config.supported_connectors.clone(); // 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"); handle_pre_determined_connector( state, debit_routing_supported_connectors, &connector_data, payment_data, acquirer_country, ) .await } ConnectorCallType::Retryable(connector_data) => { logger::info!("Performing debit routing for Retryable connector"); handle_retryable_connector( state, debit_routing_supported_connectors, connector_data, payment_data, acquirer_country, ) .await } ConnectorCallType::SessionMultiple(_) => { logger::info!( "SessionMultiple connector type is not supported for debit routing" ); None } #[cfg(feature = "v2")] ConnectorCallType::Skip => { logger::info!("Skip connector type is not supported for debit routing"); None } }; } } if let Some(debit_routing_output) = debit_routing_output { ( Some(debit_routing_output.debit_routing_connector_call_type), Some(debit_routing_output.debit_routing_output), ) } else { // If debit_routing_output is None, return the static routing output (connector) logger::info!("Debit routing is not performed, returning static routing output"); (connector, None) } } async fn should_execute_debit_routing<F, Req, D>( state: &SessionState, business_profile: &domain::Profile, operation: &BoxedOperation<'_, F, Req, D>, payment_data: &D, ) -> bool where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { if business_profile.is_debit_routing_enabled && state.conf.open_router.dynamic_routing_enabled { logger::info!("Debit routing is enabled for the profile"); let debit_routing_config = &state.conf.debit_routing_config; if should_perform_debit_routing_for_the_flow(operation, payment_data, debit_routing_config) { let is_debit_routable_connector_present = check_for_debit_routing_connector_in_profile( state, business_profile.get_id(), payment_data, ) .await; if is_debit_routable_connector_present { logger::debug!("Debit routable connector is configured for the profile"); return true; } } } false } pub fn should_perform_debit_routing_for_the_flow<Op: Debug, F: Clone, D>( operation: &Op, payment_data: &D, debit_routing_config: &settings::DebitRoutingConfig, ) -> bool where D: OperationSessionGetters<F> + Send + Sync + Clone, { match format!("{operation:?}").as_str() { "PaymentConfirm" => { logger::info!("Checking if debit routing is required"); request_validation(payment_data, debit_routing_config) } _ => false, } } fn request_validation<F: Clone, D>( payment_data: &D, debit_routing_config: &settings::DebitRoutingConfig, ) -> bool where D: OperationSessionGetters<F> + Send + Sync + Clone, { let payment_intent = payment_data.get_payment_intent(); let payment_attempt = payment_data.get_payment_attempt(); let is_currency_supported = is_currency_supported(payment_intent, debit_routing_config); let is_valid_payment_method = validate_payment_method_for_debit_routing(payment_data); payment_intent.setup_future_usage != Some(enums::FutureUsage::OffSession) && payment_intent.amount.is_greater_than(0) && is_currency_supported && payment_attempt.authentication_type == Some(enums::AuthenticationType::NoThreeDs) && is_valid_payment_method } fn is_currency_supported( payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, debit_routing_config: &settings::DebitRoutingConfig, ) -> bool { payment_intent .currency .map(|currency| { debit_routing_config .supported_currencies .contains(&currency) }) .unwrap_or(false) } fn validate_payment_method_for_debit_routing<F: Clone, D>(payment_data: &D) -> bool where D: OperationSessionGetters<F> + Send + Sync + Clone, { let payment_attempt = payment_data.get_payment_attempt(); match payment_attempt.payment_method { Some(enums::PaymentMethod::Card) => { payment_attempt.payment_method_type == Some(enums::PaymentMethodType::Debit) } Some(enums::PaymentMethod::Wallet) => { payment_attempt.payment_method_type == Some(enums::PaymentMethodType::ApplePay) && payment_data .get_payment_method_data() .and_then(|data| data.get_wallet_data()) .and_then(|data| data.get_apple_pay_wallet_data()) .and_then(|data| data.get_payment_method_type()) == Some(enums::PaymentMethodType::Debit) && matches!( payment_data.get_payment_method_token().cloned(), Some( hyperswitch_domain_models::router_data::PaymentMethodToken::ApplePayDecrypt( _ ) ) ) } _ => false, } } pub async fn check_for_debit_routing_connector_in_profile< F: Clone, D: OperationSessionGetters<F>, >( state: &SessionState, business_profile_id: &id_type::ProfileId, payment_data: &D, ) -> bool { logger::debug!("Checking for debit routing connector in profile"); let debit_routing_supported_connectors = state.conf.debit_routing_config.supported_connectors.clone(); let transaction_data = super::routing::PaymentsDslInput::new( 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(), ); let fallback_config_optional = super::routing::helpers::get_merchant_default_config( &*state.clone().store, business_profile_id.get_string_repr(), &enums::TransactionType::from(&TransactionData::Payment(transaction_data)), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .map_err(|error| { logger::warn!(?error, "Failed to fetch default connector for a profile"); }) .ok(); let is_debit_routable_connector_present = fallback_config_optional .map(|fallback_config| { fallback_config.iter().any(|fallback_config_connector| { debit_routing_supported_connectors.contains(&api_enums::Connector::from( fallback_config_connector.connector, )) }) }) .unwrap_or(false); is_debit_routable_connector_present } async fn handle_pre_determined_connector<F, D>( state: &SessionState, debit_routing_supported_connectors: HashSet<api_enums::Connector>, connector_data: &api::ConnectorRoutingData, payment_data: &mut D, acquirer_country: enums::CountryAlpha2, ) -> Option<DebitRoutingResult> 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"); let debit_routing_output = get_debit_routing_output::<F, D>(state, payment_data, acquirer_country).await?; logger::debug!( "Sorted co-badged networks info: {:?}", debit_routing_output.co_badged_card_networks_info ); 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_info .clone() .get_card_networks(), ) .await .map_err(|error| { logger::error!( "Failed to build connector routing data for debit routing {:?}", error ) }) .ok()?; if !connector_routing_data.is_empty() { return Some(DebitRoutingResult { debit_routing_connector_call_type: ConnectorCallType::Retryable( connector_routing_data, ), debit_routing_output, }); } } None } pub async fn get_debit_routing_output< F: Clone + Send, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, >( state: &SessionState, payment_data: &mut D, acquirer_country: enums::CountryAlpha2, ) -> Option<open_router::DebitRoutingOutput> { logger::debug!("Fetching sorted card networks"); let card_info = extract_card_info(payment_data); let saved_co_badged_card_data = card_info.co_badged_card_data; let saved_card_type = card_info.card_type; let card_isin = card_info.card_isin; 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)| { 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 = open_router::CoBadgedCardRequest { merchant_category_code: enums::DecisionEngineMerchantCategoryCode::Mcc0001, acquirer_country, co_badged_card_data, }; routing::perform_open_routing_for_debit_routing( state, co_badged_card_request, card_isin, payment_data, ) .await .map_err(|error| { logger::warn!(?error, "Debit routing call to open router failed"); }) .ok() } } } #[derive(Debug, Clone)] struct ExtractedCardInfo { co_badged_card_data: Option<api_models::payment_methods::CoBadgedCardData>, card_type: Option<String>, card_isin: Option<Secret<String>>, } impl ExtractedCardInfo { fn new( co_badged_card_data: Option<api_models::payment_methods::CoBadgedCardData>, card_type: Option<String>, card_isin: Option<Secret<String>>, ) -> Self { Self { co_badged_card_data, card_type, card_isin, } } fn empty() -> Self { Self::new(None, None, None) } } fn extract_card_info<F, D>(payment_data: &D) -> ExtractedCardInfo where D: OperationSessionGetters<F>, { extract_from_saved_payment_method(payment_data) .unwrap_or_else(|| extract_from_payment_method_data(payment_data)) } fn extract_from_saved_payment_method<F, D>(payment_data: &D) -> Option<ExtractedCardInfo> where D: OperationSessionGetters<F>, { let payment_methods_data = payment_data .get_payment_method_info()? .get_payment_methods_data()?; if let hyperswitch_domain_models::payment_method_data::PaymentMethodsData::Card(card) = payment_methods_data { return Some(extract_card_info_from_saved_card(&card)); } None } fn extract_card_info_from_saved_card( card: &hyperswitch_domain_models::payment_method_data::CardDetailsPaymentMethod, ) -> ExtractedCardInfo { match (&card.co_badged_card_data, &card.card_isin) { (Some(co_badged), _) => { logger::debug!("Co-badged card data found in saved payment method"); ExtractedCardInfo::new(Some(co_badged.clone()), card.card_type.clone(), None) } (None, Some(card_isin)) => { logger::debug!("No co-badged data; using saved card ISIN"); ExtractedCardInfo::new(None, None, Some(Secret::new(card_isin.clone()))) } _ => ExtractedCardInfo::empty(), } } fn extract_from_payment_method_data<F, D>(payment_data: &D) -> ExtractedCardInfo where D: OperationSessionGetters<F>, { match payment_data.get_payment_method_data() { Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::Card(card)) => { logger::debug!("Using card data from payment request"); ExtractedCardInfo::new( None, None, Some(Secret::new(card.card_number.get_extended_card_bin())), ) } Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::Wallet( wallet_data, )) => extract_from_wallet_data(wallet_data, payment_data), _ => ExtractedCardInfo::empty(), } } fn extract_from_wallet_data<F, D>( wallet_data: &hyperswitch_domain_models::payment_method_data::WalletData, payment_data: &D, ) -> ExtractedCardInfo where D: OperationSessionGetters<F>, { match wallet_data { hyperswitch_domain_models::payment_method_data::WalletData::ApplePay(_) => { logger::debug!("Using Apple Pay data from payment request"); let apple_pay_isin = extract_apple_pay_isin(payment_data); ExtractedCardInfo::new(None, None, apple_pay_isin) } _ => ExtractedCardInfo::empty(), } } fn extract_apple_pay_isin<F, D>(payment_data: &D) -> Option<Secret<String>> where D: OperationSessionGetters<F>, { payment_data.get_payment_method_token().and_then(|token| { if let hyperswitch_domain_models::router_data::PaymentMethodToken::ApplePayDecrypt( apple_pay_decrypt_data, ) = token { logger::debug!("Using Apple Pay decrypt data from payment method token"); Some(Secret::new( apple_pay_decrypt_data .application_primary_account_number .peek() .chars() .take(8) .collect::<String>(), )) } else { None } }) } async fn handle_retryable_connector<F, D>( state: &SessionState, debit_routing_supported_connectors: HashSet<api_enums::Connector>, connector_data_list: Vec<api::ConnectorRoutingData>, payment_data: &mut D, acquirer_country: enums::CountryAlpha2, ) -> Option<DebitRoutingResult> 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 .contains(&connector_data.connector_data.connector_name) }); if is_any_debit_routing_connector_supported { let debit_routing_output = get_debit_routing_output::<F, D>(state, payment_data, acquirer_country).await?; 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, connector_data_list.clone(), debit_routing_output .co_badged_card_networks_info .clone() .get_card_networks(), ) .await .map_err(|error| { logger::error!( "Failed to build connector routing data for debit routing {:?}", error ) }) .ok()?; if !connector_routing_data.is_empty() { return Some(DebitRoutingResult { debit_routing_connector_call_type: ConnectorCallType::Retryable( 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, 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_routing_data: &api::ConnectorRoutingData, 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_routing_data.connector_data.connector_name.clone()); fee_sorted_debit_networks .iter() .filter(|network| merchant_debit_networks.contains(network)) .filter(|network| is_routing_enabled || network.is_signature_network()) .map(|network| { if network.is_us_local_network() { *has_us_local_network = true; } api::ConnectorRoutingData { connector_data: connector_routing_data.connector_data.clone(), network: Some(network.clone()), action_type: connector_routing_data.action_type.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) }
{ "crate": "router", "file": "crates/router/src/core/debit_routing.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-5372194457605480289
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/routing.rs // Contains: 1 structs, 0 enums pub mod helpers; pub mod transformers; use std::collections::HashSet; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use api_models::routing::DynamicRoutingAlgoAccessor; use api_models::{ enums, mandates as mandates_api, open_router::{ DecideGatewayResponse, OpenRouterDecideGatewayRequest, UpdateScorePayload, UpdateScoreResponse, }, routing, routing::{ self as routing_types, RoutingRetrieveQuery, RuleMigrationError, RuleMigrationResponse, }, }; use async_trait::async_trait; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use common_utils::ext_traits::AsyncExt; use common_utils::request::Method; use diesel_models::routing_algorithm::RoutingAlgorithm; 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, }; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use helpers::{ enable_decision_engine_dynamic_routing_setup, update_decision_engine_dynamic_routing_setup, }; use hyperswitch_domain_models::{mandates, payment_address}; use payment_methods::helpers::StorageErrorExt; use rustc_hash::FxHashSet; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use storage_impl::redis::cache; #[cfg(feature = "payouts")] use super::payouts; use super::{ errors::RouterResult, payments::{ routing::{ utils::*, {self as payments_routing}, }, OperationSessionGetters, }, }; #[cfg(feature = "v1")] use crate::utils::ValueExt; #[cfg(feature = "v2")] use crate::{core::admin, utils::ValueExt}; use crate::{ core::{ errors::{self, CustomResult, RouterResponse}, metrics, utils as core_utils, }, db::StorageInterface, routes::SessionState, services::api as service_api, types::{ api, domain, storage::{self, enums as storage_enums}, transformers::{ForeignInto, ForeignTryFrom}, }, utils::{self, OptionExt}, }; pub enum TransactionData<'a> { Payment(PaymentsDslInput<'a>), #[cfg(feature = "payouts")] Payout(&'a payouts::PayoutData), } #[derive(Clone)] pub struct PaymentsDslInput<'a> { pub setup_mandate: Option<&'a mandates::MandateData>, pub payment_attempt: &'a storage::PaymentAttempt, pub payment_intent: &'a storage::PaymentIntent, pub payment_method_data: Option<&'a domain::PaymentMethodData>, pub address: &'a payment_address::PaymentAddress, pub recurring_details: Option<&'a mandates_api::RecurringDetails>, pub currency: storage_enums::Currency, } impl<'a> PaymentsDslInput<'a> { pub fn new( setup_mandate: Option<&'a mandates::MandateData>, payment_attempt: &'a storage::PaymentAttempt, payment_intent: &'a storage::PaymentIntent, payment_method_data: Option<&'a domain::PaymentMethodData>, address: &'a payment_address::PaymentAddress, recurring_details: Option<&'a mandates_api::RecurringDetails>, currency: storage_enums::Currency, ) -> Self { Self { setup_mandate, payment_attempt, payment_intent, payment_method_data, address, recurring_details, currency, } } } #[cfg(feature = "v2")] struct RoutingAlgorithmUpdate(RoutingAlgorithm); #[cfg(feature = "v2")] impl RoutingAlgorithmUpdate { pub fn create_new_routing_algorithm( request: &routing_types::RoutingConfigRequest, merchant_id: &common_utils::id_type::MerchantId, profile_id: common_utils::id_type::ProfileId, transaction_type: enums::TransactionType, ) -> Self { let algorithm_id = common_utils::generate_routing_id_of_default_length(); let timestamp = common_utils::date_time::now(); let algo = RoutingAlgorithm { algorithm_id, profile_id, merchant_id: merchant_id.clone(), name: request.name.clone(), description: Some(request.description.clone()), kind: request.algorithm.get_kind().foreign_into(), algorithm_data: serde_json::json!(request.algorithm), created_at: timestamp, modified_at: timestamp, algorithm_for: transaction_type, decision_engine_routing_id: None, }; Self(algo) } pub async fn fetch_routing_algo( merchant_id: &common_utils::id_type::MerchantId, algorithm_id: &common_utils::id_type::RoutingId, db: &dyn StorageInterface, ) -> RouterResult<Self> { let routing_algo = db .find_routing_algorithm_by_algorithm_id_merchant_id(algorithm_id, merchant_id) .await .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?; Ok(Self(routing_algo)) } } pub async fn retrieve_merchant_routing_dictionary( state: SessionState, merchant_context: domain::MerchantContext, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, query_params: RoutingRetrieveQuery, transaction_type: enums::TransactionType, ) -> RouterResponse<routing_types::RoutingKind> { metrics::ROUTING_MERCHANT_DICTIONARY_RETRIEVE.add(1, &[]); let routing_metadata: Vec<diesel_models::routing_algorithm::RoutingProfileMetadata> = state .store .list_routing_algorithm_metadata_by_merchant_id_transaction_type( merchant_context.get_merchant_account().get_id(), &transaction_type, i64::from(query_params.limit.unwrap_or_default()), i64::from(query_params.offset.unwrap_or_default()), ) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let routing_metadata = super::utils::filter_objects_based_on_profile_id_list( profile_id_list.clone(), routing_metadata, ); let mut 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)); // 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.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, &[]); Ok(service_api::ApplicationResponse::Json( routing_types::RoutingKind::RoutingAlgorithm(result), )) } 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, merchant_context: domain::MerchantContext, authentication_profile_id: Option<common_utils::id_type::ProfileId>, request: routing_types::RoutingConfigRequest, transaction_type: enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(1, &[]); let db = &*state.store; let key_manager_state = &(&state).into(); let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, merchant_context.get_merchant_key_store(), Some(&request.profile_id), merchant_context.get_merchant_account().get_id(), ) .await? .get_required_value("Profile")?; let merchant_id = merchant_context.get_merchant_account().get_id(); core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?; let all_mcas = state .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( key_manager_state, merchant_id, true, merchant_context.get_merchant_key_store(), ) .await .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_id.get_string_repr().to_owned(), })?; let name_mca_id_set = helpers::ConnectNameAndMCAIdForProfile( all_mcas.filter_by_profile(business_profile.get_id(), |mca| { (&mca.connector_name, mca.get_id()) }), ); let name_set = helpers::ConnectNameForProfile( all_mcas.filter_by_profile(business_profile.get_id(), |mca| &mca.connector_name), ); let algorithm_helper = helpers::RoutingAlgorithmHelpers { name_mca_id_set, name_set, routing_algorithm: &request.algorithm, }; algorithm_helper.validate_connectors_in_routing_config()?; let algo = RoutingAlgorithmUpdate::create_new_routing_algorithm( &request, merchant_context.get_merchant_account().get_id(), business_profile.get_id().to_owned(), transaction_type, ); let record = state .store .as_ref() .insert_routing_algorithm(algo.0) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let new_record = record.foreign_into(); metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(new_record)) } #[cfg(feature = "v1")] pub async fn create_routing_algorithm_under_profile( state: SessionState, merchant_context: domain::MerchantContext, authentication_profile_id: Option<common_utils::id_type::ProfileId>, request: routing_types::RoutingConfigRequest, transaction_type: enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { use api_models::routing::StaticRoutingAlgorithm as EuclidAlgorithm; metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let name = request .name .get_required_value("name") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "name" }) .attach_printable("Name of config not given")?; let description = request .description .get_required_value("description") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "description", }) .attach_printable("Description of config not given")?; let algorithm = request .algorithm .clone() .get_required_value("algorithm") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "algorithm", }) .attach_printable("Algorithm of config not given")?; let algorithm_id = common_utils::generate_routing_id_of_default_length(); let profile_id = request .profile_id .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "profile_id", }) .attach_printable("Profile_id not provided")?; 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")?; core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?; if algorithm.should_validate_connectors_in_routing_config() { helpers::validate_connectors_in_routing_config( &state, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().get_id(), &profile_id, &algorithm, ) .await?; } let mut decision_engine_routing_id: Option<String> = None; 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() { router_env::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) => { router_env::logger::error!( decision_engine_euclid_error = ?e, decision_engine_euclid_request = ?routing_rule, "failed to create rule in decision_engine" ); } } } } if decision_engine_routing_id.is_some() { router_env::logger::info!(routing_flow=?"create_euclid_routing_algorithm", is_equal=?"true", "decision_engine_euclid"); } else { router_env::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(), profile_id, merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), name: name.clone(), description: Some(description.clone()), kind: algorithm.get_kind().foreign_into(), algorithm_data: serde_json::json!(algorithm), created_at: timestamp, modified_at: timestamp, algorithm_for: transaction_type.to_owned(), decision_engine_routing_id, }; let record = db .insert_routing_algorithm(algo) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let new_record = record.foreign_into(); metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(new_record)) } #[cfg(feature = "v2")] pub async fn link_routing_config_under_profile( state: SessionState, merchant_context: domain::MerchantContext, profile_id: common_utils::id_type::ProfileId, algorithm_id: common_utils::id_type::RoutingId, transaction_type: &enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_LINK_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let routing_algorithm = RoutingAlgorithmUpdate::fetch_routing_algo( merchant_context.get_merchant_account().get_id(), &algorithm_id, db, ) .await?; utils::when(routing_algorithm.0.profile_id != profile_id, || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Profile Id is invalid for the routing config".to_string(), }) })?; 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")?; utils::when( routing_algorithm.0.algorithm_for != *transaction_type, || { Err(errors::ApiErrorResponse::PreconditionFailed { message: format!( "Cannot use {}'s routing algorithm for {} operation", routing_algorithm.0.algorithm_for, transaction_type ), }) }, )?; utils::when( business_profile.routing_algorithm_id == Some(algorithm_id.clone()) || business_profile.payout_routing_algorithm_id == Some(algorithm_id.clone()), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Algorithm is already active".to_string(), }) }, )?; admin::ProfileWrapper::new(business_profile) .update_profile_and_invalidate_routing_config_for_active_algorithm_id_update( db, key_manager_state, merchant_context.get_merchant_key_store(), algorithm_id, transaction_type, ) .await?; metrics::ROUTING_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json( routing_algorithm.0.foreign_into(), )) } #[cfg(feature = "v1")] pub async fn link_routing_config( state: SessionState, merchant_context: domain::MerchantContext, authentication_profile_id: Option<common_utils::id_type::ProfileId>, algorithm_id: common_utils::id_type::RoutingId, transaction_type: enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_LINK_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let routing_algorithm = db .find_routing_algorithm_by_algorithm_id_merchant_id( &algorithm_id, merchant_context.get_merchant_account().get_id(), ) .await .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?; let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, merchant_context.get_merchant_key_store(), Some(&routing_algorithm.profile_id), merchant_context.get_merchant_account().get_id(), ) .await? .get_required_value("Profile") .change_context(errors::ApiErrorResponse::ProfileNotFound { id: routing_algorithm.profile_id.get_string_repr().to_owned(), })?; core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?; match routing_algorithm.kind { diesel_models::enums::RoutingAlgorithmKind::Dynamic => { let mut 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(); utils::when( matches!( dynamic_routing_ref.success_based_algorithm, Some(routing::SuccessBasedAlgorithm { algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp { algorithm_id: Some(ref id), timestamp: _ }, enabled_feature: _ }) if id == &algorithm_id ) || matches!( dynamic_routing_ref.elimination_routing_algorithm, Some(routing::EliminationRoutingAlgorithm { algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp { algorithm_id: Some(ref id), timestamp: _ }, enabled_feature: _ }) if id == &algorithm_id ) || matches!( dynamic_routing_ref.contract_based_routing, Some(routing::ContractRoutingAlgorithm { algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp { algorithm_id: Some(ref id), timestamp: _ }, enabled_feature: _ }) if id == &algorithm_id ), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Algorithm is already active".to_string(), }) }, )?; if routing_algorithm.name == helpers::SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM { dynamic_routing_ref.update_algorithm_id( algorithm_id, dynamic_routing_ref .success_based_algorithm .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable( "missing success_based_algorithm in dynamic_algorithm_ref from business_profile table", )? .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.dynamic_routing_enabled { let existing_config = helpers::get_decision_engine_active_dynamic_routing_algorithm( &state, business_profile.get_id(), api_models::open_router::DecisionEngineDynamicAlgorithmType::SuccessRate, ) .await; if let Ok(Some(_config)) = existing_config { update_decision_engine_dynamic_routing_setup( &state, business_profile.get_id(), routing_algorithm.algorithm_data.clone(), routing_types::DynamicRoutingType::SuccessRateBasedRouting, &mut dynamic_routing_ref, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to update the success rate routing config in Decision Engine", )?; } else { let data: routing_types::SuccessBasedRoutingConfig = routing_algorithm.algorithm_data .clone() .parse_value("SuccessBasedRoutingConfig") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "unable to deserialize SuccessBasedRoutingConfig from routing algorithm data", )?; enable_decision_engine_dynamic_routing_setup( &state, business_profile.get_id(), routing_types::DynamicRoutingType::SuccessRateBasedRouting, &mut dynamic_routing_ref, Some(routing_types::DynamicRoutingPayload::SuccessBasedRoutingPayload(data)), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to setup decision engine dynamic routing")?; } } } } else if routing_algorithm.name == helpers::ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM { dynamic_routing_ref.update_algorithm_id( algorithm_id, dynamic_routing_ref .elimination_routing_algorithm .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable( "missing elimination_routing_algorithm in dynamic_algorithm_ref from business_profile table", )? .enabled_feature, routing_types::DynamicRoutingType::EliminationRouting, ); #[cfg(all(feature = "dynamic_routing", feature = "v1"))] { if state.conf.open_router.dynamic_routing_enabled { let existing_config = helpers::get_decision_engine_active_dynamic_routing_algorithm( &state, business_profile.get_id(), api_models::open_router::DecisionEngineDynamicAlgorithmType::Elimination, ) .await; if let Ok(Some(_config)) = existing_config { update_decision_engine_dynamic_routing_setup( &state, business_profile.get_id(), routing_algorithm.algorithm_data.clone(), routing_types::DynamicRoutingType::EliminationRouting, &mut dynamic_routing_ref, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to update the elimination routing config in Decision Engine", )?; } else { let data: routing_types::EliminationRoutingConfig = routing_algorithm.algorithm_data .clone() .parse_value("EliminationRoutingConfig") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "unable to deserialize EliminationRoutingConfig from routing algorithm data", )?; enable_decision_engine_dynamic_routing_setup( &state, business_profile.get_id(), routing_types::DynamicRoutingType::EliminationRouting, &mut dynamic_routing_ref, Some( routing_types::DynamicRoutingPayload::EliminationRoutingPayload( data, ), ), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to setup decision engine dynamic routing")?; } } } } else if routing_algorithm.name == helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM { dynamic_routing_ref.update_algorithm_id( algorithm_id, dynamic_routing_ref .contract_based_routing .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable( "missing contract_based_routing in dynamic_algorithm_ref from business_profile table", )? .enabled_feature, routing_types::DynamicRoutingType::ContractBasedRouting, ); } helpers::update_business_profile_active_dynamic_algorithm_ref( db, key_manager_state, merchant_context.get_merchant_key_store(), business_profile.clone(), dynamic_routing_ref, ) .await?; } diesel_models::enums::RoutingAlgorithmKind::Single | diesel_models::enums::RoutingAlgorithmKind::Priority | diesel_models::enums::RoutingAlgorithmKind::Advanced | diesel_models::enums::RoutingAlgorithmKind::VolumeSplit | diesel_models::enums::RoutingAlgorithmKind::ThreeDsDecisionRule => { let mut routing_ref: routing_types::RoutingAlgorithmRef = business_profile .routing_algorithm .clone() .map(|val| val.parse_value("RoutingAlgorithmRef")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "unable to deserialize routing algorithm ref from business profile", )? .unwrap_or_default(); utils::when(routing_algorithm.algorithm_for != transaction_type, || { Err(errors::ApiErrorResponse::PreconditionFailed { message: format!( "Cannot use {}'s routing algorithm for {} operation", routing_algorithm.algorithm_for, transaction_type ), }) })?; utils::when( routing_ref.algorithm_id == Some(algorithm_id.clone()), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Algorithm is already active".to_string(), }) }, )?; routing_ref.update_algorithm_id(algorithm_id); helpers::update_profile_active_algorithm_ref( db, key_manager_state, merchant_context.get_merchant_key_store(), 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" ); } } } // redact cgraph cache on rule activation helpers::redact_cgraph_cache( &state, merchant_context.get_merchant_account().get_id(), business_profile.get_id(), ) .await?; // redact routing cache on rule activation helpers::redact_routing_cache( &state, merchant_context.get_merchant_account().get_id(), business_profile.get_id(), ) .await?; metrics::ROUTING_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json( routing_algorithm.foreign_into(), )) } #[cfg(feature = "v2")] pub async fn retrieve_routing_algorithm_from_algorithm_id( state: SessionState, merchant_context: domain::MerchantContext, authentication_profile_id: Option<common_utils::id_type::ProfileId>, algorithm_id: common_utils::id_type::RoutingId, ) -> RouterResponse<routing_types::MerchantRoutingAlgorithm> { metrics::ROUTING_RETRIEVE_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let routing_algorithm = RoutingAlgorithmUpdate::fetch_routing_algo( merchant_context.get_merchant_account().get_id(), &algorithm_id, db, ) .await?; let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, merchant_context.get_merchant_key_store(), Some(&routing_algorithm.0.profile_id), merchant_context.get_merchant_account().get_id(), ) .await? .get_required_value("Profile") .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?; core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?; let response = routing_types::MerchantRoutingAlgorithm::foreign_try_from(routing_algorithm.0) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to parse routing algorithm")?; metrics::ROUTING_RETRIEVE_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(response)) } #[cfg(feature = "v1")] pub async fn retrieve_routing_algorithm_from_algorithm_id( state: SessionState, merchant_context: domain::MerchantContext, authentication_profile_id: Option<common_utils::id_type::ProfileId>, algorithm_id: common_utils::id_type::RoutingId, ) -> RouterResponse<routing_types::MerchantRoutingAlgorithm> { metrics::ROUTING_RETRIEVE_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let routing_algorithm = db .find_routing_algorithm_by_algorithm_id_merchant_id( &algorithm_id, merchant_context.get_merchant_account().get_id(), ) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, merchant_context.get_merchant_key_store(), Some(&routing_algorithm.profile_id), merchant_context.get_merchant_account().get_id(), ) .await? .get_required_value("Profile") .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?; core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?; let response = routing_types::MerchantRoutingAlgorithm::foreign_try_from(routing_algorithm) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to parse routing algorithm")?; metrics::ROUTING_RETRIEVE_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] pub async fn unlink_routing_config_under_profile( state: SessionState, merchant_context: domain::MerchantContext, profile_id: common_utils::id_type::ProfileId, transaction_type: &enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_UNLINK_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); 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")?; let routing_algo_id = match transaction_type { enums::TransactionType::Payment => business_profile.routing_algorithm_id.clone(), #[cfg(feature = "payouts")] enums::TransactionType::Payout => business_profile.payout_routing_algorithm_id.clone(), // TODO: Handle ThreeDsAuthentication Transaction Type for Three DS Decision Rule Algorithm configuration enums::TransactionType::ThreeDsAuthentication => todo!(), }; if let Some(algorithm_id) = routing_algo_id { let record = RoutingAlgorithmUpdate::fetch_routing_algo( merchant_context.get_merchant_account().get_id(), &algorithm_id, db, ) .await?; let response = record.0.foreign_into(); admin::ProfileWrapper::new(business_profile) .update_profile_and_invalidate_routing_config_for_active_algorithm_id_update( db, key_manager_state, merchant_context.get_merchant_key_store(), algorithm_id, transaction_type, ) .await?; metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(response)) } else { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Algorithm is already inactive".to_string(), })? } } #[cfg(feature = "v1")] pub async fn unlink_routing_config( state: SessionState, merchant_context: domain::MerchantContext, request: routing_types::RoutingConfigRequest, authentication_profile_id: Option<common_utils::id_type::ProfileId>, transaction_type: enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_UNLINK_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let profile_id = request .profile_id .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "profile_id", }) .attach_printable("Profile_id not provided")?; 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?; match business_profile { Some(business_profile) => { core_utils::validate_profile_id_from_auth_layer( authentication_profile_id, &business_profile, )?; let routing_algo_ref: routing_types::RoutingAlgorithmRef = match transaction_type { enums::TransactionType::Payment => business_profile.routing_algorithm.clone(), #[cfg(feature = "payouts")] enums::TransactionType::Payout => business_profile.payout_routing_algorithm.clone(), enums::TransactionType::ThreeDsAuthentication => { business_profile.three_ds_decision_rule_algorithm.clone() } } .map(|val| val.parse_value("RoutingAlgorithmRef")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to deserialize routing algorithm ref from merchant account")? .unwrap_or_default(); let timestamp = common_utils::date_time::now_unix_timestamp(); match routing_algo_ref.algorithm_id { Some(algorithm_id) => { let routing_algorithm: routing_types::RoutingAlgorithmRef = routing_types::RoutingAlgorithmRef { algorithm_id: None, timestamp, config_algo_id: routing_algo_ref.config_algo_id.clone(), surcharge_config_algo_id: routing_algo_ref.surcharge_config_algo_id, }; let record = db .find_routing_algorithm_by_profile_id_algorithm_id( &profile_id, &algorithm_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let response = record.foreign_into(); helpers::update_profile_active_algorithm_ref( db, key_manager_state, merchant_context.get_merchant_key_store(), business_profile.clone(), routing_algorithm, &transaction_type, ) .await?; // redact cgraph cache on rule activation helpers::redact_cgraph_cache( &state, merchant_context.get_merchant_account().get_id(), business_profile.get_id(), ) .await?; // redact routing cache on rule activation helpers::redact_routing_cache( &state, merchant_context.get_merchant_account().get_id(), business_profile.get_id(), ) .await?; metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(response)) } None => Err(errors::ApiErrorResponse::PreconditionFailed { message: "Algorithm is already inactive".to_string(), })?, } } None => Err(errors::ApiErrorResponse::InvalidRequestData { message: "The business_profile is not present".to_string(), } .into()), } } #[cfg(feature = "v2")] pub async fn update_default_fallback_routing( state: SessionState, merchant_context: domain::MerchantContext, profile_id: common_utils::id_type::ProfileId, updated_list_of_connectors: Vec<routing_types::RoutableConnectorChoice>, ) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> { metrics::ROUTING_UPDATE_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let 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")?; let profile_wrapper = admin::ProfileWrapper::new(profile); let default_list_of_connectors = profile_wrapper.get_default_fallback_list_of_connector_under_profile()?; utils::when( default_list_of_connectors.len() != updated_list_of_connectors.len(), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "current config and updated config have different lengths".to_string(), }) }, )?; let existing_set_of_default_connectors: FxHashSet<String> = FxHashSet::from_iter( default_list_of_connectors .iter() .map(|conn_choice| conn_choice.to_string()), ); let updated_set_of_default_connectors: FxHashSet<String> = FxHashSet::from_iter( updated_list_of_connectors .iter() .map(|conn_choice| conn_choice.to_string()), ); let symmetric_diff_between_existing_and_updated_connectors: Vec<String> = existing_set_of_default_connectors .symmetric_difference(&updated_set_of_default_connectors) .cloned() .collect(); utils::when( !symmetric_diff_between_existing_and_updated_connectors.is_empty(), || { Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "connector mismatch between old and new configs ({})", symmetric_diff_between_existing_and_updated_connectors.join(", ") ), }) }, )?; profile_wrapper .update_default_fallback_routing_of_connectors_under_profile( db, &updated_list_of_connectors, key_manager_state, merchant_context.get_merchant_key_store(), ) .await?; metrics::ROUTING_UPDATE_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json( updated_list_of_connectors, )) } #[cfg(feature = "v1")] pub async fn update_default_routing_config( state: SessionState, merchant_context: domain::MerchantContext, updated_config: Vec<routing_types::RoutableConnectorChoice>, transaction_type: &enums::TransactionType, ) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> { metrics::ROUTING_UPDATE_CONFIG.add(1, &[]); let db = state.store.as_ref(); let default_config = helpers::get_merchant_default_config( db, merchant_context .get_merchant_account() .get_id() .get_string_repr(), transaction_type, ) .await?; utils::when(default_config.len() != updated_config.len(), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "current config and updated config have different lengths".to_string(), }) })?; let existing_set: FxHashSet<String> = FxHashSet::from_iter(default_config.iter().map(|c| c.to_string())); let updated_set: FxHashSet<String> = FxHashSet::from_iter(updated_config.iter().map(|c| c.to_string())); let symmetric_diff: Vec<String> = existing_set .symmetric_difference(&updated_set) .cloned() .collect(); utils::when(!symmetric_diff.is_empty(), || { Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "connector mismatch between old and new configs ({})", symmetric_diff.join(", ") ), }) })?; helpers::update_merchant_default_config( db, merchant_context .get_merchant_account() .get_id() .get_string_repr(), updated_config.clone(), transaction_type, ) .await?; metrics::ROUTING_UPDATE_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(updated_config)) } #[cfg(feature = "v2")] pub async fn retrieve_default_fallback_algorithm_for_profile( state: SessionState, merchant_context: domain::MerchantContext, profile_id: common_utils::id_type::ProfileId, ) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> { metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let 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")?; let connectors_choice = admin::ProfileWrapper::new(profile) .get_default_fallback_list_of_connector_under_profile()?; metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(connectors_choice)) } #[cfg(feature = "v1")] pub async fn retrieve_default_routing_config( state: SessionState, profile_id: Option<common_utils::id_type::ProfileId>, merchant_context: domain::MerchantContext, transaction_type: &enums::TransactionType, ) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> { metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG.add(1, &[]); let db = state.store.as_ref(); let id = profile_id .map(|profile_id| profile_id.get_string_repr().to_owned()) .unwrap_or_else(|| { merchant_context .get_merchant_account() .get_id() .get_string_repr() .to_string() }); helpers::get_merchant_default_config(db, &id, transaction_type) .await .map(|conn_choice| { metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(1, &[]); service_api::ApplicationResponse::Json(conn_choice) }) } #[cfg(feature = "v2")] pub async fn retrieve_routing_config_under_profile( state: SessionState, merchant_context: domain::MerchantContext, query_params: RoutingRetrieveQuery, profile_id: common_utils::id_type::ProfileId, 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 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")?; let record = db .list_routing_algorithm_metadata_by_profile_id( business_profile.get_id(), i64::from(query_params.limit.unwrap_or_default()), i64::from(query_params.offset.unwrap_or_default()), ) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let active_algorithms = record .into_iter() .filter(|routing_rec| &routing_rec.algorithm_for == transaction_type) .map(|routing_algo| routing_algo.foreign_into()) .collect::<Vec<_>>(); metrics::ROUTING_RETRIEVE_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json( routing_types::LinkedRoutingConfigRetrieveResponse::ProfileBased(active_algorithms), )) } #[cfg(feature = "v1")] pub async fn retrieve_linked_routing_config( state: SessionState, merchant_context: domain::MerchantContext, authentication_profile_id: Option<common_utils::id_type::ProfileId>, query_params: routing_types::RoutingRetrieveLinkQuery, 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_key_store, Some(&profile_id), merchant_id, ) .await? .map(|profile| vec![profile]) .get_required_value("Profile") .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })? } else { let business_profile = db .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, ) }; let mut active_algorithms = Vec::new(); for business_profile in business_profiles { 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, #[cfg(feature = "payouts")] enums::TransactionType::Payout => &business_profile.payout_routing_algorithm, enums::TransactionType::ThreeDsAuthentication => { &business_profile.three_ds_decision_rule_algorithm } } .clone() .map(|val| val.parse_value("RoutingAlgorithmRef")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to deserialize routing algorithm ref from merchant account")? .unwrap_or_default(); if let Some(algorithm_id) = routing_ref.algorithm_id { let record = db .find_routing_algorithm_metadata_by_algorithm_id_profile_id( &algorithm_id, profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; 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 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)?; if record.algorithm_for == transaction_type { active_algorithms.push(record.foreign_into()); } } } metrics::ROUTING_RETRIEVE_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json( 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, merchant_context: domain::MerchantContext, transaction_type: &enums::TransactionType, ) -> RouterResponse<Vec<routing_types::ProfileDefaultRoutingConfig>> { metrics::ROUTING_RETRIEVE_CONFIG_FOR_PROFILE.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let all_profiles = db .list_profile_by_merchant_id( key_manager_state, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().get_id(), ) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound) .attach_printable("error retrieving all business profiles for merchant")?; let retrieve_config_futures = all_profiles .iter() .map(|prof| { helpers::get_merchant_default_config( db, prof.get_id().get_string_repr(), transaction_type, ) }) .collect::<Vec<_>>(); let configs = futures::future::join_all(retrieve_config_futures) .await .into_iter() .collect::<Result<Vec<_>, _>>()?; let default_configs = configs .into_iter() .zip(all_profiles.iter().map(|prof| prof.get_id().to_owned())) .map( |(config, profile_id)| routing_types::ProfileDefaultRoutingConfig { profile_id, connectors: config, }, ) .collect::<Vec<_>>(); metrics::ROUTING_RETRIEVE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(default_configs)) } pub async fn update_default_routing_config_for_profile( state: SessionState, merchant_context: domain::MerchantContext, updated_config: Vec<routing_types::RoutableConnectorChoice>, profile_id: common_utils::id_type::ProfileId, transaction_type: &enums::TransactionType, ) -> RouterResponse<routing_types::ProfileDefaultRoutingConfig> { metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); 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(), })?; let default_config = helpers::get_merchant_default_config( db, business_profile.get_id().get_string_repr(), transaction_type, ) .await?; utils::when(default_config.len() != updated_config.len(), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "current config and updated config have different lengths".to_string(), }) })?; let existing_set = FxHashSet::from_iter( default_config .iter() .map(|c| (c.connector.to_string(), c.merchant_connector_id.as_ref())), ); let updated_set = FxHashSet::from_iter( updated_config .iter() .map(|c| (c.connector.to_string(), c.merchant_connector_id.as_ref())), ); let symmetric_diff = existing_set .symmetric_difference(&updated_set) .cloned() .collect::<Vec<_>>(); utils::when(!symmetric_diff.is_empty(), || { let error_str = symmetric_diff .into_iter() .map(|(connector, ident)| format!("'{connector}:{ident:?}'")) .collect::<Vec<_>>() .join(", "); Err(errors::ApiErrorResponse::InvalidRequestData { message: format!("connector mismatch between old and new configs ({error_str})"), }) })?; helpers::update_merchant_default_config( db, business_profile.get_id().get_string_repr(), updated_config.clone(), transaction_type, ) .await?; metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json( routing_types::ProfileDefaultRoutingConfig { profile_id: business_profile.get_id().to_owned(), connectors: updated_config, }, )) } // Toggle the specific routing type as well as add the default configs in RoutingAlgorithm table // and update the same in business profile table. #[cfg(all(feature = "v1", feature = "dynamic_routing"))] pub async fn toggle_specific_dynamic_routing( state: SessionState, merchant_context: domain::MerchantContext, feature_to_enable: routing::DynamicRoutingFeatures, profile_id: common_utils::id_type::ProfileId, dynamic_routing_type: routing::DynamicRoutingType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_CREATE_REQUEST_RECEIVED.add( 1, 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(); 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(); match feature_to_enable { routing::DynamicRoutingFeatures::Metrics | routing::DynamicRoutingFeatures::DynamicConnectorSelection => { // occurs when algorithm is already present in the db // 1. If present with same feature then return response as already enabled // 2. Else update the feature and persist the same on db // 3. If not present in db then create a new default entry Box::pin(helpers::enable_dynamic_routing_algorithm( &state, merchant_context.get_merchant_key_store().clone(), business_profile, feature_to_enable, dynamic_routing_algo_ref, dynamic_routing_type, None, )) .await } routing::DynamicRoutingFeatures::None => { // disable specific dynamic routing for the requested profile helpers::disable_dynamic_routing_algorithm( &state, merchant_context.get_merchant_key_store().clone(), business_profile, dynamic_routing_algo_ref, dynamic_routing_type, ) .await } } } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] pub async fn create_specific_dynamic_routing( state: SessionState, merchant_context: domain::MerchantContext, feature_to_enable: routing::DynamicRoutingFeatures, profile_id: common_utils::id_type::ProfileId, dynamic_routing_type: routing::DynamicRoutingType, payload: routing_types::DynamicRoutingPayload, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_CREATE_REQUEST_RECEIVED.add( 1, 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(); 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(); match feature_to_enable { routing::DynamicRoutingFeatures::Metrics | routing::DynamicRoutingFeatures::DynamicConnectorSelection => { Box::pin(helpers::enable_dynamic_routing_algorithm( &state, merchant_context.get_merchant_key_store().clone(), business_profile, feature_to_enable, dynamic_routing_algo_ref, dynamic_routing_type, Some(payload), )) .await } routing::DynamicRoutingFeatures::None => { // disable specific dynamic routing for the requested profile helpers::disable_dynamic_routing_algorithm( &state, merchant_context.get_merchant_key_store().clone(), business_profile, dynamic_routing_algo_ref, dynamic_routing_type, ) .await } } } #[cfg(feature = "v1")] pub async fn configure_dynamic_routing_volume_split( state: SessionState, merchant_context: domain::MerchantContext, profile_id: common_utils::id_type::ProfileId, routing_info: routing::RoutingVolumeSplit, ) -> RouterResponse<routing::RoutingVolumeSplit> { metrics::ROUTING_CREATE_REQUEST_RECEIVED.add( 1, router_env::metric_attributes!(("profile_id", profile_id.clone())), ); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); utils::when( routing_info.split > crate::consts::DYNAMIC_ROUTING_MAX_VOLUME, || { Err(errors::ApiErrorResponse::InvalidRequestData { message: "Dynamic routing volume split should be less than 100".to_string(), }) }, )?; 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 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(); dynamic_routing_algo_ref.update_volume_split(Some(routing_info.split)); helpers::update_business_profile_active_dynamic_algorithm_ref( db, &((&state).into()), merchant_context.get_merchant_key_store(), business_profile.clone(), dynamic_routing_algo_ref.clone(), ) .await?; 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, request: routing_types::SuccessBasedRoutingConfig, 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::SuccessRateBasedRouting.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::SuccessBasedRoutingConfig = dynamic_routing_algo_to_update .algorithm_data .parse_value::<routing::SuccessBasedRoutingConfig>("SuccessBasedRoutingConfig") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to deserialize algorithm data from routing table into SuccessBasedRoutingConfig")?; 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.clone()), 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) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to insert record in routing algorithm table")?; // redact cache for success based routing configs let cache_key = format!( "{}_{}", profile_id.get_string_repr(), algorithm_id.get_string_repr() ); let cache_entries_to_redact = vec![cache::CacheKind::SuccessBasedDynamicRoutingCache( cache_key.into(), )]; let _ = cache::redact_from_redis_and_publish( state.store.get_cache_store().as_ref(), cache_entries_to_redact, ) .await .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(); metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add( 1, router_env::metric_attributes!(("profile_id", profile_id.clone())), ); if !state.conf.open_router.dynamic_routing_enabled { state .grpc_client .dynamic_routing .as_ref() .async_map(|dr_client| async { dr_client .success_rate_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)) } #[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, decision_engine_routing_id: None, }; 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| 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(); metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add( 1, router_env::metric_attributes!(("profile_id", profile_id.clone())), ); if !state.conf.open_router.dynamic_routing_enabled { state .grpc_client .dynamic_routing .as_ref() .async_map(|dr_client| async { dr_client .elimination_based_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)) } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] pub async fn contract_based_dynamic_routing_setup( state: SessionState, merchant_context: domain::MerchantContext, profile_id: common_utils::id_type::ProfileId, feature_to_enable: routing_types::DynamicRoutingFeatures, config: Option<routing_types::ContractBasedRoutingConfig>, ) -> RouterResult<service_api::ApplicationResponse<routing_types::RoutingDictionaryRecord>> { 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 mut dynamic_routing_algo_ref: Option<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", ) .ok() .flatten(); utils::when( dynamic_routing_algo_ref .as_mut() .and_then(|algo| { algo.contract_based_routing.as_mut().map(|contract_algo| { *contract_algo.get_enabled_features() == feature_to_enable && contract_algo .clone() .get_algorithm_id_with_timestamp() .algorithm_id .is_some() }) }) .unwrap_or(false), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Contract Routing with specified features is already enabled".to_string(), }) }, )?; if feature_to_enable == routing::DynamicRoutingFeatures::None { let algorithm = dynamic_routing_algo_ref .clone() .get_required_value("dynamic_routing_algo_ref") .attach_printable("Failed to get dynamic_routing_algo_ref")?; return helpers::disable_dynamic_routing_algorithm( &state, merchant_context.get_merchant_key_store().clone(), business_profile, algorithm, routing_types::DynamicRoutingType::ContractBasedRouting, ) .await; } let config = config .get_required_value("ContractBasedRoutingConfig") .attach_printable("Failed to get ContractBasedRoutingConfig from request")?; let merchant_id = business_profile.merchant_id.clone(); let algorithm_id = common_utils::generate_routing_id_of_default_length(); let timestamp = common_utils::date_time::now(); let algo = RoutingAlgorithm { algorithm_id: algorithm_id.clone(), profile_id: profile_id.clone(), merchant_id, name: helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(), description: None, kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic, algorithm_data: serde_json::json!(config), 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 // 2. if dynamic_routing_algo_ref is not present, create a new dynamic_routing_algo_ref with contract algo set up let final_algorithm = if let Some(mut algo) = dynamic_routing_algo_ref { algo.update_algorithm_id( algorithm_id, feature_to_enable, routing_types::DynamicRoutingType::ContractBasedRouting, ); if feature_to_enable == routing::DynamicRoutingFeatures::DynamicConnectorSelection { algo.disable_algorithm_id(routing_types::DynamicRoutingType::SuccessRateBasedRouting); } algo } else { let contract_algo = routing_types::ContractRoutingAlgorithm { algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp::new(Some( algorithm_id.clone(), )), enabled_feature: feature_to_enable, }; routing_types::DynamicRoutingAlgorithmRef { success_based_algorithm: None, 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), } }; // validate the contained mca_ids let mut contained_mca = Vec::new(); if let Some(info_vec) = &config.label_info { for info in info_vec { utils::when( contained_mca.iter().any(|mca_id| mca_id == &info.mca_id), || { Err(error_stack::Report::new( errors::ApiErrorResponse::InvalidRequestData { message: "Duplicate mca configuration received".to_string(), }, )) }, )?; contained_mca.push(info.mca_id.to_owned()); } let validation_futures: Vec<_> = info_vec .iter() .map(|info| async { let mca_id = info.mca_id.clone(); let label = info.label.clone(); let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_context.get_merchant_account().get_id(), &mca_id, merchant_context.get_merchant_key_store(), ) .await .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: mca_id.get_string_repr().to_owned(), })?; utils::when(mca.connector_name != label, || { Err(error_stack::Report::new( errors::ApiErrorResponse::InvalidRequestData { message: "Incorrect mca configuration received".to_string(), }, )) })?; Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(()) }) .collect(); futures::future::try_join_all(validation_futures).await?; } let record = db .insert_routing_algorithm(algo) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to insert record in routing algorithm table")?; helpers::update_business_profile_active_dynamic_algorithm_ref( db, key_manager_state, merchant_context.get_merchant_key_store(), business_profile, final_algorithm, ) .await?; let new_record = record.foreign_into(); metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add( 1, router_env::metric_attributes!(("profile_id", profile_id.get_string_repr().to_string())), ); Ok(service_api::ApplicationResponse::Json(new_record)) } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] pub async fn contract_based_routing_update_configs( state: SessionState, request: routing_types::ContractBasedRoutingConfig, merchant_context: domain::MerchantContext, 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.get_string_repr().to_owned()), ( "algorithm_type", routing::DynamicRoutingType::ContractBasedRouting.to_string() ) ), ); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); 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::ContractBasedRoutingConfig = dynamic_routing_algo_to_update .algorithm_data .parse_value::<routing::ContractBasedRoutingConfig>("ContractBasedRoutingConfig") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to deserialize algorithm data from routing table into ContractBasedRoutingConfig")?; // validate the contained mca_ids let mut contained_mca = Vec::new(); if let Some(info_vec) = &request.label_info { for info in info_vec { let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_context.get_merchant_account().get_id(), &info.mca_id, merchant_context.get_merchant_key_store(), ) .await .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: info.mca_id.get_string_repr().to_owned(), })?; utils::when(mca.connector_name != info.label, || { Err(errors::ApiErrorResponse::InvalidRequestData { message: "Incorrect mca configuration received".to_string(), }) })?; utils::when( contained_mca.iter().any(|mca_id| mca_id == &info.mca_id), || { Err(error_stack::Report::new( errors::ApiErrorResponse::InvalidRequestData { message: "Duplicate mca configuration received".to_string(), }, )) }, )?; contained_mca.push(info.mca_id.to_owned()); } } 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, decision_engine_routing_id: None, }; 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 contract based routing configs let cache_key = format!( "{}_{}", profile_id.get_string_repr(), algorithm_id.get_string_repr() ); let cache_entries_to_redact = vec![cache::CacheKind::ContractBasedDynamicRoutingCache( cache_key.into(), )]; let _ = cache::redact_from_redis_and_publish( state.store.get_cache_store().as_ref(), cache_entries_to_redact, ) .await .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(); metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add( 1, router_env::metric_attributes!(("profile_id", profile_id.get_string_repr().to_owned())), ); state .grpc_client .dynamic_routing .as_ref() .async_map(|dr_client| async { dr_client .contract_based_client .invalidate_contracts( profile_id.get_string_repr().into(), state.get_grpc_headers(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to invalidate the contract based routing keys") }) .await .transpose()?; Ok(service_api::ApplicationResponse::Json(new_record)) } #[async_trait] pub trait GetRoutableConnectorsForChoice { async fn get_routable_connectors( &self, db: &dyn StorageInterface, business_profile: &domain::Profile, ) -> RouterResult<RoutableConnectors>; } pub struct StraightThroughAlgorithmTypeSingle(pub serde_json::Value); #[async_trait] impl GetRoutableConnectorsForChoice for StraightThroughAlgorithmTypeSingle { async fn get_routable_connectors( &self, _db: &dyn StorageInterface, _business_profile: &domain::Profile, ) -> RouterResult<RoutableConnectors> { let straight_through_routing_algorithm = self .0 .clone() .parse_value::<api::routing::StraightThroughAlgorithm>("RoutingAlgorithm") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse the straight through routing algorithm")?; let routable_connector = match straight_through_routing_algorithm { api::routing::StraightThroughAlgorithm::Single(connector) => { vec![*connector] } api::routing::StraightThroughAlgorithm::Priority(_) | api::routing::StraightThroughAlgorithm::VolumeSplit(_) => { Err(errors::RoutingError::DslIncorrectSelectionAlgorithm) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Unsupported algorithm received as a result of static routing", )? } }; Ok(RoutableConnectors(routable_connector)) } } pub struct DecideConnector; #[async_trait] impl GetRoutableConnectorsForChoice for DecideConnector { async fn get_routable_connectors( &self, db: &dyn StorageInterface, business_profile: &domain::Profile, ) -> RouterResult<RoutableConnectors> { let fallback_config = helpers::get_merchant_default_config( db, business_profile.get_id().get_string_repr(), &common_enums::TransactionType::Payment, ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; Ok(RoutableConnectors(fallback_config)) } } pub struct RoutableConnectors(Vec<routing_types::RoutableConnectorChoice>); impl RoutableConnectors { pub fn filter_network_transaction_id_flow_supported_connectors( self, nit_connectors: HashSet<String>, ) -> Self { let connectors = self .0 .into_iter() .filter(|routable_connector_choice| { nit_connectors.contains(&routable_connector_choice.connector.to_string()) }) .collect(); Self(connectors) } pub async fn construct_dsl_and_perform_eligibility_analysis<F, D>( self, state: &SessionState, key_store: &domain::MerchantKeyStore, payment_data: &D, profile_id: &common_utils::id_type::ProfileId, ) -> RouterResult<Vec<api::ConnectorData>> where F: Send + Clone, D: OperationSessionGetters<F>, { let payments_dsl_input = PaymentsDslInput::new( 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(), ); let routable_connector_choice = self.0.clone(); let backend_input = payments_routing::make_dsl_input(&payments_dsl_input) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct dsl input")?; let connectors = payments_routing::perform_cgraph_filtering( state, key_store, routable_connector_choice, backend_input, None, profile_id, &common_enums::TransactionType::Payment, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Eligibility analysis failed for routable connectors")?; 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(), ) }) .collect::<CustomResult<Vec<_>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; 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; 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(); let business_profile = 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(), })?; #[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, ]; #[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, 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(); 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(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()))) } 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)" ); 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(), 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:?}"), ); } } } Ok(routing_types::RuleMigrationResult { success: response_list, errors: error_list, }) } pub async fn decide_gateway_open_router( state: SessionState, req_body: OpenRouterDecideGatewayRequest, ) -> RouterResponse<DecideGatewayResponse> { let response = if state.conf.open_router.dynamic_routing_enabled { SRApiClient::send_decision_engine_request( &state, Method::Post, "decide-gateway", Some(req_body), None, None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError)? .response .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to perform decide gateway call with open router")? } else { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Dynamic routing is not enabled")? }; Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) } pub async fn update_gateway_score_open_router( state: SessionState, req_body: UpdateScorePayload, ) -> RouterResponse<UpdateScoreResponse> { let response = if state.conf.open_router.dynamic_routing_enabled { SRApiClient::send_decision_engine_request( &state, Method::Post, "update-gateway-score", Some(req_body), None, None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError)? .response .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to perform update gateway score call with open router")? } else { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Dynamic routing is not enabled")? }; Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) }
{ "crate": "router", "file": "crates/router/src/core/routing.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-2112312769310321398
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/three_ds_decision_rule.rs // Contains: 1 structs, 0 enums pub mod utils; use common_types::three_ds_decision_rule_engine::ThreeDSDecisionRule; use common_utils::ext_traits::ValueExt; use error_stack::ResultExt; use euclid::{ backend::{self, inputs as dsl_inputs, EuclidBackend}, frontend::ast, }; use hyperswitch_domain_models::merchant_context::MerchantContext; use router_env::{instrument, tracing}; use crate::{ core::{ errors, errors::{RouterResponse, StorageErrorExt}, }, services, types::transformers::ForeignFrom, SessionState, }; #[instrument(skip_all)] pub async fn execute_three_ds_decision_rule( state: SessionState, merchant_context: MerchantContext, request: api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteRequest, ) -> RouterResponse<api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteResponse> { let decision = get_three_ds_decision_rule_output( &state, merchant_context.get_merchant_account().get_id(), request.clone(), ) .await?; // Construct response let response = api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteResponse { decision }; Ok(services::ApplicationResponse::Json(response)) } pub async fn get_three_ds_decision_rule_output( state: &SessionState, merchant_id: &common_utils::id_type::MerchantId, request: api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteRequest, ) -> errors::RouterResult<common_types::three_ds_decision_rule_engine::ThreeDSDecision> { let db = state.store.as_ref(); // Retrieve the rule from database let routing_algorithm = db .find_routing_algorithm_by_algorithm_id_merchant_id(&request.routing_id, merchant_id) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let algorithm: Algorithm = routing_algorithm .algorithm_data .parse_value("Algorithm") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error parsing program from three_ds_decision rule algorithm")?; let program: ast::Program<ThreeDSDecisionRule> = algorithm .data .parse_value("Program<ThreeDSDecisionRule>") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error parsing program from three_ds_decision rule algorithm")?; // Construct backend input from request let backend_input = dsl_inputs::BackendInput::foreign_from(request.clone()); // Initialize interpreter with the rule program let interpreter = backend::VirInterpreterBackend::with_program(program) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error initializing DSL interpreter backend")?; // Execute the rule let result = interpreter .execute(backend_input) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error executing 3DS decision rule")?; // Apply PSD2 validations to the decision let final_decision = utils::apply_psd2_validations_during_execute(result.get_output().get_decision(), &request); Ok(final_decision) } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct Algorithm { data: serde_json::Value, }
{ "crate": "router", "file": "crates/router/src/core/three_ds_decision_rule.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_851327162418810293
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/utils.rs // Contains: 1 structs, 0 enums pub mod customer_validation; pub mod refunds_transformers; pub mod refunds_validator; use std::{collections::HashSet, marker::PhantomData, str::FromStr}; use api_models::enums::{Connector, DisputeStage, DisputeStatus}; #[cfg(feature = "payouts")] use api_models::payouts::PayoutVendorAccountDetails; use common_enums::{IntentStatus, RequestIncrementalAuthorization}; #[cfg(feature = "payouts")] use common_utils::{crypto::Encryptable, pii::Email}; use common_utils::{ errors::CustomResult, ext_traits::AsyncExt, types::{keymanager::KeyManagerState, ConnectorTransactionIdTrait, MinorUnit}, }; use diesel_models::refund as diesel_refund; use error_stack::{report, ResultExt}; #[cfg(feature = "v2")] use hyperswitch_domain_models::types::VaultRouterData; use hyperswitch_domain_models::{ merchant_connector_account::MerchantConnectorAccount, payment_address::PaymentAddress, router_data::ErrorResponse, router_data_v2::flow_common_types::VaultConnectorFlowData, router_request_types, types::{OrderDetailsWithAmount, VaultRouterDataV2}, }; use hyperswitch_interfaces::api::ConnectorSpecifications; #[cfg(feature = "v2")] use masking::ExposeOptionInterface; use masking::Secret; #[cfg(feature = "payouts")] use masking::{ExposeInterface, PeekInterface}; use maud::{html, PreEscaped}; use regex::Regex; use router_env::{instrument, tracing}; use super::payments::helpers; #[cfg(feature = "payouts")] use super::payouts::{helpers as payout_helpers, PayoutData}; #[cfg(feature = "payouts")] use crate::core::payments; #[cfg(feature = "v2")] use crate::core::payments::helpers as payment_helpers; use crate::{ configs::Settings, consts, core::{ errors::{self, RouterResult, StorageErrorExt}, payments::PaymentData, }, db::StorageInterface, routes::SessionState, types::{ self, api, domain, storage::{self, enums}, PollConfig, }, utils::{generate_id, OptionExt, ValueExt}, }; pub const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_DISPUTE_FLOW: &str = "irrelevant_connector_request_reference_id_in_dispute_flow"; const IRRELEVANT_ATTEMPT_ID_IN_DISPUTE_FLOW: &str = "irrelevant_attempt_id_in_dispute_flow"; #[cfg(all(feature = "payouts", feature = "v2"))] #[instrument(skip_all)] pub async fn construct_payout_router_data<'a, F>( _state: &SessionState, _connector_data: &api::ConnectorData, _merchant_context: &domain::MerchantContext, _payout_data: &mut PayoutData, ) -> RouterResult<types::PayoutsRouterData<F>> { todo!() } #[cfg(all(feature = "payouts", feature = "v1"))] #[instrument(skip_all)] pub async fn construct_payout_router_data<'a, F>( state: &SessionState, connector_data: &api::ConnectorData, merchant_context: &domain::MerchantContext, payout_data: &mut PayoutData, ) -> RouterResult<types::PayoutsRouterData<F>> { let merchant_connector_account = payout_data .merchant_connector_account .clone() .get_required_value("merchant_connector_account")?; let connector_name = connector_data.connector_name; let connector_auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError)?; let billing = payout_data.billing_address.to_owned(); let billing_address = billing.map(api_models::payments::Address::from); let address = PaymentAddress::new(None, billing_address.map(From::from), None, None); let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let payouts = &payout_data.payouts; let payout_attempt = &payout_data.payout_attempt; let customer_details = &payout_data.customer_details; let connector_label = format!( "{}_{}", payout_data.profile_id.get_string_repr(), connector_name ); let connector_customer_id = customer_details .as_ref() .and_then(|c| c.connector_customer.as_ref()) .and_then(|connector_customer_value| { connector_customer_value .clone() .expose() .get(connector_label) .cloned() }) .and_then(|id| serde_json::from_value::<String>(id).ok()); let vendor_details: Option<PayoutVendorAccountDetails> = match api_models::enums::PayoutConnectors::try_from(connector_name.to_owned()).map_err( |err| report!(errors::ApiErrorResponse::InternalServerError).attach_printable(err), )? { api_models::enums::PayoutConnectors::Stripe => { payout_data.payouts.metadata.to_owned().and_then(|meta| { let val = meta .peek() .to_owned() .parse_value("PayoutVendorAccountDetails") .ok(); val }) } _ => None, }; let webhook_url = helpers::create_webhook_url( &state.base_url, &merchant_context.get_merchant_account().get_id().to_owned(), merchant_connector_account .get_mca_id() .get_required_value("merchant_connector_id")? .get_string_repr(), ); let connector_transfer_method_id = payout_helpers::should_create_connector_transfer_method(&*payout_data, connector_data)?; let browser_info = payout_data.browser_info.to_owned(); let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), customer_id: customer_details.to_owned().map(|c| c.customer_id), tenant_id: state.tenant.tenant_id.clone(), connector_customer: connector_customer_id, connector: connector_name.to_string(), payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("payout") .get_string_repr() .to_owned(), attempt_id: "".to_string(), status: enums::AttemptStatus::Failure, payment_method: enums::PaymentMethod::default(), payment_method_type: None, connector_auth_type, description: None, address, auth_type: enums::AuthenticationType::default(), connector_meta_data: merchant_connector_account.get_metadata(), connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: None, minor_amount_captured: None, payment_method_status: None, request: types::PayoutsData { payout_id: payouts.payout_id.clone(), amount: payouts.amount.get_amount_as_i64(), minor_amount: payouts.amount, connector_payout_id: payout_attempt.connector_payout_id.clone(), destination_currency: payouts.destination_currency, source_currency: payouts.source_currency, entity_type: payouts.entity_type.to_owned(), payout_type: payouts.payout_type, vendor_details, priority: payouts.priority, customer_details: customer_details .to_owned() .map(|c| payments::CustomerDetails { customer_id: Some(c.customer_id), name: c.name.map(Encryptable::into_inner), email: c.email.map(Email::from), phone: c.phone.map(Encryptable::into_inner), phone_country_code: c.phone_country_code, tax_registration_id: c.tax_registration_id.map(Encryptable::into_inner), }), connector_transfer_method_id, webhook_url: Some(webhook_url), browser_info, payout_connector_metadata: payout_attempt.payout_connector_metadata.to_owned(), }, response: Ok(types::PayoutsResponseData::default()), access_token: None, session_token: None, reference_id: None, payment_method_token: None, recurring_mandate_payment_data: None, preprocessing_id: None, connector_request_reference_id: payout_attempt.payout_attempt_id.clone(), payout_method_data: payout_data.payout_method_data.to_owned(), quote_id: None, test_mode, payment_method_balance: None, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, }; Ok(router_data) } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_refund_router_data<'a, F>( state: &'a SessionState, connector_enum: Connector, merchant_context: &domain::MerchantContext, payment_intent: &'a storage::PaymentIntent, payment_attempt: &storage::PaymentAttempt, refund: &'a diesel_refund::Refund, merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails, ) -> RouterResult<types::RefundsRouterData<F>> { let auth_type = merchant_connector_account .get_connector_account_details() .change_context(errors::ApiErrorResponse::InternalServerError)?; let status = payment_attempt.status; let payment_amount = payment_attempt.get_total_amount(); let currency = payment_intent.get_currency(); let payment_method_type = payment_attempt.payment_method_type; let webhook_url = match merchant_connector_account { domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount( merchant_connector_account, ) => Some(helpers::create_webhook_url( &state.base_url.clone(), merchant_context.get_merchant_account().get_id(), merchant_connector_account.get_id().get_string_repr(), )), // TODO: Implement for connectors that require a webhook URL to be included in the request payload. domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => None, }; let supported_connector = &state .conf .multiple_api_version_supported_connectors .supported_connectors; let connector_api_version = if supported_connector.contains(&connector_enum) { state .store .find_config_by_key(&format!("connector_api_version_{connector_enum}")) .await .map(|value| value.config) .ok() } else { None }; let browser_info = payment_attempt .browser_info .clone() .map(types::BrowserInformation::from); let connector_refund_id = refund.get_optional_connector_refund_id().cloned(); let capture_method = payment_intent.capture_method; let customer_id = payment_intent .get_optional_customer_id() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get optional customer id")?; let braintree_metadata = payment_intent .connector_metadata .as_ref() .and_then(|cm| cm.braintree.clone()); let merchant_account_id = braintree_metadata .as_ref() .and_then(|braintree| braintree.merchant_account_id.clone()); let merchant_config_currency = braintree_metadata.and_then(|braintree| braintree.merchant_config_currency); let connector_wallets_details = match merchant_connector_account { domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount( merchant_connector_account, ) => merchant_connector_account.get_connector_wallets_details(), domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => None, }; let 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_enum.to_string(), payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), attempt_id: payment_attempt.id.get_string_repr().to_string().clone(), status, payment_method: payment_method_type, payment_method_type: Some(payment_attempt.payment_method_subtype), connector_auth_type: auth_type, description: None, // Does refund need shipping/billing address ? address: PaymentAddress::default(), auth_type: payment_attempt.authentication_type, connector_meta_data: merchant_connector_account.get_metadata(), connector_wallets_details, amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), payment_method_status: None, minor_amount_captured: payment_intent.amount_captured, request: types::RefundsData { refund_id: refund.id.get_string_repr().to_string(), connector_transaction_id: refund.get_connector_transaction_id().clone(), refund_amount: refund.refund_amount.get_amount_as_i64(), minor_refund_amount: refund.refund_amount, currency, payment_amount: payment_amount.get_amount_as_i64(), minor_payment_amount: payment_amount, webhook_url, connector_metadata: payment_attempt.connector_metadata.clone().expose_option(), reason: refund.refund_reason.clone(), connector_refund_id: connector_refund_id.clone(), browser_info, split_refunds: None, integrity_object: None, refund_status: refund.refund_status, merchant_account_id, merchant_config_currency, refund_connector_metadata: refund.metadata.clone(), capture_method: Some(capture_method), additional_payment_method_data: None, }, response: Ok(types::RefundsResponseData { connector_refund_id: connector_refund_id.unwrap_or_default(), refund_status: refund.refund_status, }), access_token: None, session_token: None, reference_id: None, payment_method_token: None, connector_customer: None, recurring_mandate_payment_data: None, preprocessing_id: None, connector_request_reference_id: refund .merchant_reference_id .get_string_repr() .to_string() .clone(), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode: None, payment_method_balance: None, connector_api_version, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: Some(refund.id.get_string_repr().to_string().clone()), dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, }; Ok(router_data) } #[cfg(feature = "v1")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_refund_router_data<'a, F>( state: &'a SessionState, connector_id: &str, merchant_context: &domain::MerchantContext, money: (MinorUnit, enums::Currency), payment_intent: &'a storage::PaymentIntent, payment_attempt: &storage::PaymentAttempt, refund: &'a diesel_refund::Refund, creds_identifier: Option<String>, split_refunds: Option<router_request_types::SplitRefundsRequest>, ) -> RouterResult<types::RefundsRouterData<F>> { let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")?; let merchant_connector_account = helpers::get_merchant_connector_account( state, merchant_context.get_merchant_account().get_id(), creds_identifier.as_deref(), merchant_context.get_merchant_key_store(), profile_id, connector_id, payment_attempt.merchant_connector_id.as_ref(), ) .await?; let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError)?; let status = payment_attempt.status; let (payment_amount, currency) = money; let payment_method = payment_attempt .payment_method .get_required_value("payment_method") .change_context(errors::ApiErrorResponse::InternalServerError)?; let merchant_connector_account_id_or_connector_name = payment_attempt .merchant_connector_id .as_ref() .map(|mca_id| mca_id.get_string_repr()) .unwrap_or(connector_id); let webhook_url = Some(helpers::create_webhook_url( &state.base_url.clone(), merchant_context.get_merchant_account().get_id(), merchant_connector_account_id_or_connector_name, )); let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let supported_connector = &state .conf .multiple_api_version_supported_connectors .supported_connectors; let connector_enum = 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 browser_info: Option<types::BrowserInformation> = payment_attempt .browser_info .clone() .map(|b| b.parse_value("BrowserInformation")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; let connector_refund_id = refund.get_optional_connector_refund_id().cloned(); let capture_method = payment_attempt.capture_method; let braintree_metadata = payment_intent .connector_metadata .clone() .map(|cm| { cm.parse_value::<api_models::payments::ConnectorMetadata>("ConnectorMetadata") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed parsing ConnectorMetadata") }) .transpose()? .and_then(|cm| cm.braintree); let merchant_account_id = braintree_metadata .as_ref() .and_then(|braintree| braintree.merchant_account_id.clone()); let merchant_config_currency = braintree_metadata.and_then(|braintree| braintree.merchant_config_currency); let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> = payment_attempt .payment_method_data .clone() .and_then(|value| match serde_json::from_value(value) { Ok(data) => Some(data), Err(e) => { router_env::logger::error!("Failed to deserialize payment_method_data: {}", e); None } }); let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_context.get_merchant_account().get_id().clone(), customer_id: payment_intent.customer_id.to_owned(), tenant_id: state.tenant.tenant_id.clone(), connector: connector_id.to_string(), payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), attempt_id: payment_attempt.attempt_id.clone(), status, payment_method, payment_method_type: payment_attempt.payment_method_type, connector_auth_type: auth_type, description: None, // Does refund need shipping/billing address ? address: PaymentAddress::default(), auth_type: 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(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), payment_method_status: None, minor_amount_captured: payment_intent.amount_captured, request: types::RefundsData { refund_id: refund.refund_id.clone(), connector_transaction_id: refund.get_connector_transaction_id().clone(), refund_amount: refund.refund_amount.get_amount_as_i64(), minor_refund_amount: refund.refund_amount, currency, payment_amount: payment_amount.get_amount_as_i64(), minor_payment_amount: payment_amount, webhook_url, connector_metadata: payment_attempt.connector_metadata.clone(), refund_connector_metadata: refund.metadata.clone(), reason: refund.refund_reason.clone(), connector_refund_id: connector_refund_id.clone(), browser_info, split_refunds, integrity_object: None, refund_status: refund.refund_status, merchant_account_id, merchant_config_currency, capture_method, additional_payment_method_data, }, response: Ok(types::RefundsResponseData { connector_refund_id: connector_refund_id.unwrap_or_default(), refund_status: refund.refund_status, }), access_token: None, session_token: None, reference_id: None, payment_method_token: None, connector_customer: None, recurring_mandate_payment_data: None, preprocessing_id: None, connector_request_reference_id: refund.refund_id.clone(), #[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: None, frm_metadata: None, refund_id: Some(refund.refund_id.clone()), dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, }; Ok(router_data) } pub fn get_or_generate_id( key: &str, provided_id: &Option<String>, prefix: &str, ) -> Result<String, errors::ApiErrorResponse> { let validate_id = |id| validate_id(id, key); provided_id .clone() .map_or(Ok(generate_id(consts::ID_LENGTH, prefix)), validate_id) } fn invalid_id_format_error(key: &str) -> errors::ApiErrorResponse { errors::ApiErrorResponse::InvalidDataFormat { field_name: key.to_string(), expected_format: format!( "length should be less than {} characters", consts::MAX_ID_LENGTH ), } } pub fn validate_id(id: String, key: &str) -> Result<String, errors::ApiErrorResponse> { if id.len() > consts::MAX_ID_LENGTH { Err(invalid_id_format_error(key)) } else { Ok(id) } } #[cfg(feature = "v1")] pub fn get_split_refunds( split_refund_input: refunds_transformers::SplitRefundInput, ) -> RouterResult<Option<router_request_types::SplitRefundsRequest>> { match split_refund_input.split_payment_request.as_ref() { Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(stripe_payment)) => { let (charge_id_option, charge_type_option) = match ( &split_refund_input.payment_charges, &split_refund_input.split_payment_request, ) { ( Some(common_types::payments::ConnectorChargeResponseData::StripeSplitPayment( stripe_split_payment_response, )), _, ) => ( stripe_split_payment_response.charge_id.clone(), Some(stripe_split_payment_response.charge_type.clone()), ), ( _, Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment( stripe_split_payment_request, )), ) => ( split_refund_input.charge_id, Some(stripe_split_payment_request.charge_type.clone()), ), (_, _) => (None, None), }; if let Some(charge_id) = charge_id_option { let options = refunds_validator::validate_stripe_charge_refund( charge_type_option, &split_refund_input.refund_request, )?; Ok(Some( router_request_types::SplitRefundsRequest::StripeSplitRefund( router_request_types::StripeSplitRefund { charge_id, charge_type: stripe_payment.charge_type.clone(), transfer_account_id: stripe_payment.transfer_account_id.clone(), options, }, ), )) } else { Ok(None) } } Some(common_types::payments::SplitPaymentsRequest::AdyenSplitPayment(_)) => { match &split_refund_input.payment_charges { Some(common_types::payments::ConnectorChargeResponseData::AdyenSplitPayment( adyen_split_payment_response, )) => { if let Some(common_types::refunds::SplitRefund::AdyenSplitRefund( split_refund_request, )) = split_refund_input.refund_request.clone() { refunds_validator::validate_adyen_charge_refund( adyen_split_payment_response, &split_refund_request, )?; Ok(Some( router_request_types::SplitRefundsRequest::AdyenSplitRefund( split_refund_request, ), )) } else { Ok(None) } } _ => Ok(None), } } Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(_)) => { match ( &split_refund_input.payment_charges, &split_refund_input.refund_request, ) { ( Some(common_types::payments::ConnectorChargeResponseData::XenditSplitPayment( xendit_split_payment_response, )), Some(common_types::refunds::SplitRefund::XenditSplitRefund( split_refund_request, )), ) => { let user_id = refunds_validator::validate_xendit_charge_refund( xendit_split_payment_response, split_refund_request, )?; Ok(user_id.map(|for_user_id| { router_request_types::SplitRefundsRequest::XenditSplitRefund( common_types::domain::XenditSplitSubMerchantData { for_user_id }, ) })) } ( Some(common_types::payments::ConnectorChargeResponseData::XenditSplitPayment( xendit_split_payment_response, )), None, ) => { let option_for_user_id = match xendit_split_payment_response { common_types::payments::XenditChargeResponseData::MultipleSplits( common_types::payments::XenditMultipleSplitResponse { for_user_id, .. }, ) => for_user_id.clone(), common_types::payments::XenditChargeResponseData::SingleSplit( common_types::domain::XenditSplitSubMerchantData { for_user_id }, ) => Some(for_user_id.clone()), }; if option_for_user_id.is_some() { Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "split_refunds.xendit_split_refund.for_user_id", })? } else { Ok(None) } } _ => Ok(None), } } _ => Ok(None), } } #[cfg(test)] mod tests { #![allow(clippy::expect_used)] use super::*; #[test] fn validate_id_length_constraint() { let payment_id = "abcdefghijlkmnopqrstuvwzyzabcdefghijknlmnopsjkdnfjsknfkjsdnfspoig".to_string(); //length = 65 let result = validate_id(payment_id, "payment_id"); assert!(result.is_err()); } #[test] fn validate_id_proper_response() { let payment_id = "abcdefghijlkmnopqrstjhbjhjhkhbhgcxdfxvmhb".to_string(); let result = validate_id(payment_id.clone(), "payment_id"); assert!(result.is_ok()); let result = result.unwrap_or_default(); assert_eq!(result, payment_id); } #[test] fn test_generate_id() { let generated_id = generate_id(consts::ID_LENGTH, "ref"); assert_eq!(generated_id.len(), consts::ID_LENGTH + 4) } #[test] fn test_filter_objects_based_on_profile_id_list() { #[derive(PartialEq, Debug, Clone)] struct Object { profile_id: Option<common_utils::id_type::ProfileId>, } impl Object { pub fn new(profile_id: &'static str) -> Self { Self { profile_id: Some( common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from( profile_id, )) .expect("invalid profile ID"), ), } } } impl GetProfileId for Object { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { self.profile_id.as_ref() } } fn new_profile_id(profile_id: &'static str) -> common_utils::id_type::ProfileId { common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from(profile_id)) .expect("invalid profile ID") } // non empty object_list and profile_id_list let object_list = vec![ Object::new("p1"), Object::new("p2"), Object::new("p2"), Object::new("p4"), Object::new("p5"), ]; let profile_id_list = vec![ new_profile_id("p1"), new_profile_id("p2"), new_profile_id("p3"), ]; let filtered_list = filter_objects_based_on_profile_id_list(Some(profile_id_list), object_list.clone()); let expected_result = vec![Object::new("p1"), Object::new("p2"), Object::new("p2")]; assert_eq!(filtered_list, expected_result); // non empty object_list and empty profile_id_list let empty_profile_id_list = vec![]; let filtered_list = filter_objects_based_on_profile_id_list( Some(empty_profile_id_list), object_list.clone(), ); let expected_result = vec![]; assert_eq!(filtered_list, expected_result); // non empty object_list and None profile_id_list let profile_id_list_as_none = None; let filtered_list = filter_objects_based_on_profile_id_list(profile_id_list_as_none, object_list); let expected_result = vec![ Object::new("p1"), Object::new("p2"), Object::new("p2"), Object::new("p4"), Object::new("p5"), ]; assert_eq!(filtered_list, expected_result); } } // Dispute Stage can move linearly from PreDispute -> Dispute -> PreArbitration -> Arbitration -> DisputeReversal pub fn validate_dispute_stage( prev_dispute_stage: DisputeStage, dispute_stage: DisputeStage, ) -> bool { match prev_dispute_stage { DisputeStage::PreDispute => true, DisputeStage::Dispute => !matches!(dispute_stage, DisputeStage::PreDispute), DisputeStage::PreArbitration => matches!( dispute_stage, DisputeStage::PreArbitration | DisputeStage::Arbitration | DisputeStage::DisputeReversal ), DisputeStage::Arbitration => matches!( dispute_stage, DisputeStage::Arbitration | DisputeStage::DisputeReversal ), DisputeStage::DisputeReversal => matches!(dispute_stage, DisputeStage::DisputeReversal), } } //Dispute status can go from Opened -> (Expired | Accepted | Cancelled | Challenged -> (Won | Lost)) pub fn validate_dispute_status( prev_dispute_status: DisputeStatus, dispute_status: DisputeStatus, ) -> bool { match prev_dispute_status { DisputeStatus::DisputeOpened => true, DisputeStatus::DisputeExpired => { matches!(dispute_status, DisputeStatus::DisputeExpired) } DisputeStatus::DisputeAccepted => { matches!(dispute_status, DisputeStatus::DisputeAccepted) } DisputeStatus::DisputeCancelled => { matches!(dispute_status, DisputeStatus::DisputeCancelled) } DisputeStatus::DisputeChallenged => matches!( dispute_status, DisputeStatus::DisputeChallenged | DisputeStatus::DisputeWon | DisputeStatus::DisputeLost | DisputeStatus::DisputeAccepted | DisputeStatus::DisputeCancelled | DisputeStatus::DisputeExpired ), DisputeStatus::DisputeWon => matches!(dispute_status, DisputeStatus::DisputeWon), DisputeStatus::DisputeLost => matches!(dispute_status, DisputeStatus::DisputeLost), } } pub fn validate_dispute_stage_and_dispute_status( prev_dispute_stage: DisputeStage, prev_dispute_status: DisputeStatus, dispute_stage: DisputeStage, dispute_status: DisputeStatus, ) -> CustomResult<(), errors::WebhooksFlowError> { let dispute_stage_validation = validate_dispute_stage(prev_dispute_stage, dispute_stage); let dispute_status_validation = if dispute_stage == prev_dispute_stage { validate_dispute_status(prev_dispute_status, dispute_status) } else { true }; common_utils::fp_utils::when( !(dispute_stage_validation && dispute_status_validation), || { super::metrics::INCOMING_DISPUTE_WEBHOOK_VALIDATION_FAILURE_METRIC.add(1, &[]); Err(errors::WebhooksFlowError::DisputeWebhookValidationFailed)? }, ) } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn construct_accept_dispute_router_data<'a>( state: &'a SessionState, payment_intent: &'a storage::PaymentIntent, payment_attempt: &storage::PaymentAttempt, merchant_context: &domain::MerchantContext, dispute: &storage::Dispute, ) -> RouterResult<types::AcceptDisputeRouterData> { let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")? .clone(); let merchant_connector_account = helpers::get_merchant_connector_account( state, merchant_context.get_merchant_account().get_id(), None, merchant_context.get_merchant_key_store(), &profile_id, &dispute.connector, payment_attempt.merchant_connector_id.as_ref(), ) .await?; let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError)?; let payment_method = payment_attempt .payment_method .get_required_value("payment_method")?; let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_context.get_merchant_account().get_id().clone(), connector: dispute.connector.to_string(), tenant_id: state.tenant.tenant_id.clone(), payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), attempt_id: payment_attempt.attempt_id.clone(), status: payment_attempt.status, payment_method, payment_method_type: payment_attempt.payment_method_type, connector_auth_type: auth_type, description: None, address: PaymentAddress::default(), auth_type: 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(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), minor_amount_captured: payment_intent.amount_captured, payment_method_status: None, request: types::AcceptDisputeRequestData { dispute_id: dispute.dispute_id.clone(), connector_dispute_id: dispute.connector_dispute_id.clone(), dispute_status: dispute.dispute_status, }, response: Err(ErrorResponse::default()), access_token: None, session_token: None, reference_id: None, payment_method_token: None, connector_customer: None, customer_id: None, recurring_mandate_payment_data: None, preprocessing_id: None, connector_request_reference_id: get_connector_request_reference_id( &state.conf, merchant_context.get_merchant_account().get_id(), payment_intent, payment_attempt, &dispute.connector, )?, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode, payment_method_balance: None, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, dispute_id: Some(dispute.dispute_id.clone()), refund_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, }; Ok(router_data) } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn construct_submit_evidence_router_data<'a>( state: &'a SessionState, payment_intent: &'a storage::PaymentIntent, payment_attempt: &storage::PaymentAttempt, merchant_context: &domain::MerchantContext, dispute: &storage::Dispute, submit_evidence_request_data: types::SubmitEvidenceRequestData, ) -> RouterResult<types::SubmitEvidenceRouterData> { let connector_id = &dispute.connector; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")? .clone(); let merchant_connector_account = helpers::get_merchant_connector_account( state, merchant_context.get_merchant_account().get_id(), None, merchant_context.get_merchant_key_store(), &profile_id, connector_id, payment_attempt.merchant_connector_id.as_ref(), ) .await?; let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError)?; let payment_method = payment_attempt .payment_method .get_required_value("payment_method_type")?; let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_context.get_merchant_account().get_id().clone(), connector: connector_id.to_string(), payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), tenant_id: state.tenant.tenant_id.clone(), attempt_id: payment_attempt.attempt_id.clone(), status: payment_attempt.status, payment_method, payment_method_type: payment_attempt.payment_method_type, connector_auth_type: auth_type, description: None, address: PaymentAddress::default(), auth_type: 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(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), minor_amount_captured: payment_intent.amount_captured, request: submit_evidence_request_data, response: Err(ErrorResponse::default()), access_token: None, session_token: None, reference_id: None, payment_method_token: None, connector_customer: None, customer_id: None, recurring_mandate_payment_data: None, preprocessing_id: None, payment_method_balance: None, payment_method_status: None, connector_request_reference_id: get_connector_request_reference_id( &state.conf, merchant_context.get_merchant_account().get_id(), payment_intent, payment_attempt, connector_id, )?, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: Some(dispute.dispute_id.clone()), connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, }; Ok(router_data) } #[cfg(feature = "v1")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_upload_file_router_data<'a>( state: &'a SessionState, payment_intent: &'a storage::PaymentIntent, payment_attempt: &storage::PaymentAttempt, merchant_context: &domain::MerchantContext, create_file_request: &api::CreateFileRequest, dispute_data: storage::Dispute, connector_id: &str, file_key: String, ) -> RouterResult<types::UploadFileRouterData> { let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")? .clone(); let merchant_connector_account = helpers::get_merchant_connector_account( state, merchant_context.get_merchant_account().get_id(), None, merchant_context.get_merchant_key_store(), &profile_id, connector_id, payment_attempt.merchant_connector_id.as_ref(), ) .await?; let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError)?; let payment_method = payment_attempt .payment_method .get_required_value("payment_method_type")?; let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_context.get_merchant_account().get_id().clone(), connector: connector_id.to_string(), payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), tenant_id: state.tenant.tenant_id.clone(), attempt_id: payment_attempt.attempt_id.clone(), status: payment_attempt.status, payment_method, payment_method_type: payment_attempt.payment_method_type, connector_auth_type: auth_type, description: None, address: PaymentAddress::default(), auth_type: 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(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), minor_amount_captured: payment_intent.amount_captured, payment_method_status: None, request: types::UploadFileRequestData { file_key, file: create_file_request.file.clone(), file_type: create_file_request.file_type.clone(), file_size: create_file_request.file_size, dispute_id: dispute_data.dispute_id.clone(), connector_dispute_id: dispute_data.connector_dispute_id.clone(), }, response: Err(ErrorResponse::default()), access_token: None, session_token: None, reference_id: None, payment_method_token: None, connector_customer: None, customer_id: None, recurring_mandate_payment_data: None, preprocessing_id: None, payment_method_balance: None, connector_request_reference_id: get_connector_request_reference_id( &state.conf, merchant_context.get_merchant_account().get_id(), payment_intent, payment_attempt, connector_id, )?, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, }; Ok(router_data) } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn construct_dispute_list_router_data<'a>( state: &'a SessionState, merchant_connector_account: MerchantConnectorAccount, req: types::FetchDisputesRequestData, ) -> RouterResult<types::FetchDisputesRouterData> { let merchant_id = merchant_connector_account.merchant_id.clone(); let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: "ConnectorAuthType".to_string(), })?; Ok(types::RouterData { flow: PhantomData, merchant_id, customer_id: None, connector_customer: None, connector: merchant_connector_account.connector_name.clone(), payment_id: consts::IRRELEVANT_PAYMENT_INTENT_ID.to_owned(), tenant_id: state.tenant.tenant_id.clone(), attempt_id: consts::IRRELEVANT_PAYMENT_ATTEMPT_ID.to_owned(), status: common_enums::AttemptStatus::default(), payment_method: common_enums::PaymentMethod::default(), payment_method_type: None, connector_auth_type: auth_type, description: None, address: PaymentAddress::default(), auth_type: common_enums::AuthenticationType::default(), connector_meta_data: merchant_connector_account.get_metadata().clone(), connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: None, minor_amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_token: None, recurring_mandate_payment_data: None, preprocessing_id: None, payment_method_balance: None, connector_api_version: None, request: req, response: Err(ErrorResponse::default()), //TODO connector_request_reference_id: "IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_AUTHENTICATION_FLOW".to_owned(), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, dispute_id: None, refund_id: None, payment_method_status: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, }) } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn construct_dispute_sync_router_data<'a>( state: &'a SessionState, payment_intent: &'a storage::PaymentIntent, payment_attempt: &storage::PaymentAttempt, merchant_context: &domain::MerchantContext, dispute: &storage::Dispute, ) -> RouterResult<types::DisputeSyncRouterData> { let _db = &*state.store; let connector_id = &dispute.connector; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")? .clone(); let merchant_connector_account = helpers::get_merchant_connector_account( state, merchant_context.get_merchant_account().get_id(), None, merchant_context.get_merchant_key_store(), &profile_id, connector_id, payment_attempt.merchant_connector_id.as_ref(), ) .await?; let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError)?; let payment_method = payment_attempt .payment_method .get_required_value("payment_method")?; let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_context.get_merchant_account().get_id().clone(), connector: connector_id.to_string(), payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), tenant_id: state.tenant.tenant_id.clone(), attempt_id: payment_attempt.attempt_id.clone(), status: payment_attempt.status, payment_method, payment_method_type: payment_attempt.payment_method_type, connector_auth_type: auth_type, description: None, address: PaymentAddress::default(), auth_type: 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(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), minor_amount_captured: payment_intent.amount_captured, payment_method_status: None, request: types::DisputeSyncData { dispute_id: dispute.dispute_id.clone(), connector_dispute_id: dispute.connector_dispute_id.clone(), }, response: Err(ErrorResponse::get_not_implemented()), access_token: None, session_token: None, reference_id: None, payment_method_token: None, customer_id: None, connector_customer: None, recurring_mandate_payment_data: None, preprocessing_id: None, payment_method_balance: None, connector_request_reference_id: get_connector_request_reference_id( &state.conf, merchant_context.get_merchant_account().get_id(), payment_intent, payment_attempt, connector_id, )?, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: Some(dispute.dispute_id.clone()), connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, }; Ok(router_data) } #[cfg(feature = "v2")] pub async fn construct_payments_dynamic_tax_calculation_router_data<F: Clone>( state: &SessionState, merchant_context: &domain::MerchantContext, payment_data: &mut PaymentData<F>, merchant_connector_account: &MerchantConnectorAccount, ) -> RouterResult<types::PaymentsTaxCalculationRouterData> { todo!() } #[cfg(feature = "v1")] pub async fn construct_payments_dynamic_tax_calculation_router_data<F: Clone>( state: &SessionState, merchant_context: &domain::MerchantContext, payment_data: &mut PaymentData<F>, merchant_connector_account: &MerchantConnectorAccount, ) -> RouterResult<types::PaymentsTaxCalculationRouterData> { let payment_intent = &payment_data.payment_intent.clone(); let payment_attempt = &payment_data.payment_attempt.clone(); #[cfg(feature = "v1")] let test_mode: Option<bool> = merchant_connector_account.test_mode; #[cfg(feature = "v2")] let test_mode = None; let connector_auth_type: types::ConnectorAuthType = merchant_connector_account .connector_account_details .clone() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; let shipping_address = payment_data .tax_data .clone() .map(|tax_data| tax_data.shipping_details) .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Missing shipping_details")?; let order_details: Option<Vec<OrderDetailsWithAmount>> = payment_intent .order_details .clone() .map(|order_details| { order_details .iter() .map(|data| { data.to_owned() .parse_value("OrderDetailsWithAmount") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "OrderDetailsWithAmount", }) .attach_printable("Unable to parse OrderDetailsWithAmount") }) .collect::<Result<Vec<_>, _>>() }) .transpose()?; let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), customer_id: None, connector_customer: None, connector: merchant_connector_account.connector_name.clone(), payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), attempt_id: payment_attempt.attempt_id.clone(), tenant_id: state.tenant.tenant_id.clone(), status: payment_attempt.status, payment_method: diesel_models::enums::PaymentMethod::default(), payment_method_type: payment_attempt.payment_method_type, connector_auth_type, description: None, address: payment_data.address.clone(), auth_type: payment_attempt.authentication_type.unwrap_or_default(), connector_meta_data: None, connector_wallets_details: None, amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_token: None, recurring_mandate_payment_data: None, preprocessing_id: None, payment_method_balance: None, connector_api_version: None, request: types::PaymentsTaxCalculationData { amount: payment_intent.amount, shipping_cost: payment_intent.shipping_cost, order_details, currency: payment_data.currency, shipping_address, }, response: Err(ErrorResponse::default()), connector_request_reference_id: get_connector_request_reference_id( &state.conf, merchant_context.get_merchant_account().get_id(), payment_intent, payment_attempt, &merchant_connector_account.connector_name, )?, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, payment_method_status: None, minor_amount_captured: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, }; Ok(router_data) } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn construct_defend_dispute_router_data<'a>( state: &'a SessionState, payment_intent: &'a storage::PaymentIntent, payment_attempt: &storage::PaymentAttempt, merchant_context: &domain::MerchantContext, dispute: &storage::Dispute, ) -> RouterResult<types::DefendDisputeRouterData> { let _db = &*state.store; let connector_id = &dispute.connector; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")? .clone(); let merchant_connector_account = helpers::get_merchant_connector_account( state, merchant_context.get_merchant_account().get_id(), None, merchant_context.get_merchant_key_store(), &profile_id, connector_id, payment_attempt.merchant_connector_id.as_ref(), ) .await?; let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError)?; let payment_method = payment_attempt .payment_method .get_required_value("payment_method_type")?; let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_context.get_merchant_account().get_id().clone(), connector: connector_id.to_string(), payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), tenant_id: state.tenant.tenant_id.clone(), attempt_id: payment_attempt.attempt_id.clone(), status: payment_attempt.status, payment_method, payment_method_type: payment_attempt.payment_method_type, connector_auth_type: auth_type, description: None, address: PaymentAddress::default(), auth_type: 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(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), minor_amount_captured: payment_intent.amount_captured, payment_method_status: None, request: types::DefendDisputeRequestData { dispute_id: dispute.dispute_id.clone(), connector_dispute_id: dispute.connector_dispute_id.clone(), }, response: Err(ErrorResponse::get_not_implemented()), access_token: None, session_token: None, reference_id: None, payment_method_token: None, customer_id: None, connector_customer: None, recurring_mandate_payment_data: None, preprocessing_id: None, payment_method_balance: None, connector_request_reference_id: get_connector_request_reference_id( &state.conf, merchant_context.get_merchant_account().get_id(), payment_intent, payment_attempt, connector_id, )?, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: Some(dispute.dispute_id.clone()), connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, }; Ok(router_data) } #[instrument(skip_all)] pub async fn construct_retrieve_file_router_data<'a>( state: &'a SessionState, merchant_context: &domain::MerchantContext, file_metadata: &diesel_models::file::FileMetadata, dispute: Option<storage::Dispute>, connector_id: &str, ) -> RouterResult<types::RetrieveFileRouterData> { let profile_id = file_metadata .profile_id .as_ref() .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "profile_id", }) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in file_metadata")?; let merchant_connector_account = helpers::get_merchant_connector_account( state, merchant_context.get_merchant_account().get_id(), None, merchant_context.get_merchant_key_store(), profile_id, connector_id, file_metadata.merchant_connector_id.as_ref(), ) .await?; let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError)?; let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_context.get_merchant_account().get_id().clone(), connector: connector_id.to_string(), tenant_id: state.tenant.tenant_id.clone(), customer_id: None, connector_customer: None, payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("dispute") .get_string_repr() .to_owned(), attempt_id: IRRELEVANT_ATTEMPT_ID_IN_DISPUTE_FLOW.to_string(), status: diesel_models::enums::AttemptStatus::default(), payment_method: diesel_models::enums::PaymentMethod::default(), payment_method_type: None, connector_auth_type: auth_type, description: None, address: PaymentAddress::default(), auth_type: diesel_models::enums::AuthenticationType::default(), connector_meta_data: merchant_connector_account.get_metadata(), connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: None, minor_amount_captured: None, payment_method_status: None, request: types::RetrieveFileRequestData { provider_file_id: file_metadata .provider_file_id .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Missing provider file id")?, connector_dispute_id: dispute.map(|dispute_data| dispute_data.connector_dispute_id), }, response: Err(ErrorResponse::default()), access_token: None, session_token: None, reference_id: None, payment_method_token: None, recurring_mandate_payment_data: None, preprocessing_id: None, payment_method_balance: None, connector_request_reference_id: IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_DISPUTE_FLOW .to_string(), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, }; Ok(router_data) } pub fn is_merchant_enabled_for_payment_id_as_connector_request_id( conf: &Settings, merchant_id: &common_utils::id_type::MerchantId, ) -> bool { let config_map = &conf .connector_request_reference_id_config .merchant_ids_send_payment_id_as_connector_request_id; config_map.contains(merchant_id) } #[cfg(feature = "v1")] pub fn get_connector_request_reference_id( conf: &Settings, merchant_id: &common_utils::id_type::MerchantId, payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, connector_name: &str, ) -> CustomResult<String, errors::ApiErrorResponse> { let is_config_enabled_to_send_payment_id_as_connector_request_id = is_merchant_enabled_for_payment_id_as_connector_request_id(conf, merchant_id); let connector_data = api::ConnectorData::get_connector_by_name( &conf.connectors, connector_name, api::GetToken::Connector, payment_attempt.merchant_connector_id.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| "Failed to construct connector data")?; let connector_request_reference_id = connector_data .connector .generate_connector_request_reference_id( payment_intent, payment_attempt, is_config_enabled_to_send_payment_id_as_connector_request_id, ); Ok(connector_request_reference_id) } // TODO: Based on the connector configuration, the connector_request_reference_id should be generated #[cfg(feature = "v2")] pub fn get_connector_request_reference_id( conf: &Settings, merchant_id: &common_utils::id_type::MerchantId, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> String { todo!() } /// Validate whether the profile_id exists and is associated with the merchant_id pub async fn validate_and_get_business_profile( db: &dyn StorageInterface, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_id: Option<&common_utils::id_type::ProfileId>, merchant_id: &common_utils::id_type::MerchantId, ) -> RouterResult<Option<domain::Profile>> { profile_id .async_map(|profile_id| async { db.find_business_profile_by_merchant_id_profile_id( key_manager_state, merchant_key_store, merchant_id, profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), }) }) .await .transpose() } fn connector_needs_business_sub_label(connector_name: &str) -> bool { let connectors_list = [Connector::Cybersource]; connectors_list .map(|connector| connector.to_string()) .contains(&connector_name.to_string()) } /// Create the connector label /// {connector_name}_{country}_{business_label} pub fn get_connector_label( business_country: Option<api_models::enums::CountryAlpha2>, business_label: Option<&String>, business_sub_label: Option<&String>, connector_name: &str, ) -> Option<String> { business_country .zip(business_label) .map(|(business_country, business_label)| { let mut connector_label = format!("{connector_name}_{business_country}_{business_label}"); // Business sub label is currently being used only for cybersource // To ensure backwards compatibality, cybersource mca's created before this change // will have the business_sub_label value as default. // // Even when creating the connector account, if no sub label is provided, default will be used if connector_needs_business_sub_label(connector_name) { if let Some(sub_label) = business_sub_label { connector_label.push_str(&format!("_{sub_label}")); } else { connector_label.push_str("_default"); // For backwards compatibality } } connector_label }) } #[cfg(feature = "v1")] /// If profile_id is not passed, use default profile if available, or /// If business_details (business_country and business_label) are passed, get the business_profile /// or return a `MissingRequiredField` error #[allow(clippy::too_many_arguments)] pub async fn get_profile_id_from_business_details( key_manager_state: &KeyManagerState, business_country: Option<api_models::enums::CountryAlpha2>, business_label: Option<&String>, merchant_context: &domain::MerchantContext, request_profile_id: Option<&common_utils::id_type::ProfileId>, db: &dyn StorageInterface, should_validate: bool, ) -> RouterResult<common_utils::id_type::ProfileId> { match request_profile_id.or(merchant_context .get_merchant_account() .default_profile .as_ref()) { Some(profile_id) => { // Check whether this business profile belongs to the merchant if should_validate { let _ = 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?; } Ok(profile_id.clone()) } None => match business_country.zip(business_label) { Some((business_country, business_label)) => { let profile_name = format!("{business_country}_{business_label}"); let business_profile = db .find_business_profile_by_profile_name_merchant_id( key_manager_state, merchant_context.get_merchant_key_store(), &profile_name, merchant_context.get_merchant_account().get_id(), ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_name, })?; Ok(business_profile.get_id().to_owned()) } _ => Err(report!(errors::ApiErrorResponse::MissingRequiredField { field_name: "profile_id or business_country, business_label" })), }, } } pub fn get_poll_id(merchant_id: &common_utils::id_type::MerchantId, unique_id: String) -> String { merchant_id.get_poll_id(&unique_id) } pub fn get_external_authentication_request_poll_id( payment_id: &common_utils::id_type::PaymentId, ) -> String { payment_id.get_external_authentication_request_poll_id() } pub fn get_modular_authentication_request_poll_id( authentication_id: &common_utils::id_type::AuthenticationId, ) -> String { authentication_id.get_external_authentication_request_poll_id() } pub fn get_html_redirect_response_popup( return_url_with_query_params: String, ) -> RouterResult<String> { Ok(html! { head { title { "Redirect Form" } (PreEscaped(format!(r#" <script> let return_url = "{return_url_with_query_params}"; try {{ // if inside iframe, send post message to parent for redirection if (window.self !== window.parent) {{ window.parent.postMessage({{openurl_if_required: return_url}}, '*') // if parent, redirect self to return_url }} else {{ window.location.href = return_url }} }} catch(err) {{ // if error occurs, send post message to parent and wait for 10 secs to redirect. if doesn't redirect, redirect self to return_url window.parent.postMessage({{openurl_if_required: return_url}}, '*') setTimeout(function() {{ window.location.href = return_url }}, 10000); console.log(err.message) }} </script> "#))) } } .into_string()) } #[cfg(feature = "v1")] pub fn get_html_redirect_response_for_external_authentication( return_url_with_query_params: String, payment_response: &api_models::payments::PaymentsResponse, payment_id: common_utils::id_type::PaymentId, poll_config: &PollConfig, ) -> RouterResult<String> { // if intent_status is requires_customer_action then set poll_id, fetch poll config and do a poll_status post message, else do open_url post message to redirect to return_url let html = match payment_response.status { IntentStatus::RequiresCustomerAction => { // Request poll id sent to client for retrieve_poll_status api let req_poll_id = get_external_authentication_request_poll_id(&payment_id); let poll_frequency = poll_config.frequency; let poll_delay_in_secs = poll_config.delay_in_secs; html! { head { title { "Redirect Form" } (PreEscaped(format!(r#" <script> let return_url = "{return_url_with_query_params}"; let poll_status_data = {{ 'poll_id': '{req_poll_id}', 'frequency': '{poll_frequency}', 'delay_in_secs': '{poll_delay_in_secs}', 'return_url_with_query_params': return_url }}; try {{ // if inside iframe, send post message to parent for redirection if (window.self !== window.parent) {{ window.parent.postMessage({{poll_status: poll_status_data}}, '*') // if parent, redirect self to return_url }} else {{ window.location.href = return_url }} }} catch(err) {{ // if error occurs, send post message to parent and wait for 10 secs to redirect. if doesn't redirect, redirect self to return_url window.parent.postMessage({{poll_status: poll_status_data}}, '*') setTimeout(function() {{ window.location.href = return_url }}, 10000); console.log(err.message) }} </script> "#))) } } .into_string() }, _ => { html! { head { title { "Redirect Form" } (PreEscaped(format!(r#" <script> let return_url = "{return_url_with_query_params}"; try {{ // if inside iframe, send post message to parent for redirection if (window.self !== window.parent) {{ window.parent.postMessage({{openurl_if_required: return_url}}, '*') // if parent, redirect self to return_url }} else {{ window.location.href = return_url }} }} catch(err) {{ // if error occurs, send post message to parent and wait for 10 secs to redirect. if doesn't redirect, redirect self to return_url window.parent.postMessage({{openurl_if_required: return_url}}, '*') setTimeout(function() {{ window.location.href = return_url }}, 10000); console.log(err.message) }} </script> "#))) } } .into_string() }, }; Ok(html) } #[cfg(feature = "v1")] pub fn get_html_redirect_response_for_external_modular_authentication( return_url_with_query_params: String, authentication_response: &api_models::authentication::AuthenticationResponse, authentication_id: common_utils::id_type::AuthenticationId, poll_config: &PollConfig, ) -> RouterResult<String> { // if authentication_status is pending then set poll_id, fetch poll config and do a poll_status post message, else do open_url post message to redirect to return_url let html = match authentication_response.status { common_enums::AuthenticationStatus::Pending => { // Request poll id sent to client for retrieve_poll_status api let req_poll_id = get_modular_authentication_request_poll_id(&authentication_id); let poll_frequency = poll_config.frequency; let poll_delay_in_secs = poll_config.delay_in_secs; html! { head { title { "Redirect Form" } (PreEscaped(format!(r#" <script> let return_url = "{return_url_with_query_params}"; let poll_status_data = {{ 'poll_id': '{req_poll_id}', 'frequency': '{poll_frequency}', 'delay_in_secs': '{poll_delay_in_secs}', 'return_url_with_query_params': return_url }}; try {{ // if inside iframe, send post message to parent for redirection if (window.self !== window.parent) {{ window.parent.postMessage({{poll_status: poll_status_data}}, '*') // if parent, redirect self to return_url }} else {{ window.location.href = return_url }} }} catch(err) {{ // if error occurs, send post message to parent and wait for 10 secs to redirect. if doesn't redirect, redirect self to return_url window.parent.postMessage({{poll_status: poll_status_data}}, '*') setTimeout(function() {{ window.location.href = return_url }}, 10000); console.log(err.message) }} </script> "#))) } } .into_string() }, _ => { html! { head { title { "Redirect Form" } (PreEscaped(format!(r#" <script> let return_url = "{return_url_with_query_params}"; try {{ // if inside iframe, send post message to parent for redirection if (window.self !== window.parent) {{ window.parent.postMessage({{openurl_if_required: return_url}}, '*') // if parent, redirect self to return_url }} else {{ window.location.href = return_url }} }} catch(err) {{ // if error occurs, send post message to parent and wait for 10 secs to redirect. if doesn't redirect, redirect self to return_url window.parent.postMessage({{openurl_if_required: return_url}}, '*') setTimeout(function() {{ window.location.href = return_url }}, 10000); console.log(err.message) }} </script> "#))) } } .into_string() }, }; Ok(html) } #[inline] pub fn get_flow_name<F>() -> RouterResult<String> { Ok(std::any::type_name::<F>() .to_string() .rsplit("::") .next() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Flow stringify failed")? .to_string()) } pub fn get_request_incremental_authorization_value( request_incremental_authorization: Option<bool>, capture_method: Option<common_enums::CaptureMethod>, ) -> RouterResult<Option<RequestIncrementalAuthorization>> { Some(request_incremental_authorization .map(|request_incremental_authorization| { if request_incremental_authorization { if matches!( capture_method, Some(common_enums::CaptureMethod::Automatic) | Some(common_enums::CaptureMethod::SequentialAutomatic) ) { Err(errors::ApiErrorResponse::NotSupported { message: "incremental authorization is not supported when capture_method is automatic".to_owned() })? } Ok(RequestIncrementalAuthorization::True) } else { Ok(RequestIncrementalAuthorization::False) } }) .unwrap_or(Ok(RequestIncrementalAuthorization::default()))).transpose() } pub fn get_incremental_authorization_allowed_value( incremental_authorization_allowed: Option<bool>, request_incremental_authorization: Option<RequestIncrementalAuthorization>, ) -> Option<bool> { if request_incremental_authorization == Some(RequestIncrementalAuthorization::False) { Some(false) } else { incremental_authorization_allowed } } pub(crate) trait GetProfileId { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId>; } impl GetProfileId for MerchantConnectorAccount { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { Some(&self.profile_id) } } impl GetProfileId for storage::PaymentIntent { #[cfg(feature = "v1")] fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { self.profile_id.as_ref() } // TODO: handle this in a better way for v2 #[cfg(feature = "v2")] fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { Some(&self.profile_id) } } impl<A> GetProfileId for (storage::PaymentIntent, A) { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { self.0.get_profile_id() } } impl GetProfileId for diesel_models::Dispute { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { self.profile_id.as_ref() } } impl GetProfileId for diesel_models::Refund { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { self.profile_id.as_ref() } } #[cfg(feature = "v1")] impl GetProfileId for api_models::routing::RoutingConfigRequest { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { self.profile_id.as_ref() } } #[cfg(feature = "v2")] impl GetProfileId for api_models::routing::RoutingConfigRequest { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { Some(&self.profile_id) } } impl GetProfileId for api_models::routing::RoutingRetrieveLinkQuery { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { self.profile_id.as_ref() } } impl GetProfileId for diesel_models::routing_algorithm::RoutingProfileMetadata { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { Some(&self.profile_id) } } impl GetProfileId for domain::Profile { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { Some(self.get_id()) } } #[cfg(feature = "payouts")] impl GetProfileId for storage::Payouts { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { Some(&self.profile_id) } } #[cfg(feature = "payouts")] impl<T, F, R> GetProfileId for (storage::Payouts, T, F, R) { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { self.0.get_profile_id() } } /// Filter Objects based on profile ids pub(super) fn filter_objects_based_on_profile_id_list< T: GetProfileId, U: IntoIterator<Item = T> + FromIterator<T>, >( profile_id_list_auth_layer: Option<Vec<common_utils::id_type::ProfileId>>, object_list: U, ) -> U { if let Some(profile_id_list) = profile_id_list_auth_layer { let profile_ids_to_filter: HashSet<_> = profile_id_list.iter().collect(); object_list .into_iter() .filter_map(|item| { if item .get_profile_id() .is_some_and(|profile_id| profile_ids_to_filter.contains(profile_id)) { Some(item) } else { None } }) .collect() } else { object_list } } pub(crate) fn validate_profile_id_from_auth_layer<T: GetProfileId + std::fmt::Debug>( profile_id_auth_layer: Option<common_utils::id_type::ProfileId>, object: &T, ) -> RouterResult<()> { match (profile_id_auth_layer, object.get_profile_id()) { (Some(auth_profile_id), Some(object_profile_id)) => { auth_profile_id.eq(object_profile_id).then_some(()).ok_or( errors::ApiErrorResponse::PreconditionFailed { message: "Profile id authentication failed. Please use the correct JWT token" .to_string(), } .into(), ) } (Some(_auth_profile_id), None) => RouterResult::Err( errors::ApiErrorResponse::PreconditionFailed { message: "Couldn't find profile_id in record for authentication".to_string(), } .into(), ) .attach_printable(format!("Couldn't find profile_id in entity {object:?}")), (None, None) | (None, Some(_)) => Ok(()), } } pub async fn construct_vault_router_data<F>( state: &SessionState, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_account: &MerchantConnectorAccount, payment_method_vaulting_data: Option< hyperswitch_domain_models::vault::PaymentMethodVaultingData, >, connector_vault_id: Option<String>, connector_customer_id: Option<String>, ) -> RouterResult<VaultRouterDataV2<F>> { let connector_auth_type = merchant_connector_account .get_connector_account_details() .change_context(errors::ApiErrorResponse::InternalServerError)?; let resource_common_data = VaultConnectorFlowData { merchant_id: merchant_id.to_owned(), }; let router_data = types::RouterDataV2 { flow: PhantomData, resource_common_data, tenant_id: state.tenant.tenant_id.clone(), connector_auth_type, request: types::VaultRequestData { payment_method_vaulting_data, connector_vault_id, connector_customer_id, }, response: Ok(types::VaultResponseData::default()), }; Ok(router_data) } pub fn validate_bank_account_data(data: &types::MerchantAccountData) -> RouterResult<()> { match data { types::MerchantAccountData::Iban { iban, .. } => validate_iban(iban), types::MerchantAccountData::Sepa { iban, .. } => validate_iban(iban), types::MerchantAccountData::SepaInstant { iban, .. } => validate_iban(iban), types::MerchantAccountData::Bacs { account_number, sort_code, .. } => validate_uk_account(account_number, sort_code), types::MerchantAccountData::FasterPayments { account_number, sort_code, .. } => validate_uk_account(account_number, sort_code), types::MerchantAccountData::Elixir { iban, .. } => validate_elixir_account(iban), types::MerchantAccountData::Bankgiro { number, .. } => validate_bankgiro_number(number), types::MerchantAccountData::Plusgiro { number, .. } => validate_plusgiro_number(number), } } fn validate_iban(iban: &Secret<String>) -> RouterResult<()> { let iban_str = iban.peek(); if iban_str.len() > consts::IBAN_MAX_LENGTH || iban_str.len() < consts::IBAN_MIN_LENGTH { return Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "IBAN length must be between {} and {} characters", consts::IBAN_MIN_LENGTH, consts::IBAN_MAX_LENGTH ), } .into()); } if iban.peek().len() > consts::IBAN_MAX_LENGTH { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "IBAN length must be up to 34 characters".to_string(), } .into()); } let pattern = Regex::new(r"^[A-Z0-9]*$") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to create regex pattern")?; let mut iban = iban.peek().to_string(); if !pattern.is_match(iban.as_str()) { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "IBAN data must be alphanumeric".to_string(), } .into()); } // MOD check let first_4 = iban.chars().take(4).collect::<String>(); iban.push_str(first_4.as_str()); let len = iban.len(); let rearranged_iban = iban .chars() .rev() .take(len - 4) .collect::<String>() .chars() .rev() .collect::<String>(); let mut result = String::new(); rearranged_iban.chars().for_each(|c| { if c.is_ascii_uppercase() { let digit = (u32::from(c) - u32::from('A')) + 10; result.push_str(&format!("{digit:02}")); } else { result.push(c); } }); let num = result .parse::<u128>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to validate IBAN")?; if num % 97 != 1 { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid IBAN".to_string(), } .into()); } Ok(()) } fn validate_uk_account( account_number: &Secret<String>, sort_code: &Secret<String>, ) -> RouterResult<()> { if account_number.peek().len() > consts::BACS_MAX_ACCOUNT_NUMBER_LENGTH || sort_code.peek().len() != consts::BACS_SORT_CODE_LENGTH { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid BACS numbers".to_string(), } .into()); } Ok(()) } fn validate_elixir_account(iban: &Secret<String>) -> RouterResult<()> { let iban_str = iban.peek(); // Validate IBAN first validate_iban(iban)?; // Check if IBAN is Polish if !iban_str.starts_with("PL") { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Elixir IBAN must be Polish (PL)".to_string(), } .into()); } // Validate IBAN length for Poland if iban_str.len() != consts::ELIXIR_IBAN_LENGTH { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Polish IBAN must be 28 characters".to_string(), } .into()); } Ok(()) } fn validate_bankgiro_number(number: &Secret<String>) -> RouterResult<()> { let num_str = number.peek(); let clean_number = num_str.replace("-", "").replace(" ", ""); // Length validation if clean_number.len() < consts::BANKGIRO_MIN_LENGTH || clean_number.len() > consts::BANKGIRO_MAX_LENGTH { return Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Bankgiro number must be between {} and {} digits", consts::BANKGIRO_MIN_LENGTH, consts::BANKGIRO_MAX_LENGTH ), } .into()); } // Must be numeric if !clean_number.chars().all(|c| c.is_ascii_digit()) { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Bankgiro number must be numeric".to_string(), } .into()); } Ok(()) } fn validate_plusgiro_number(number: &Secret<String>) -> RouterResult<()> { let num_str = number.peek(); let clean_number = num_str.replace("-", "").replace(" ", ""); // Length validation if clean_number.len() < consts::PLUSGIRO_MIN_LENGTH || clean_number.len() > consts::PLUSGIRO_MAX_LENGTH { return Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Plusgiro number must be between {} and {} digits", consts::PLUSGIRO_MIN_LENGTH, consts::PLUSGIRO_MAX_LENGTH ), } .into()); } // Must be numeric if !clean_number.chars().all(|c| c.is_ascii_digit()) { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Plusgiro number must be numeric".to_string(), } .into()); } Ok(()) } pub fn should_add_dispute_sync_task_to_pt(state: &SessionState, connector_name: Connector) -> bool { let list_dispute_supported_connectors = state .conf .list_dispute_supported_connectors .connector_list .clone(); list_dispute_supported_connectors.contains(&connector_name) } pub fn should_proceed_with_submit_evidence( dispute_stage: DisputeStage, dispute_status: DisputeStatus, ) -> bool { matches!( dispute_stage, DisputeStage::PreDispute | DisputeStage::Dispute | DisputeStage::PreArbitration | DisputeStage::Arbitration ) && matches!( dispute_status, DisputeStatus::DisputeOpened | DisputeStatus::DisputeChallenged ) } pub fn should_proceed_with_accept_dispute( dispute_stage: DisputeStage, dispute_status: DisputeStatus, ) -> bool { matches!( dispute_stage, DisputeStage::PreDispute | DisputeStage::Dispute | DisputeStage::PreArbitration | DisputeStage::Arbitration ) && matches!( dispute_status, DisputeStatus::DisputeChallenged | DisputeStatus::DisputeOpened ) }
{ "crate": "router", "file": "crates/router/src/core/utils.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_2471434254409511430
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/admin.rs // Contains: 1 structs, 0 enums use std::str::FromStr; use api_models::{ admin::{self as admin_types}, enums as api_enums, routing as routing_types, }; use common_enums::{MerchantAccountRequestType, MerchantAccountType, OrganizationType}; use common_utils::{ date_time, ext_traits::{AsyncExt, Encode, OptionExt, ValueExt}, fp_utils, id_type, pii, type_name, types::keymanager::{self as km_types, KeyManagerState, ToEncryptable}, }; #[cfg(all(any(feature = "v1", feature = "v2"), feature = "olap"))] use diesel_models::{business_profile::CardTestingGuardConfig, organization::OrganizationBridge}; use diesel_models::{configs, payment_method}; use error_stack::{report, FutureExt, ResultExt}; use external_services::http_client::client; use hyperswitch_domain_models::merchant_connector_account::{ FromRequestEncryptableMerchantConnectorAccount, UpdateEncryptableMerchantConnectorAccount, }; use masking::{ExposeInterface, PeekInterface, Secret}; use pm_auth::types as pm_auth_types; use uuid::Uuid; use super::routing::helpers::redact_cgraph_cache; #[cfg(any(feature = "v1", feature = "v2"))] use crate::types::transformers::ForeignFrom; use crate::{ consts, core::{ connector_validation::ConnectorAuthTypeAndMetadataValidation, disputes, encryption::transfer_encryption_key, errors::{self, RouterResponse, RouterResult, StorageErrorExt}, payment_methods::{cards, transformers}, payments::helpers, pm_auth::helpers::PaymentAuthConnectorDataExt, routing, utils as core_utils, }, db::{AccountsStorageInterface, StorageInterface}, logger, routes::{metrics, SessionState}, services::{ self, api::{self as service_api}, authentication, pm_auth as payment_initiation_service, }, types::{ self, api::{self, admin}, domain::{ self, types::{self as domain_types, AsyncLift}, }, storage::{self, enums::MerchantStorageScheme}, transformers::{ForeignInto, ForeignTryFrom, ForeignTryInto}, }, utils, }; #[inline] pub fn create_merchant_publishable_key() -> String { format!( "pk_{}_{}", router_env::env::prefix_for_env(), Uuid::new_v4().simple() ) } pub async fn insert_merchant_configs( db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, ) -> RouterResult<()> { db.insert_config(configs::ConfigNew { key: merchant_id.get_requires_cvv_key(), config: "true".to_string(), }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while setting requires_cvv config")?; db.insert_config(configs::ConfigNew { key: merchant_id.get_merchant_fingerprint_secret_key(), config: utils::generate_id(consts::FINGERPRINT_SECRET_LENGTH, "fs"), }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while inserting merchant fingerprint secret")?; Ok(()) } #[cfg(feature = "olap")] fn add_publishable_key_to_decision_service( state: &SessionState, merchant_context: &domain::MerchantContext, ) { let state = state.clone(); let publishable_key = merchant_context .get_merchant_account() .publishable_key .clone(); let merchant_id = merchant_context.get_merchant_account().get_id().clone(); authentication::decision::spawn_tracked_job( async move { authentication::decision::add_publishable_key( &state, publishable_key.into(), merchant_id, None, ) .await }, authentication::decision::ADD, ); } #[cfg(feature = "olap")] pub async fn create_organization( state: SessionState, req: api::OrganizationCreateRequest, ) -> RouterResponse<api::OrganizationResponse> { let db_organization = ForeignFrom::foreign_from(req); state .accounts_store .insert_organization(db_organization) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: "Organization with the given organization_name already exists".to_string(), }) .attach_printable("Error when creating organization") .map(ForeignFrom::foreign_from) .map(service_api::ApplicationResponse::Json) } #[cfg(feature = "olap")] pub async fn update_organization( state: SessionState, org_id: api::OrganizationId, req: api::OrganizationUpdateRequest, ) -> RouterResponse<api::OrganizationResponse> { let organization_update = diesel_models::organization::OrganizationUpdate::Update { organization_name: req.organization_name, organization_details: req.organization_details, metadata: req.metadata, platform_merchant_id: req.platform_merchant_id, }; state .accounts_store .update_organization_by_org_id(&org_id.organization_id, organization_update) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "organization with the given id does not exist".to_string(), }) .attach_printable(format!( "Failed to update organization with organization_id: {:?}", org_id.organization_id )) .map(ForeignFrom::foreign_from) .map(service_api::ApplicationResponse::Json) } #[cfg(feature = "olap")] pub async fn get_organization( state: SessionState, org_id: api::OrganizationId, ) -> RouterResponse<api::OrganizationResponse> { #[cfg(all(feature = "v1", feature = "olap"))] { CreateOrValidateOrganization::new(Some(org_id.organization_id)) .create_or_validate(state.accounts_store.as_ref()) .await .map(ForeignFrom::foreign_from) .map(service_api::ApplicationResponse::Json) } #[cfg(all(feature = "v2", feature = "olap"))] { CreateOrValidateOrganization::new(org_id.organization_id) .create_or_validate(state.accounts_store.as_ref()) .await .map(ForeignFrom::foreign_from) .map(service_api::ApplicationResponse::Json) } } #[cfg(feature = "olap")] pub async fn create_merchant_account( state: SessionState, req: api::MerchantAccountCreate, org_data_from_auth: Option<authentication::AuthenticationDataWithOrg>, ) -> RouterResponse<api::MerchantAccountResponse> { #[cfg(feature = "keymanager_create")] use common_utils::{keymanager, types::keymanager::EncryptionTransferRequest}; let db = state.store.as_ref(); let key = services::generate_aes256_key() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate aes 256 key")?; let master_key = db.get_master_key(); let key_manager_state: &KeyManagerState = &(&state).into(); let merchant_id = req.get_merchant_reference_id(); let identifier = km_types::Identifier::Merchant(merchant_id.clone()); #[cfg(feature = "keymanager_create")] { use base64::Engine; use crate::consts::BASE64_ENGINE; if key_manager_state.enabled { keymanager::transfer_key_to_key_manager( key_manager_state, EncryptionTransferRequest { identifier: identifier.clone(), key: BASE64_ENGINE.encode(key), }, ) .await .change_context(errors::ApiErrorResponse::DuplicateMerchantAccount) .attach_printable("Failed to insert key to KeyManager")?; } } let key_store = domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain_types::crypto_operation( key_manager_state, type_name!(domain::MerchantKeyStore), domain_types::CryptoOperation::Encrypt(key.to_vec().into()), identifier.clone(), master_key, ) .await .and_then(|val| val.try_into_operation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to decrypt data from key store")?, created_at: date_time::now(), }; let domain_merchant_account = req .create_domain_model_from_request( &state, key_store.clone(), &merchant_id, org_data_from_auth, ) .await?; let key_manager_state = &(&state).into(); db.insert_merchant_key_store( key_manager_state, key_store.clone(), &master_key.to_vec().into(), ) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?; let merchant_account = db .insert_merchant(key_manager_state, domain_merchant_account, &key_store) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), key_store.clone(), ))); add_publishable_key_to_decision_service(&state, &merchant_context); insert_merchant_configs(db, &merchant_id).await?; Ok(service_api::ApplicationResponse::Json( api::MerchantAccountResponse::foreign_try_from(merchant_account) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while generating response")?, )) } #[cfg(feature = "olap")] #[async_trait::async_trait] trait MerchantAccountCreateBridge { async fn create_domain_model_from_request( self, state: &SessionState, key: domain::MerchantKeyStore, identifier: &id_type::MerchantId, org_data_from_auth: Option<authentication::AuthenticationDataWithOrg>, ) -> RouterResult<domain::MerchantAccount>; } #[cfg(all(feature = "v1", feature = "olap"))] #[async_trait::async_trait] impl MerchantAccountCreateBridge for api::MerchantAccountCreate { async fn create_domain_model_from_request( self, state: &SessionState, key_store: domain::MerchantKeyStore, identifier: &id_type::MerchantId, org_data_from_auth: Option<authentication::AuthenticationDataWithOrg>, ) -> RouterResult<domain::MerchantAccount> { let db = &*state.accounts_store; let publishable_key = create_merchant_publishable_key(); let primary_business_details = self.get_primary_details_as_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "primary_business_details", }, )?; let webhook_details = self.webhook_details.clone().map(ForeignInto::foreign_into); let pm_collect_link_config = self.get_pm_link_config_as_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "pm_collect_link_config", }, )?; let merchant_details = self.get_merchant_details_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_details", }, )?; self.parse_routing_algorithm() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "routing_algorithm", }) .attach_printable("Invalid routing algorithm given")?; let metadata = self.get_metadata_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "metadata", }, )?; // Get the enable payment response hash as a boolean, where the default value is true let enable_payment_response_hash = self.get_enable_payment_response_hash(); let payment_response_hash_key = self.get_payment_response_hash_key(); let parent_merchant_id = get_parent_merchant( state, self.sub_merchants_enabled, self.parent_merchant_id.as_ref(), &key_store, ) .await?; let org_id = match (&self.organization_id, &org_data_from_auth) { (Some(req_org_id), Some(auth)) => { if req_org_id != &auth.organization_id { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Mismatched organization_id in request and authenticated context" .to_string(), } .into()); } Some(req_org_id.clone()) } (None, Some(auth)) => Some(auth.organization_id.clone()), (req_org_id, _) => req_org_id.clone(), }; let organization = CreateOrValidateOrganization::new(org_id) .create_or_validate(db) .await?; let merchant_account_type = match organization.get_organization_type() { OrganizationType::Standard => { match self.merchant_account_type.unwrap_or_default() { // Allow only if explicitly Standard or not provided MerchantAccountRequestType::Standard => MerchantAccountType::Standard, MerchantAccountRequestType::Connected => { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Merchant account type must be Standard for a Standard Organization" .to_string(), } .into()); } } } OrganizationType::Platform => { let accounts = state .store .list_merchant_accounts_by_organization_id( &state.into(), &organization.get_organization_id(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let platform_account_exists = accounts .iter() .any(|account| account.merchant_account_type == MerchantAccountType::Platform); if accounts.is_empty() || !platform_account_exists { // First merchant in a Platform org must be Platform MerchantAccountType::Platform } else { match self.merchant_account_type.unwrap_or_default() { MerchantAccountRequestType::Standard => MerchantAccountType::Standard, MerchantAccountRequestType::Connected => { if state.conf.platform.allow_connected_merchants { MerchantAccountType::Connected } else { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Connected merchant accounts are not allowed" .to_string(), } .into()); } } } } } }; let key = key_store.key.clone().into_inner(); let key_manager_state = state.into(); let merchant_account = async { Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>( domain::MerchantAccountSetter { merchant_id: identifier.clone(), merchant_name: self .merchant_name .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, type_name!(domain::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?, merchant_details: merchant_details .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, type_name!(domain::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?, return_url: self.return_url.map(|a| a.to_string()), webhook_details, routing_algorithm: Some(serde_json::json!({ "algorithm_id": null, "timestamp": 0 })), sub_merchants_enabled: self.sub_merchants_enabled, parent_merchant_id, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post: self .redirect_to_merchant_with_http_post .unwrap_or_default(), publishable_key, locker_id: self.locker_id, metadata, storage_scheme: MerchantStorageScheme::PostgresOnly, primary_business_details, created_at: date_time::now(), modified_at: date_time::now(), intent_fulfillment_time: None, frm_routing_algorithm: self.frm_routing_algorithm, #[cfg(feature = "payouts")] payout_routing_algorithm: self.payout_routing_algorithm, #[cfg(not(feature = "payouts"))] payout_routing_algorithm: None, organization_id: organization.get_organization_id(), is_recon_enabled: false, default_profile: None, recon_status: diesel_models::enums::ReconStatus::NotRequested, payment_link_config: None, pm_collect_link_config, version: common_types::consts::API_VERSION, is_platform_account: false, product_type: self.product_type, merchant_account_type, }, ) } .await .change_context(errors::ApiErrorResponse::InternalServerError)?; let mut domain_merchant_account = domain::MerchantAccount::from(merchant_account); CreateProfile::new(self.primary_business_details.clone()) .create_profiles(state, &mut domain_merchant_account, &key_store) .await?; Ok(domain_merchant_account) } } #[cfg(feature = "olap")] enum CreateOrValidateOrganization { /// Creates a new organization #[cfg(feature = "v1")] Create, /// Validates if this organization exists in the records Validate { organization_id: id_type::OrganizationId, }, } #[cfg(feature = "olap")] impl CreateOrValidateOrganization { #[cfg(all(feature = "v1", feature = "olap"))] /// Create an action to either create or validate the given organization_id /// If organization_id is passed, then validate if this organization exists /// If not passed, create a new organization fn new(organization_id: Option<id_type::OrganizationId>) -> Self { if let Some(organization_id) = organization_id { Self::Validate { organization_id } } else { Self::Create } } #[cfg(all(feature = "v2", feature = "olap"))] /// Create an action to validate the provided organization_id fn new(organization_id: id_type::OrganizationId) -> Self { Self::Validate { organization_id } } #[cfg(feature = "olap")] /// Apply the action, whether to create the organization or validate the given organization_id async fn create_or_validate( &self, db: &dyn AccountsStorageInterface, ) -> RouterResult<diesel_models::organization::Organization> { match self { #[cfg(feature = "v1")] Self::Create => { let new_organization = api_models::organization::OrganizationNew::new( OrganizationType::Standard, None, ); let db_organization = ForeignFrom::foreign_from(new_organization); db.insert_organization(db_organization) .await .to_duplicate_response(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error when creating organization") } Self::Validate { organization_id } => db .find_organization_by_org_id(organization_id) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "organization with the given id does not exist".to_string(), }), } } } #[cfg(all(feature = "v1", feature = "olap"))] enum CreateProfile { /// Create profiles from primary business details /// If there is only one profile created, then set this profile as default CreateFromPrimaryBusinessDetails { primary_business_details: Vec<admin_types::PrimaryBusinessDetails>, }, /// Create a default profile, set this as default profile CreateDefaultProfile, } #[cfg(all(feature = "v1", feature = "olap"))] impl CreateProfile { /// Create a new profile action from the given information /// If primary business details exist, then create profiles from them /// If primary business details are empty, then create default profile fn new(primary_business_details: Option<Vec<admin_types::PrimaryBusinessDetails>>) -> Self { match primary_business_details { Some(primary_business_details) if !primary_business_details.is_empty() => { Self::CreateFromPrimaryBusinessDetails { primary_business_details, } } _ => Self::CreateDefaultProfile, } } async fn create_profiles( &self, state: &SessionState, merchant_account: &mut domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<()> { match self { Self::CreateFromPrimaryBusinessDetails { primary_business_details, } => { let business_profiles = Self::create_profiles_for_each_business_details( state, merchant_account.clone(), primary_business_details, key_store, ) .await?; // Update the default business profile in merchant account if business_profiles.len() == 1 { merchant_account.default_profile = business_profiles .first() .map(|business_profile| business_profile.get_id().to_owned()) } } Self::CreateDefaultProfile => { let business_profile = self .create_default_business_profile(state, merchant_account.clone(), key_store) .await?; merchant_account.default_profile = Some(business_profile.get_id().to_owned()); } } Ok(()) } /// Create default profile async fn create_default_business_profile( &self, state: &SessionState, merchant_account: domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<domain::Profile> { let business_profile = create_and_insert_business_profile( state, api_models::admin::ProfileCreate::default(), merchant_account.clone(), key_store, ) .await?; Ok(business_profile) } /// Create profile for each primary_business_details, /// If there is no default profile in merchant account and only one primary_business_detail /// is available, then create a default profile. async fn create_profiles_for_each_business_details( state: &SessionState, merchant_account: domain::MerchantAccount, primary_business_details: &Vec<admin_types::PrimaryBusinessDetails>, key_store: &domain::MerchantKeyStore, ) -> RouterResult<Vec<domain::Profile>> { let mut business_profiles_vector = Vec::with_capacity(primary_business_details.len()); // This must ideally be run in a transaction, // if there is an error in inserting some profile, because of unique constraints // the whole query must be rolled back for business_profile in primary_business_details { let profile_name = format!("{}_{}", business_profile.country, business_profile.business); let profile_create_request = api_models::admin::ProfileCreate { profile_name: Some(profile_name), ..Default::default() }; create_and_insert_business_profile( state, profile_create_request, merchant_account.clone(), key_store, ) .await .map_err(|profile_insert_error| { logger::warn!("Profile already exists {profile_insert_error:?}"); }) .map(|business_profile| business_profiles_vector.push(business_profile)) .ok(); } Ok(business_profiles_vector) } } #[cfg(all(feature = "v2", feature = "olap"))] #[async_trait::async_trait] impl MerchantAccountCreateBridge for api::MerchantAccountCreate { async fn create_domain_model_from_request( self, state: &SessionState, key_store: domain::MerchantKeyStore, identifier: &id_type::MerchantId, _org_data: Option<authentication::AuthenticationDataWithOrg>, ) -> RouterResult<domain::MerchantAccount> { let publishable_key = create_merchant_publishable_key(); let db = &*state.accounts_store; let metadata = self.get_metadata_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "metadata", }, )?; let merchant_details = self.get_merchant_details_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_details", }, )?; let organization = CreateOrValidateOrganization::new(self.organization_id.clone()) .create_or_validate(db) .await?; // V2 currently supports creation of Standard merchant accounts only, irrespective of organization type let merchant_account_type = MerchantAccountType::Standard; let key = key_store.key.into_inner(); let id = identifier.to_owned(); let key_manager_state = state.into(); let identifier = km_types::Identifier::Merchant(id.clone()); async { Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>( domain::MerchantAccount::from(domain::MerchantAccountSetter { id, merchant_name: Some( domain_types::crypto_operation( &key_manager_state, type_name!(domain::MerchantAccount), domain_types::CryptoOperation::Encrypt( self.merchant_name .map(|merchant_name| merchant_name.into_inner()), ), identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_operation())?, ), merchant_details: merchant_details .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, type_name!(domain::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?, publishable_key, metadata, storage_scheme: MerchantStorageScheme::PostgresOnly, created_at: date_time::now(), modified_at: date_time::now(), organization_id: organization.get_organization_id(), recon_status: diesel_models::enums::ReconStatus::NotRequested, is_platform_account: false, version: common_types::consts::API_VERSION, product_type: self.product_type, merchant_account_type, }), ) } .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to encrypt merchant details") } } #[cfg(all(feature = "olap", feature = "v2"))] pub async fn list_merchant_account( state: SessionState, organization_id: api_models::organization::OrganizationId, ) -> RouterResponse<Vec<api::MerchantAccountResponse>> { let merchant_accounts = state .store .list_merchant_accounts_by_organization_id( &(&state).into(), &organization_id.organization_id, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_accounts = merchant_accounts .into_iter() .map(|merchant_account| { api::MerchantAccountResponse::foreign_try_from(merchant_account).change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_account", }, ) }) .collect::<Result<Vec<_>, _>>()?; Ok(services::ApplicationResponse::Json(merchant_accounts)) } #[cfg(all(feature = "olap", feature = "v1"))] pub async fn list_merchant_account( state: SessionState, req: api_models::admin::MerchantAccountListRequest, org_data_from_auth: Option<authentication::AuthenticationDataWithOrg>, ) -> RouterResponse<Vec<api::MerchantAccountResponse>> { if let Some(auth) = org_data_from_auth { if auth.organization_id != req.organization_id { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Organization ID in request and authentication do not match".to_string(), } .into()); } } let merchant_accounts = state .store .list_merchant_accounts_by_organization_id(&(&state).into(), &req.organization_id) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_accounts = merchant_accounts .into_iter() .map(|merchant_account| { api::MerchantAccountResponse::foreign_try_from(merchant_account).change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_account", }, ) }) .collect::<Result<Vec<_>, _>>()?; Ok(services::ApplicationResponse::Json(merchant_accounts)) } pub async fn get_merchant_account( state: SessionState, req: api::MerchantId, _profile_id: Option<id_type::ProfileId>, ) -> RouterResponse<api::MerchantAccountResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &req.merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, &req.merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; Ok(service_api::ApplicationResponse::Json( api::MerchantAccountResponse::foreign_try_from(merchant_account) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct response")?, )) } #[cfg(feature = "v1")] /// For backwards compatibility, whenever new business labels are passed in /// primary_business_details, create a profile pub async fn create_profile_from_business_labels( state: &SessionState, db: &dyn StorageInterface, key_store: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, new_business_details: Vec<admin_types::PrimaryBusinessDetails>, ) -> RouterResult<()> { let key_manager_state = &state.into(); let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let old_business_details = merchant_account .primary_business_details .clone() .parse_value::<Vec<admin_types::PrimaryBusinessDetails>>("PrimaryBusinessDetails") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "routing_algorithm", }) .attach_printable("Invalid routing algorithm given")?; // find the diff between two vectors let business_profiles_to_create = new_business_details .into_iter() .filter(|business_details| !old_business_details.contains(business_details)) .collect::<Vec<_>>(); for business_profile in business_profiles_to_create { let profile_name = format!("{}_{}", business_profile.country, business_profile.business); let profile_create_request = admin_types::ProfileCreate { profile_name: Some(profile_name), ..Default::default() }; let profile_create_result = create_and_insert_business_profile( state, profile_create_request, merchant_account.clone(), key_store, ) .await .map_err(|profile_insert_error| { // If there is any duplicate error, we need not take any action logger::warn!("Profile already exists {profile_insert_error:?}"); }); // If a profile is created, then unset the default profile if profile_create_result.is_ok() && merchant_account.default_profile.is_some() { let unset_default_profile = domain::MerchantAccountUpdate::UnsetDefaultProfile; db.update_merchant( key_manager_state, merchant_account.clone(), unset_default_profile, key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; } } Ok(()) } #[cfg(any(feature = "v1", feature = "v2", feature = "olap"))] #[async_trait::async_trait] trait MerchantAccountUpdateBridge { async fn get_update_merchant_object( self, state: &SessionState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, ) -> RouterResult<storage::MerchantAccountUpdate>; } #[cfg(feature = "v1")] #[async_trait::async_trait] impl MerchantAccountUpdateBridge for api::MerchantAccountUpdate { async fn get_update_merchant_object( self, state: &SessionState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, ) -> RouterResult<storage::MerchantAccountUpdate> { let key_manager_state = &state.into(); let key = key_store.key.get_inner().peek(); let db = state.store.as_ref(); let primary_business_details = self.get_primary_details_as_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "primary_business_details", }, )?; let pm_collect_link_config = self.get_pm_link_config_as_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "pm_collect_link_config", }, )?; let merchant_details = self.get_merchant_details_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_details", }, )?; self.parse_routing_algorithm().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "routing_algorithm", }, )?; let webhook_details = self.webhook_details.map(ForeignInto::foreign_into); let parent_merchant_id = get_parent_merchant( state, self.sub_merchants_enabled, self.parent_merchant_id.as_ref(), key_store, ) .await?; // This supports changing the business profile by passing in the profile_id let business_profile_id_update = if let Some(ref profile_id) = self.default_profile { // Validate whether profile_id passed in request is valid and is linked to the merchant core_utils::validate_and_get_business_profile( state.store.as_ref(), key_manager_state, key_store, Some(profile_id), merchant_id, ) .await? .map(|business_profile| Some(business_profile.get_id().to_owned())) } else { None }; #[cfg(any(feature = "v1", feature = "v2"))] // In order to support backwards compatibility, if a business_labels are passed in the update // call, then create new profiles with the profile_name as business_label self.primary_business_details .clone() .async_map(|primary_business_details| async { let _ = create_profile_from_business_labels( state, db, key_store, merchant_id, primary_business_details, ) .await; }) .await; let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone()); Ok(storage::MerchantAccountUpdate::Update { merchant_name: self .merchant_name .map(Secret::new) .async_lift(|inner| async { domain_types::crypto_operation( key_manager_state, type_name!(storage::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), identifier.clone(), key, ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt merchant name")?, merchant_details: merchant_details .async_lift(|inner| async { domain_types::crypto_operation( key_manager_state, type_name!(storage::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), identifier.clone(), key, ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt merchant details")?, return_url: self.return_url.map(|a| a.to_string()), webhook_details, sub_merchants_enabled: self.sub_merchants_enabled, parent_merchant_id, enable_payment_response_hash: self.enable_payment_response_hash, payment_response_hash_key: self.payment_response_hash_key, redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, locker_id: self.locker_id, metadata: self.metadata, publishable_key: None, primary_business_details, frm_routing_algorithm: self.frm_routing_algorithm, intent_fulfillment_time: None, #[cfg(feature = "payouts")] payout_routing_algorithm: self.payout_routing_algorithm, #[cfg(not(feature = "payouts"))] payout_routing_algorithm: None, default_profile: business_profile_id_update, payment_link_config: None, pm_collect_link_config, routing_algorithm: self.routing_algorithm, }) } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl MerchantAccountUpdateBridge for api::MerchantAccountUpdate { async fn get_update_merchant_object( self, state: &SessionState, _merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, ) -> RouterResult<storage::MerchantAccountUpdate> { let key_manager_state = &state.into(); let key = key_store.key.get_inner().peek(); let merchant_details = self.get_merchant_details_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_details", }, )?; let metadata = self.get_metadata_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "metadata", }, )?; let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone()); Ok(storage::MerchantAccountUpdate::Update { merchant_name: self .merchant_name .map(Secret::new) .async_lift(|inner| async { domain_types::crypto_operation( key_manager_state, type_name!(storage::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), identifier.clone(), key, ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt merchant name")?, merchant_details: merchant_details .async_lift(|inner| async { domain_types::crypto_operation( key_manager_state, type_name!(storage::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), identifier.clone(), key, ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt merchant details")?, metadata: metadata.map(Box::new), publishable_key: None, }) } } pub async fn merchant_account_update( state: SessionState, merchant_id: &id_type::MerchantId, _profile_id: Option<id_type::ProfileId>, req: api::MerchantAccountUpdate, ) -> RouterResponse<api::MerchantAccountResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account_storage_object = req .get_update_merchant_object(&state, merchant_id, &key_store) .await .attach_printable("Failed to create merchant account update object")?; let response = db .update_specific_fields_in_merchant( key_manager_state, merchant_id, merchant_account_storage_object, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; Ok(service_api::ApplicationResponse::Json( api::MerchantAccountResponse::foreign_try_from(response) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while generating response")?, )) } pub async fn merchant_account_delete( state: SessionState, merchant_id: id_type::MerchantId, ) -> RouterResponse<api::MerchantAccountDeleteResponse> { let mut is_deleted = false; let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_key_store = db .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(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &merchant_key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let is_merchant_account_deleted = db .delete_merchant_account_by_merchant_id(&merchant_id) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; if is_merchant_account_deleted { let is_merchant_key_store_deleted = db .delete_merchant_key_store_by_merchant_id(&merchant_id) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; is_deleted = is_merchant_account_deleted && is_merchant_key_store_deleted; } let state = state.clone(); authentication::decision::spawn_tracked_job( async move { authentication::decision::revoke_api_key( &state, merchant_account.publishable_key.into(), ) .await }, authentication::decision::REVOKE, ); match db .delete_config_by_key(merchant_id.get_requires_cvv_key().as_str()) .await { Ok(_) => Ok::<_, errors::ApiErrorResponse>(()), Err(err) => { if err.current_context().is_db_not_found() { logger::error!("requires_cvv config not found in db: {err:?}"); Ok(()) } else { Err(err .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while deleting requires_cvv config"))? } } } .ok(); let response = api::MerchantAccountDeleteResponse { merchant_id, deleted: is_deleted, }; Ok(service_api::ApplicationResponse::Json(response)) } #[cfg(feature = "v1")] async fn get_parent_merchant( state: &SessionState, sub_merchants_enabled: Option<bool>, parent_merchant: Option<&id_type::MerchantId>, key_store: &domain::MerchantKeyStore, ) -> RouterResult<Option<id_type::MerchantId>> { Ok(match sub_merchants_enabled { Some(true) => { Some( parent_merchant.ok_or_else(|| { report!(errors::ValidationError::MissingRequiredField { field_name: "parent_merchant_id".to_string() }) .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "If `sub_merchants_enabled` is `true`, then `parent_merchant_id` is mandatory".to_string(), }) }) .map(|id| validate_merchant_id(state, id,key_store).change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "parent_merchant_id" } ))? .await? .get_id().to_owned() ) } _ => None, }) } #[cfg(feature = "v1")] async fn validate_merchant_id( state: &SessionState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, ) -> RouterResult<domain::MerchantAccount> { let db = &*state.store; db.find_merchant_account_by_merchant_id(&state.into(), merchant_id, key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) } struct ConnectorStatusAndDisabledValidation<'a> { status: &'a Option<api_enums::ConnectorStatus>, disabled: &'a Option<bool>, auth: &'a types::ConnectorAuthType, current_status: &'a api_enums::ConnectorStatus, } impl ConnectorStatusAndDisabledValidation<'_> { fn validate_status_and_disabled( &self, ) -> RouterResult<(api_enums::ConnectorStatus, Option<bool>)> { let connector_status = match (self.status, self.auth) { ( Some(common_enums::ConnectorStatus::Active), types::ConnectorAuthType::TemporaryAuth, ) => { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Connector status cannot be active when using TemporaryAuth" .to_string(), } .into()); } (Some(status), _) => status, (None, types::ConnectorAuthType::TemporaryAuth) => { &common_enums::ConnectorStatus::Inactive } (None, _) => self.current_status, }; let disabled = match (self.disabled, connector_status) { (Some(false), common_enums::ConnectorStatus::Inactive) => { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Connector cannot be enabled when connector_status is inactive or when using TemporaryAuth" .to_string(), } .into()); } (Some(disabled), _) => Some(*disabled), (None, common_enums::ConnectorStatus::Inactive) => Some(true), // Enable the connector if nothing is passed in the request (None, _) => Some(false), }; Ok((*connector_status, disabled)) } } struct ConnectorMetadata<'a> { connector_metadata: &'a Option<pii::SecretSerdeValue>, } impl ConnectorMetadata<'_> { fn validate_apple_pay_certificates_in_mca_metadata(&self) -> RouterResult<()> { self.connector_metadata .clone() .map(api_models::payments::ConnectorMetadata::from_value) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "metadata".to_string(), expected_format: "connector metadata".to_string(), })? .and_then(|metadata| metadata.get_apple_pay_certificates()) .map(|(certificate, certificate_key)| { client::create_identity_from_certificate_and_key(certificate, certificate_key) }) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "certificate/certificate key", })?; Ok(()) } } struct PMAuthConfigValidation<'a> { connector_type: &'a api_enums::ConnectorType, pm_auth_config: &'a Option<pii::SecretSerdeValue>, db: &'a dyn StorageInterface, merchant_id: &'a id_type::MerchantId, profile_id: &'a id_type::ProfileId, key_store: &'a domain::MerchantKeyStore, key_manager_state: &'a KeyManagerState, } impl PMAuthConfigValidation<'_> { async fn validate_pm_auth(&self, val: &pii::SecretSerdeValue) -> RouterResponse<()> { let config = serde_json::from_value::<api_models::pm_auth::PaymentMethodAuthConfig>( val.clone().expose(), ) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "invalid data received for payment method auth config".to_string(), }) .attach_printable("Failed to deserialize Payment Method Auth config")?; let all_mcas = self .db .find_merchant_connector_account_by_merchant_id_and_disabled_list( self.key_manager_state, self.merchant_id, true, self.key_store, ) .await .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: self.merchant_id.get_string_repr().to_owned(), })?; for conn_choice in config.enabled_payment_methods { let pm_auth_mca = all_mcas .iter() .find(|mca| mca.get_id() == conn_choice.mca_id) .ok_or(errors::ApiErrorResponse::GenericNotFoundError { message: "payment method auth connector account not found".to_string(), })?; if &pm_auth_mca.profile_id != self.profile_id { return Err(errors::ApiErrorResponse::GenericNotFoundError { message: "payment method auth profile_id differs from connector profile_id" .to_string(), } .into()); } } Ok(services::ApplicationResponse::StatusOk) } async fn validate_pm_auth_config(&self) -> RouterResult<()> { if self.connector_type != &api_enums::ConnectorType::PaymentMethodAuth { if let Some(val) = self.pm_auth_config.clone() { self.validate_pm_auth(&val).await?; } } Ok(()) } } struct ConnectorTypeAndConnectorName<'a> { connector_type: &'a api_enums::ConnectorType, connector_name: &'a api_enums::Connector, } impl ConnectorTypeAndConnectorName<'_> { fn get_routable_connector(&self) -> RouterResult<Option<api_enums::RoutableConnectors>> { let mut routable_connector = api_enums::RoutableConnectors::from_str(&self.connector_name.to_string()).ok(); let vault_connector = api_enums::convert_vault_connector(self.connector_name.to_string().as_str()); let pm_auth_connector = api_enums::convert_pm_auth_connector(self.connector_name.to_string().as_str()); let authentication_connector = api_enums::convert_authentication_connector(self.connector_name.to_string().as_str()); let tax_connector = api_enums::convert_tax_connector(self.connector_name.to_string().as_str()); let billing_connector = api_enums::convert_billing_connector(self.connector_name.to_string().as_str()); if pm_auth_connector.is_some() { if self.connector_type != &api_enums::ConnectorType::PaymentMethodAuth && self.connector_type != &api_enums::ConnectorType::PaymentProcessor { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid connector type given".to_string(), } .into()); } } else if authentication_connector.is_some() { if self.connector_type != &api_enums::ConnectorType::AuthenticationProcessor { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid connector type given".to_string(), } .into()); } } else if tax_connector.is_some() { if self.connector_type != &api_enums::ConnectorType::TaxProcessor { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid connector type given".to_string(), } .into()); } } else if billing_connector.is_some() { if self.connector_type != &api_enums::ConnectorType::BillingProcessor { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid connector type given".to_string(), } .into()); } } else if vault_connector.is_some() { if self.connector_type != &api_enums::ConnectorType::VaultProcessor { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid connector type given".to_string(), } .into()); } } else { let routable_connector_option = self .connector_name .to_string() .parse::<api_enums::RoutableConnectors>() .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid connector name given".to_string(), })?; routable_connector = Some(routable_connector_option); }; Ok(routable_connector) } } #[cfg(feature = "v1")] struct MerchantDefaultConfigUpdate<'a> { routable_connector: &'a Option<api_enums::RoutableConnectors>, merchant_connector_id: &'a id_type::MerchantConnectorAccountId, store: &'a dyn StorageInterface, merchant_id: &'a id_type::MerchantId, profile_id: &'a id_type::ProfileId, transaction_type: &'a api_enums::TransactionType, } #[cfg(feature = "v1")] impl MerchantDefaultConfigUpdate<'_> { async fn retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists( &self, ) -> RouterResult<()> { let mut default_routing_config = routing::helpers::get_merchant_default_config( self.store, self.merchant_id.get_string_repr(), self.transaction_type, ) .await?; let mut default_routing_config_for_profile = routing::helpers::get_merchant_default_config( self.store, self.profile_id.get_string_repr(), self.transaction_type, ) .await?; if let Some(routable_connector_val) = self.routable_connector { let choice = routing_types::RoutableConnectorChoice { choice_kind: routing_types::RoutableChoiceKind::FullStruct, connector: *routable_connector_val, merchant_connector_id: Some(self.merchant_connector_id.clone()), }; if !default_routing_config.contains(&choice) { default_routing_config.push(choice.clone()); routing::helpers::update_merchant_default_config( self.store, self.merchant_id.get_string_repr(), default_routing_config.clone(), self.transaction_type, ) .await?; } if !default_routing_config_for_profile.contains(&choice.clone()) { default_routing_config_for_profile.push(choice); routing::helpers::update_merchant_default_config( self.store, self.profile_id.get_string_repr(), default_routing_config_for_profile.clone(), self.transaction_type, ) .await?; } } Ok(()) } async fn retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists( &self, ) -> RouterResult<()> { let mut default_routing_config = routing::helpers::get_merchant_default_config( self.store, self.merchant_id.get_string_repr(), self.transaction_type, ) .await?; let mut default_routing_config_for_profile = routing::helpers::get_merchant_default_config( self.store, self.profile_id.get_string_repr(), self.transaction_type, ) .await?; if let Some(routable_connector_val) = self.routable_connector { let choice = routing_types::RoutableConnectorChoice { choice_kind: routing_types::RoutableChoiceKind::FullStruct, connector: *routable_connector_val, merchant_connector_id: Some(self.merchant_connector_id.clone()), }; if default_routing_config.contains(&choice) { default_routing_config.retain(|mca| { mca.merchant_connector_id.as_ref() != Some(self.merchant_connector_id) }); routing::helpers::update_merchant_default_config( self.store, self.merchant_id.get_string_repr(), default_routing_config.clone(), self.transaction_type, ) .await?; } if default_routing_config_for_profile.contains(&choice.clone()) { default_routing_config_for_profile.retain(|mca| { mca.merchant_connector_id.as_ref() != Some(self.merchant_connector_id) }); routing::helpers::update_merchant_default_config( self.store, self.profile_id.get_string_repr(), default_routing_config_for_profile.clone(), self.transaction_type, ) .await?; } } Ok(()) } } #[cfg(feature = "v2")] struct DefaultFallbackRoutingConfigUpdate<'a> { routable_connector: &'a Option<api_enums::RoutableConnectors>, merchant_connector_id: &'a id_type::MerchantConnectorAccountId, store: &'a dyn StorageInterface, business_profile: domain::Profile, key_store: hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, key_manager_state: &'a KeyManagerState, } #[cfg(feature = "v2")] impl DefaultFallbackRoutingConfigUpdate<'_> { async fn retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists( &self, ) -> RouterResult<()> { let profile_wrapper = ProfileWrapper::new(self.business_profile.clone()); let default_routing_config_for_profile = &mut profile_wrapper.get_default_fallback_list_of_connector_under_profile()?; if let Some(routable_connector_val) = self.routable_connector { let choice = routing_types::RoutableConnectorChoice { choice_kind: routing_types::RoutableChoiceKind::FullStruct, connector: *routable_connector_val, merchant_connector_id: Some(self.merchant_connector_id.clone()), }; if !default_routing_config_for_profile.contains(&choice.clone()) { default_routing_config_for_profile.push(choice); profile_wrapper .update_default_fallback_routing_of_connectors_under_profile( self.store, default_routing_config_for_profile, self.key_manager_state, &self.key_store, ) .await? } } Ok(()) } async fn retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists( &self, ) -> RouterResult<()> { let profile_wrapper = ProfileWrapper::new(self.business_profile.clone()); let default_routing_config_for_profile = &mut profile_wrapper.get_default_fallback_list_of_connector_under_profile()?; if let Some(routable_connector_val) = self.routable_connector { let choice = routing_types::RoutableConnectorChoice { choice_kind: routing_types::RoutableChoiceKind::FullStruct, connector: *routable_connector_val, merchant_connector_id: Some(self.merchant_connector_id.clone()), }; if default_routing_config_for_profile.contains(&choice.clone()) { default_routing_config_for_profile.retain(|mca| { mca.merchant_connector_id.as_ref() != Some(self.merchant_connector_id) }); profile_wrapper .update_default_fallback_routing_of_connectors_under_profile( self.store, default_routing_config_for_profile, self.key_manager_state, &self.key_store, ) .await? } } Ok(()) } } #[cfg(any(feature = "v1", feature = "v2", feature = "olap"))] #[async_trait::async_trait] trait MerchantConnectorAccountUpdateBridge { async fn get_merchant_connector_account_from_id( self, db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, merchant_connector_id: &id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> RouterResult<domain::MerchantConnectorAccount>; async fn create_domain_model_from_request( self, state: &SessionState, mca: &domain::MerchantConnectorAccount, key_manager_state: &KeyManagerState, merchant_context: &domain::MerchantContext, ) -> RouterResult<domain::MerchantConnectorAccountUpdate>; } #[cfg(all(feature = "v2", feature = "olap"))] #[async_trait::async_trait] impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnectorUpdate { async fn get_merchant_connector_account_from_id( self, db: &dyn StorageInterface, _merchant_id: &id_type::MerchantId, merchant_connector_id: &id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> RouterResult<domain::MerchantConnectorAccount> { db.find_merchant_connector_account_by_id( key_manager_state, merchant_connector_id, key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) } async fn create_domain_model_from_request( self, state: &SessionState, mca: &domain::MerchantConnectorAccount, key_manager_state: &KeyManagerState, merchant_context: &domain::MerchantContext, ) -> RouterResult<domain::MerchantConnectorAccountUpdate> { let frm_configs = self.get_frm_config_as_secret(); let payment_methods_enabled = self.payment_methods_enabled; let auth = types::ConnectorAuthType::from_secret_value( self.connector_account_details .clone() .unwrap_or(mca.connector_account_details.clone().into_inner()), ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_account_details".to_string(), expected_format: "auth_type and api_key".to_string(), })?; let metadata = self.metadata.clone().or(mca.metadata.clone()); let connector_auth_type_and_metadata_validation = ConnectorAuthTypeAndMetadataValidation { connector_name: &mca.connector_name, auth_type: &auth, connector_meta_data: &metadata, }; connector_auth_type_and_metadata_validation.validate_auth_and_metadata_type()?; let connector_status_and_disabled_validation = ConnectorStatusAndDisabledValidation { status: &self.status, disabled: &self.disabled, auth: &auth, current_status: &mca.status, }; let (connector_status, disabled) = connector_status_and_disabled_validation.validate_status_and_disabled()?; let pm_auth_config_validation = PMAuthConfigValidation { connector_type: &self.connector_type, pm_auth_config: &self.pm_auth_config, db: state.store.as_ref(), merchant_id: merchant_context.get_merchant_account().get_id(), profile_id: &mca.profile_id.clone(), key_store: merchant_context.get_merchant_key_store(), key_manager_state, }; pm_auth_config_validation.validate_pm_auth_config().await?; let merchant_recipient_data = if let Some(data) = &self.additional_merchant_data { Some( process_open_banking_connectors( state, merchant_context.get_merchant_account().get_id(), &auth, &self.connector_type, &mca.connector_name, types::AdditionalMerchantData::foreign_from(data.clone()), merchant_context.get_merchant_key_store(), ) .await?, ) } else { None } .map(|data| { serde_json::to_value(types::AdditionalMerchantData::OpenBankingRecipientData( data, )) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize MerchantRecipientData")?; let encrypted_data = domain_types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), domain_types::CryptoOperation::BatchEncrypt( UpdateEncryptableMerchantConnectorAccount::to_encryptable( UpdateEncryptableMerchantConnectorAccount { connector_account_details: self.connector_account_details, connector_wallets_details: helpers::get_connector_wallets_details_with_apple_pay_certificates( &self.metadata, &self.connector_wallets_details, ) .await?, additional_merchant_data: merchant_recipient_data.map(Secret::new), }, ), ), km_types::Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), merchant_context.get_merchant_key_store().key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details".to_string())?; let encrypted_data = UpdateEncryptableMerchantConnectorAccount::from_encryptable(encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details")?; let feature_metadata = self .feature_metadata .as_ref() .map(ForeignTryFrom::foreign_try_from) .transpose()?; Ok(storage::MerchantConnectorAccountUpdate::Update { connector_type: Some(self.connector_type), connector_label: self.connector_label.clone(), connector_account_details: Box::new(encrypted_data.connector_account_details), disabled, payment_methods_enabled, metadata: self.metadata, frm_configs, connector_webhook_details: match &self.connector_webhook_details { Some(connector_webhook_details) => Box::new( connector_webhook_details .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .map(Some)? .map(Secret::new), ), None => Box::new(None), }, applepay_verified_domains: None, pm_auth_config: Box::new(self.pm_auth_config), status: Some(connector_status), additional_merchant_data: Box::new(encrypted_data.additional_merchant_data), connector_wallets_details: Box::new(encrypted_data.connector_wallets_details), feature_metadata: Box::new(feature_metadata), }) } } #[cfg(all(feature = "v1", feature = "olap"))] #[async_trait::async_trait] impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnectorUpdate { async fn get_merchant_connector_account_from_id( self, db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, merchant_connector_id: &id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> RouterResult<domain::MerchantConnectorAccount> { db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_id, merchant_connector_id, key_store, ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, ) } async fn create_domain_model_from_request( self, state: &SessionState, mca: &domain::MerchantConnectorAccount, key_manager_state: &KeyManagerState, merchant_context: &domain::MerchantContext, ) -> RouterResult<domain::MerchantConnectorAccountUpdate> { let payment_methods_enabled = self.payment_methods_enabled.map(|pm_enabled| { pm_enabled .iter() .flat_map(Encode::encode_to_value) .map(Secret::new) .collect::<Vec<pii::SecretSerdeValue>>() }); let frm_configs = get_frm_config_as_secret(self.frm_configs); let auth: types::ConnectorAuthType = self .connector_account_details .clone() .unwrap_or(mca.connector_account_details.clone().into_inner()) .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_account_details".to_string(), expected_format: "auth_type and api_key".to_string(), })?; let metadata = self.metadata.clone().or(mca.metadata.clone()); let connector_name = mca.connector_name.as_ref(); let connector_enum = api_models::enums::Connector::from_str(connector_name) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "connector", }) .attach_printable_lazy(|| { format!("unable to parse connector name {connector_name:?}") })?; let connector_auth_type_and_metadata_validation = ConnectorAuthTypeAndMetadataValidation { connector_name: &connector_enum, auth_type: &auth, connector_meta_data: &metadata, }; connector_auth_type_and_metadata_validation.validate_auth_and_metadata_type()?; let connector_status_and_disabled_validation = ConnectorStatusAndDisabledValidation { status: &self.status, disabled: &self.disabled, auth: &auth, current_status: &mca.status, }; let (connector_status, disabled) = connector_status_and_disabled_validation.validate_status_and_disabled()?; if self.connector_type != api_enums::ConnectorType::PaymentMethodAuth { if let Some(val) = self.pm_auth_config.clone() { validate_pm_auth( val, state, merchant_context.get_merchant_account().get_id(), merchant_context.clone(), &mca.profile_id, ) .await?; } } let merchant_recipient_data = if let Some(data) = &self.additional_merchant_data { Some( process_open_banking_connectors( state, merchant_context.get_merchant_account().get_id(), &auth, &self.connector_type, &connector_enum, types::AdditionalMerchantData::foreign_from(data.clone()), merchant_context.get_merchant_key_store(), ) .await?, ) } else { None } .map(|data| { serde_json::to_value(types::AdditionalMerchantData::OpenBankingRecipientData( data, )) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize MerchantRecipientData")?; let encrypted_data = domain_types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), domain_types::CryptoOperation::BatchEncrypt( UpdateEncryptableMerchantConnectorAccount::to_encryptable( UpdateEncryptableMerchantConnectorAccount { connector_account_details: self.connector_account_details, connector_wallets_details: helpers::get_connector_wallets_details_with_apple_pay_certificates( &self.metadata, &self.connector_wallets_details, ) .await?, additional_merchant_data: merchant_recipient_data.map(Secret::new), }, ), ), km_types::Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), merchant_context.get_merchant_key_store().key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details".to_string())?; let encrypted_data = UpdateEncryptableMerchantConnectorAccount::from_encryptable(encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details")?; Ok(storage::MerchantConnectorAccountUpdate::Update { connector_type: Some(self.connector_type), connector_name: None, merchant_connector_id: None, connector_label: self.connector_label.clone(), connector_account_details: Box::new(encrypted_data.connector_account_details), test_mode: self.test_mode, disabled, payment_methods_enabled, metadata: self.metadata, frm_configs, connector_webhook_details: match &self.connector_webhook_details { Some(connector_webhook_details) => Box::new( connector_webhook_details .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .map(Some)? .map(Secret::new), ), None => Box::new(None), }, applepay_verified_domains: None, pm_auth_config: Box::new(self.pm_auth_config), status: Some(connector_status), additional_merchant_data: Box::new(encrypted_data.additional_merchant_data), connector_wallets_details: Box::new(encrypted_data.connector_wallets_details), }) } } #[cfg(any(feature = "v1", feature = "v2", feature = "olap"))] #[async_trait::async_trait] trait MerchantConnectorAccountCreateBridge { async fn create_domain_model_from_request( self, state: &SessionState, key_store: domain::MerchantKeyStore, business_profile: &domain::Profile, key_manager_state: &KeyManagerState, ) -> RouterResult<domain::MerchantConnectorAccount>; async fn validate_and_get_business_profile( self, merchant_context: &domain::MerchantContext, db: &dyn StorageInterface, key_manager_state: &KeyManagerState, ) -> RouterResult<domain::Profile>; } #[cfg(all(feature = "v2", feature = "olap"))] #[async_trait::async_trait] impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { async fn create_domain_model_from_request( self, state: &SessionState, key_store: domain::MerchantKeyStore, business_profile: &domain::Profile, key_manager_state: &KeyManagerState, ) -> RouterResult<domain::MerchantConnectorAccount> { // If connector label is not passed in the request, generate one let connector_label = self.get_connector_label(business_profile.profile_name.clone()); let frm_configs = self.get_frm_config_as_secret(); let payment_methods_enabled = self.payment_methods_enabled; // Validate Merchant api details and return error if not in correct format let auth = types::ConnectorAuthType::from_option_secret_value( self.connector_account_details.clone(), ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_account_details".to_string(), expected_format: "auth_type and api_key".to_string(), })?; let connector_auth_type_and_metadata_validation = ConnectorAuthTypeAndMetadataValidation { connector_name: &self.connector_name, auth_type: &auth, connector_meta_data: &self.metadata, }; connector_auth_type_and_metadata_validation.validate_auth_and_metadata_type()?; let connector_status_and_disabled_validation = ConnectorStatusAndDisabledValidation { status: &self.status, disabled: &self.disabled, auth: &auth, current_status: &api_enums::ConnectorStatus::Active, }; let (connector_status, disabled) = connector_status_and_disabled_validation.validate_status_and_disabled()?; let identifier = km_types::Identifier::Merchant(business_profile.merchant_id.clone()); let merchant_recipient_data = if let Some(data) = &self.additional_merchant_data { Some( process_open_banking_connectors( state, &business_profile.merchant_id, &auth, &self.connector_type, &self.connector_name, types::AdditionalMerchantData::foreign_from(data.clone()), &key_store, ) .await?, ) } else { None } .map(|data| { serde_json::to_value(types::AdditionalMerchantData::OpenBankingRecipientData( data, )) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize MerchantRecipientData")?; let encrypted_data = domain_types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), domain_types::CryptoOperation::BatchEncrypt( FromRequestEncryptableMerchantConnectorAccount::to_encryptable( FromRequestEncryptableMerchantConnectorAccount { connector_account_details: self.connector_account_details.ok_or( errors::ApiErrorResponse::MissingRequiredField { field_name: "connector_account_details", }, )?, connector_wallets_details: helpers::get_connector_wallets_details_with_apple_pay_certificates( &self.metadata, &self.connector_wallets_details, ) .await?, additional_merchant_data: merchant_recipient_data.map(Secret::new), }, ), ), identifier.clone(), key_store.key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details".to_string())?; let encrypted_data = FromRequestEncryptableMerchantConnectorAccount::from_encryptable(encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details")?; let feature_metadata = self .feature_metadata .as_ref() .map(ForeignTryFrom::foreign_try_from) .transpose()?; Ok(domain::MerchantConnectorAccount { merchant_id: business_profile.merchant_id.clone(), connector_type: self.connector_type, connector_name: self.connector_name, connector_account_details: encrypted_data.connector_account_details, payment_methods_enabled, disabled, metadata: self.metadata.clone(), frm_configs, connector_label: Some(connector_label.clone()), created_at: date_time::now(), modified_at: date_time::now(), id: common_utils::generate_merchant_connector_account_id_of_default_length(), connector_webhook_details: match self.connector_webhook_details { Some(connector_webhook_details) => { connector_webhook_details.encode_to_value( ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!("Failed to serialize api_models::admin::MerchantConnectorWebhookDetails for Merchant: {:?}", business_profile.merchant_id)) .map(Some)? .map(Secret::new) } None => None, }, profile_id: business_profile.get_id().to_owned(), applepay_verified_domains: None, pm_auth_config: self.pm_auth_config.clone(), status: connector_status, connector_wallets_details: encrypted_data.connector_wallets_details, additional_merchant_data: encrypted_data.additional_merchant_data, version: common_types::consts::API_VERSION, feature_metadata, }) } async fn validate_and_get_business_profile( self, merchant_context: &domain::MerchantContext, db: &dyn StorageInterface, key_manager_state: &KeyManagerState, ) -> RouterResult<domain::Profile> { let profile_id = self.profile_id; // Check whether this profile belongs to the merchant 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(), })?; Ok(business_profile) } } #[cfg(feature = "v1")] struct PaymentMethodsEnabled<'a> { payment_methods_enabled: &'a Option<Vec<api_models::admin::PaymentMethodsEnabled>>, } #[cfg(feature = "v1")] impl PaymentMethodsEnabled<'_> { fn get_payment_methods_enabled(&self) -> RouterResult<Option<Vec<pii::SecretSerdeValue>>> { let mut vec = Vec::new(); let payment_methods_enabled = match self.payment_methods_enabled.clone() { Some(val) => { for pm in val.into_iter() { let pm_value = pm .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed while encoding to serde_json::Value, PaymentMethod", )?; vec.push(Secret::new(pm_value)) } Some(vec) } None => None, }; Ok(payment_methods_enabled) } } #[cfg(all(feature = "v1", feature = "olap"))] #[async_trait::async_trait] impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { async fn create_domain_model_from_request( self, state: &SessionState, key_store: domain::MerchantKeyStore, business_profile: &domain::Profile, key_manager_state: &KeyManagerState, ) -> RouterResult<domain::MerchantConnectorAccount> { // If connector label is not passed in the request, generate one let connector_label = self .connector_label .clone() .or(core_utils::get_connector_label( self.business_country, self.business_label.as_ref(), self.business_sub_label.as_ref(), &self.connector_name.to_string(), )) .unwrap_or(format!( "{}_{}", self.connector_name, business_profile.profile_name )); let payment_methods_enabled = PaymentMethodsEnabled { payment_methods_enabled: &self.payment_methods_enabled, }; let payment_methods_enabled = payment_methods_enabled.get_payment_methods_enabled()?; let frm_configs = self.get_frm_config_as_secret(); // Validate Merchant api details and return error if not in correct format let auth = types::ConnectorAuthType::from_option_secret_value( self.connector_account_details.clone(), ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_account_details".to_string(), expected_format: "auth_type and api_key".to_string(), })?; let connector_auth_type_and_metadata_validation = ConnectorAuthTypeAndMetadataValidation { connector_name: &self.connector_name, auth_type: &auth, connector_meta_data: &self.metadata, }; connector_auth_type_and_metadata_validation.validate_auth_and_metadata_type()?; let connector_status_and_disabled_validation = ConnectorStatusAndDisabledValidation { status: &self.status, disabled: &self.disabled, auth: &auth, current_status: &api_enums::ConnectorStatus::Active, }; let (connector_status, disabled) = connector_status_and_disabled_validation.validate_status_and_disabled()?; let identifier = km_types::Identifier::Merchant(business_profile.merchant_id.clone()); let merchant_recipient_data = if let Some(data) = &self.additional_merchant_data { Some( process_open_banking_connectors( state, &business_profile.merchant_id, &auth, &self.connector_type, &self.connector_name, types::AdditionalMerchantData::foreign_from(data.clone()), &key_store, ) .await?, ) } else { None } .map(|data| { serde_json::to_value(types::AdditionalMerchantData::OpenBankingRecipientData( data, )) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize MerchantRecipientData")?; let encrypted_data = domain_types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), domain_types::CryptoOperation::BatchEncrypt( FromRequestEncryptableMerchantConnectorAccount::to_encryptable( FromRequestEncryptableMerchantConnectorAccount { connector_account_details: self.connector_account_details.ok_or( errors::ApiErrorResponse::MissingRequiredField { field_name: "connector_account_details", }, )?, connector_wallets_details: helpers::get_connector_wallets_details_with_apple_pay_certificates( &self.metadata, &self.connector_wallets_details, ) .await?, additional_merchant_data: merchant_recipient_data.map(Secret::new), }, ), ), identifier.clone(), key_store.key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details".to_string())?; let encrypted_data = FromRequestEncryptableMerchantConnectorAccount::from_encryptable(encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details")?; Ok(domain::MerchantConnectorAccount { merchant_id: business_profile.merchant_id.clone(), connector_type: self.connector_type, connector_name: self.connector_name.to_string(), merchant_connector_id: common_utils::generate_merchant_connector_account_id_of_default_length(), connector_account_details: encrypted_data.connector_account_details, payment_methods_enabled, disabled, metadata: self.metadata.clone(), frm_configs, connector_label: Some(connector_label.clone()), created_at: date_time::now(), modified_at: date_time::now(), connector_webhook_details: match self.connector_webhook_details { Some(connector_webhook_details) => { connector_webhook_details.encode_to_value( ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!("Failed to serialize api_models::admin::MerchantConnectorWebhookDetails for Merchant: {:?}", business_profile.merchant_id)) .map(Some)? .map(Secret::new) } None => None, }, profile_id: business_profile.get_id().to_owned(), applepay_verified_domains: None, pm_auth_config: self.pm_auth_config.clone(), status: connector_status, connector_wallets_details: encrypted_data.connector_wallets_details, test_mode: self.test_mode, business_country: self.business_country, business_label: self.business_label.clone(), business_sub_label: self.business_sub_label.clone(), additional_merchant_data: encrypted_data.additional_merchant_data, version: common_types::consts::API_VERSION, }) } /// If profile_id is not passed, use default profile if available, or /// If business_details (business_country and business_label) are passed, get the business_profile /// or return a `MissingRequiredField` error async fn validate_and_get_business_profile( self, merchant_context: &domain::MerchantContext, db: &dyn StorageInterface, key_manager_state: &KeyManagerState, ) -> RouterResult<domain::Profile> { match self.profile_id.or(merchant_context .get_merchant_account() .default_profile .clone()) { Some(profile_id) => { // Check whether this business profile belongs to the merchant 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(), })?; Ok(business_profile) } None => match self.business_country.zip(self.business_label) { Some((business_country, business_label)) => { let profile_name = format!("{business_country}_{business_label}"); let business_profile = db .find_business_profile_by_profile_name_merchant_id( key_manager_state, merchant_context.get_merchant_key_store(), &profile_name, merchant_context.get_merchant_account().get_id(), ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_name, })?; Ok(business_profile) } _ => Err(report!(errors::ApiErrorResponse::MissingRequiredField { field_name: "profile_id or business_country, business_label" })), }, } } } pub async fn create_connector( state: SessionState, req: api::MerchantConnectorCreate, merchant_context: domain::MerchantContext, auth_profile_id: Option<id_type::ProfileId>, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); #[cfg(feature = "dummy_connector")] fp_utils::when( req.connector_name .validate_dummy_connector_create(state.conf.dummy_connector.enabled), || { Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid connector name".to_string(), }) }, )?; let connector_metadata = ConnectorMetadata { connector_metadata: &req.metadata, }; let merchant_id = merchant_context.get_merchant_account().get_id(); connector_metadata.validate_apple_pay_certificates_in_mca_metadata()?; #[cfg(feature = "v1")] helpers::validate_business_details( req.business_country, req.business_label.as_ref(), &merchant_context, )?; let business_profile = req .clone() .validate_and_get_business_profile(&merchant_context, store, key_manager_state) .await?; #[cfg(feature = "v2")] if req.connector_type == common_enums::ConnectorType::BillingProcessor { 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)?; let pm_auth_config_validation = PMAuthConfigValidation { connector_type: &req.connector_type, pm_auth_config: &req.pm_auth_config, db: store, merchant_id, profile_id: business_profile.get_id(), key_store: merchant_context.get_merchant_key_store(), key_manager_state, }; pm_auth_config_validation.validate_pm_auth_config().await?; let connector_type_and_connector_enum = ConnectorTypeAndConnectorName { connector_type: &req.connector_type, connector_name: &req.connector_name, }; let routable_connector = connector_type_and_connector_enum.get_routable_connector()?; // The purpose of this merchant account update is just to update the // merchant account `modified_at` field for KGraph cache invalidation state .store .update_specific_fields_in_merchant( key_manager_state, merchant_id, storage::MerchantAccountUpdate::ModifiedAtUpdate, merchant_context.get_merchant_key_store(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error updating the merchant account when creating payment connector")?; let merchant_connector_account = req .clone() .create_domain_model_from_request( &state, merchant_context.get_merchant_key_store().clone(), &business_profile, key_manager_state, ) .await?; let mca = state .store .insert_merchant_connector_account( key_manager_state, merchant_connector_account.clone(), merchant_context.get_merchant_key_store(), ) .await .to_duplicate_response( errors::ApiErrorResponse::DuplicateMerchantConnectorAccount { profile_id: business_profile.get_id().get_string_repr().to_owned(), connector_label: merchant_connector_account .connector_label .unwrap_or_default(), }, )?; // redact cgraph cache on new connector creation redact_cgraph_cache(&state, merchant_id, business_profile.get_id()).await?; #[cfg(feature = "v1")] disputes::schedule_dispute_sync_task(&state, &business_profile, &mca).await?; #[cfg(feature = "v1")] //update merchant default config let merchant_default_config_update = MerchantDefaultConfigUpdate { routable_connector: &routable_connector, merchant_connector_id: &mca.get_id(), store, merchant_id, profile_id: business_profile.get_id(), transaction_type: &req.get_transaction_type(), }; #[cfg(feature = "v2")] //update merchant default config let merchant_default_config_update = DefaultFallbackRoutingConfigUpdate { routable_connector: &routable_connector, merchant_connector_id: &mca.get_id(), store, business_profile, key_store: merchant_context.get_merchant_key_store().to_owned(), key_manager_state, }; merchant_default_config_update .retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists() .await?; metrics::MCA_CREATE.add( 1, router_env::metric_attributes!( ("connector", req.connector_name.to_string()), ("merchant", merchant_id.clone()), ), ); let mca_response = mca.foreign_try_into()?; Ok(service_api::ApplicationResponse::Json(mca_response)) } #[cfg(feature = "v1")] async fn validate_pm_auth( val: pii::SecretSerdeValue, state: &SessionState, merchant_id: &id_type::MerchantId, merchant_context: domain::MerchantContext, profile_id: &id_type::ProfileId, ) -> RouterResponse<()> { let config = serde_json::from_value::<api_models::pm_auth::PaymentMethodAuthConfig>(val.expose()) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "invalid data received for payment method auth config".to_string(), }) .attach_printable("Failed to deserialize Payment Method Auth config")?; let all_mcas = state .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( &state.into(), merchant_id, true, merchant_context.get_merchant_key_store(), ) .await .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_context .get_merchant_account() .get_id() .get_string_repr() .to_owned(), })?; for conn_choice in config.enabled_payment_methods { let pm_auth_mca = all_mcas .iter() .find(|mca| mca.get_id() == conn_choice.mca_id) .ok_or(errors::ApiErrorResponse::GenericNotFoundError { message: "payment method auth connector account not found".to_string(), })?; if &pm_auth_mca.profile_id != profile_id { return Err(errors::ApiErrorResponse::GenericNotFoundError { message: "payment method auth profile_id differs from connector profile_id" .to_string(), } .into()); } } Ok(services::ApplicationResponse::StatusOk) } #[cfg(feature = "v1")] pub async fn retrieve_connector( state: SessionState, merchant_id: id_type::MerchantId, profile_id: Option<id_type::ProfileId>, merchant_connector_id: id_type::MerchantConnectorAccountId, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = store .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &store.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let _merchant_account = store .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let mca = store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, &merchant_id, &merchant_connector_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), })?; core_utils::validate_profile_id_from_auth_layer(profile_id, &mca)?; Ok(service_api::ApplicationResponse::Json( mca.foreign_try_into()?, )) } #[cfg(feature = "v2")] pub async fn retrieve_connector( state: SessionState, merchant_context: domain::MerchantContext, id: id_type::MerchantConnectorAccountId, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let mca = store .find_merchant_connector_account_by_id( key_manager_state, &id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: id.clone().get_string_repr().to_string(), })?; // Validate if the merchant_id sent in the request is valid if mca.merchant_id != *merchant_id { return Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Invalid merchant_id {} provided for merchant_connector_account {:?}", merchant_id.get_string_repr(), id ), } .into()); } Ok(service_api::ApplicationResponse::Json( mca.foreign_try_into()?, )) } #[cfg(all(feature = "olap", feature = "v2"))] pub async fn list_connectors_for_a_profile( state: SessionState, key_store: domain::MerchantKeyStore, profile_id: id_type::ProfileId, ) -> RouterResponse<Vec<api_models::admin::MerchantConnectorListResponse>> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_connector_accounts = store .list_connector_account_by_profile_id(key_manager_state, &profile_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; let mut response = vec![]; for mca in merchant_connector_accounts.into_iter() { response.push(mca.foreign_try_into()?); } Ok(service_api::ApplicationResponse::Json(response)) } pub async fn list_payment_connectors( state: SessionState, merchant_id: id_type::MerchantId, profile_id_list: Option<Vec<id_type::ProfileId>>, ) -> RouterResponse<Vec<api_models::admin::MerchantConnectorListResponse>> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = store .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &store.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; // Validate merchant account store .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_connector_accounts = store .find_merchant_connector_account_by_merchant_id_and_disabled_list( key_manager_state, &merchant_id, true, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; let merchant_connector_accounts = core_utils::filter_objects_based_on_profile_id_list( profile_id_list, merchant_connector_accounts, ); let mut response = vec![]; // The can be eliminated once [#79711](https://github.com/rust-lang/rust/issues/79711) is stabilized for mca in merchant_connector_accounts.into_iter() { response.push(mca.foreign_try_into()?); } Ok(service_api::ApplicationResponse::Json(response)) } pub async fn update_connector( state: SessionState, merchant_id: &id_type::MerchantId, profile_id: Option<id_type::ProfileId>, merchant_connector_id: &id_type::MerchantConnectorAccountId, req: api_models::admin::MerchantConnectorUpdate, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let mca = req .clone() .get_merchant_connector_account_from_id( db, merchant_id, merchant_connector_id, &key_store, key_manager_state, ) .await?; core_utils::validate_profile_id_from_auth_layer(profile_id, &mca)?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), key_store.clone(), ))); let payment_connector = req .clone() .create_domain_model_from_request(&state, &mca, key_manager_state, &merchant_context) .await?; // Profile id should always be present let profile_id = mca.profile_id.clone(); let request_connector_label = req.connector_label; let updated_mca = db .update_merchant_connector_account( key_manager_state, mca.clone(), payment_connector.into(), &key_store, ) .await .change_context( errors::ApiErrorResponse::DuplicateMerchantConnectorAccount { profile_id: profile_id.get_string_repr().to_owned(), connector_label: request_connector_label.unwrap_or_default(), }, ) .attach_printable_lazy(|| { format!( "Failed while updating MerchantConnectorAccount: id: {merchant_connector_id:?}", ) })?; // redact cgraph cache on connector updation redact_cgraph_cache(&state, merchant_id, &profile_id).await?; // redact routing cache on connector updation #[cfg(feature = "v1")] let merchant_config = MerchantDefaultConfigUpdate { routable_connector: &Some( common_enums::RoutableConnectors::from_str(&mca.connector_name).map_err(|_| { errors::ApiErrorResponse::InvalidDataValue { field_name: "connector_name", } })?, ), merchant_connector_id: &mca.get_id(), store: db, merchant_id, profile_id: &mca.profile_id, transaction_type: &mca.connector_type.into(), }; #[cfg(feature = "v1")] if req.disabled.unwrap_or(false) { merchant_config .retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists() .await?; } else { merchant_config .retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists() .await?; } let response = updated_mca.foreign_try_into()?; Ok(service_api::ApplicationResponse::Json(response)) } #[cfg(feature = "v1")] pub async fn delete_connector( state: SessionState, merchant_id: id_type::MerchantId, merchant_connector_id: id_type::MerchantConnectorAccountId, ) -> RouterResponse<api::MerchantConnectorDeleteResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let _merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, &merchant_id, &merchant_connector_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), })?; let is_deleted = db .delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &merchant_id, &merchant_connector_id, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), })?; // delete the mca from the config as well let merchant_default_config_delete = MerchantDefaultConfigUpdate { routable_connector: &Some( common_enums::RoutableConnectors::from_str(&mca.connector_name).map_err(|_| { errors::ApiErrorResponse::InvalidDataValue { field_name: "connector_name", } })?, ), merchant_connector_id: &mca.get_id(), store: db, merchant_id: &merchant_id, profile_id: &mca.profile_id, transaction_type: &mca.connector_type.into(), }; merchant_default_config_delete .retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists() .await?; // redact cgraph cache on connector deletion redact_cgraph_cache(&state, &merchant_id, &mca.profile_id).await?; let response = api::MerchantConnectorDeleteResponse { merchant_id, merchant_connector_id, deleted: is_deleted, }; Ok(service_api::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] pub async fn delete_connector( state: SessionState, merchant_context: domain::MerchantContext, id: id_type::MerchantConnectorAccountId, ) -> RouterResponse<api::MerchantConnectorDeleteResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let mca = db .find_merchant_connector_account_by_id( key_manager_state, &id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: id.clone().get_string_repr().to_string(), })?; // Validate if the merchant_id sent in the request is valid if mca.merchant_id != *merchant_id { return Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Invalid merchant_id {} provided for merchant_connector_account {:?}", merchant_id.get_string_repr(), id ), } .into()); } let is_deleted = db .delete_merchant_connector_account_by_id(&id) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: id.clone().get_string_repr().to_string(), })?; let business_profile = db .find_business_profile_by_profile_id( key_manager_state, merchant_context.get_merchant_key_store(), &mca.profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: mca.profile_id.get_string_repr().to_owned(), })?; let merchant_default_config_delete = DefaultFallbackRoutingConfigUpdate { routable_connector: &Some( common_enums::RoutableConnectors::from_str(&mca.connector_name.to_string()).map_err( |_| errors::ApiErrorResponse::InvalidDataValue { field_name: "connector_name", }, )?, ), merchant_connector_id: &mca.get_id(), store: db, business_profile, key_store: merchant_context.get_merchant_key_store().to_owned(), key_manager_state, }; merchant_default_config_delete .retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists() .await?; let response = api::MerchantConnectorDeleteResponse { merchant_id: merchant_id.clone(), id, deleted: is_deleted, }; Ok(service_api::ApplicationResponse::Json(response)) } pub async fn kv_for_merchant( state: SessionState, merchant_id: id_type::MerchantId, enable: bool, ) -> RouterResponse<api_models::admin::ToggleKVResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; // check if the merchant account exists let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let updated_merchant_account = match (enable, merchant_account.storage_scheme) { (true, MerchantStorageScheme::RedisKv) | (false, MerchantStorageScheme::PostgresOnly) => { Ok(merchant_account) } (true, MerchantStorageScheme::PostgresOnly) => { if state.conf.as_ref().is_kv_soft_kill_mode() { Err(errors::ApiErrorResponse::InvalidRequestData { message: "Kv cannot be enabled when application is in soft_kill_mode" .to_owned(), })? } db.update_merchant( key_manager_state, merchant_account, storage::MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme: MerchantStorageScheme::RedisKv, }, &key_store, ) .await } (false, MerchantStorageScheme::RedisKv) => { db.update_merchant( key_manager_state, merchant_account, storage::MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme: MerchantStorageScheme::PostgresOnly, }, &key_store, ) .await } } .map_err(|error| { error .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to switch merchant_storage_scheme") })?; let kv_status = matches!( updated_merchant_account.storage_scheme, MerchantStorageScheme::RedisKv ); Ok(service_api::ApplicationResponse::Json( api_models::admin::ToggleKVResponse { merchant_id: updated_merchant_account.get_id().to_owned(), kv_enabled: kv_status, }, )) } pub async fn toggle_kv_for_all_merchants( state: SessionState, enable: bool, ) -> RouterResponse<api_models::admin::ToggleAllKVResponse> { let db = state.store.as_ref(); let storage_scheme = if enable { MerchantStorageScheme::RedisKv } else { MerchantStorageScheme::PostgresOnly }; let total_update = db .update_all_merchant_account(storage::MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme, }) .await .map_err(|error| { error .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to switch merchant_storage_scheme for all merchants") })?; Ok(service_api::ApplicationResponse::Json( api_models::admin::ToggleAllKVResponse { total_updated: total_update, kv_enabled: enable, }, )) } pub async fn check_merchant_account_kv_status( state: SessionState, merchant_id: id_type::MerchantId, ) -> RouterResponse<api_models::admin::ToggleKVResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; // check if the merchant account exists let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let kv_status = matches!( merchant_account.storage_scheme, MerchantStorageScheme::RedisKv ); Ok(service_api::ApplicationResponse::Json( api_models::admin::ToggleKVResponse { merchant_id: merchant_account.get_id().to_owned(), kv_enabled: kv_status, }, )) } pub fn get_frm_config_as_secret( frm_configs: Option<Vec<api_models::admin::FrmConfigs>>, ) -> Option<Vec<Secret<serde_json::Value>>> { match frm_configs.as_ref() { Some(frm_value) => { let configs_for_frm_value: Vec<Secret<serde_json::Value>> = frm_value .iter() .map(|config| { config .encode_to_value() .change_context(errors::ApiErrorResponse::ConfigNotFound) .map(Secret::new) }) .collect::<Result<Vec<_>, _>>() .ok()?; Some(configs_for_frm_value) } None => None, } } #[cfg(feature = "v1")] pub async fn create_and_insert_business_profile( state: &SessionState, request: api::ProfileCreate, merchant_account: domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<domain::Profile> { let business_profile_new = admin::create_profile_from_merchant_account(state, merchant_account, request, key_store) .await?; let profile_name = business_profile_new.profile_name.clone(); state .store .insert_business_profile(&state.into(), key_store, business_profile_new) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: format!( "Business Profile with the profile_name {profile_name} already exists" ), }) .attach_printable("Failed to insert Business profile because of duplication error") } #[cfg(feature = "olap")] #[async_trait::async_trait] trait ProfileCreateBridge { #[cfg(feature = "v1")] async fn create_domain_model_from_request( self, state: &SessionState, merchant_context: &domain::MerchantContext, ) -> RouterResult<domain::Profile>; #[cfg(feature = "v2")] async fn create_domain_model_from_request( self, state: &SessionState, key: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, ) -> RouterResult<domain::Profile>; } #[cfg(feature = "olap")] #[async_trait::async_trait] impl ProfileCreateBridge for api::ProfileCreate { #[cfg(feature = "v1")] async fn create_domain_model_from_request( self, state: &SessionState, merchant_context: &domain::MerchantContext, ) -> RouterResult<domain::Profile> { use common_utils::ext_traits::AsyncExt; if let Some(session_expiry) = &self.session_expiry { helpers::validate_session_expiry(session_expiry.to_owned())?; } if let Some(intent_fulfillment_expiry) = self.intent_fulfillment_time { helpers::validate_intent_fulfillment_expiry(intent_fulfillment_expiry)?; } if let Some(ref routing_algorithm) = self.routing_algorithm { let _: api_models::routing::StaticRoutingAlgorithm = routing_algorithm .clone() .parse_value("RoutingAlgorithm") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "routing_algorithm", }) .attach_printable("Invalid routing algorithm given")?; } // Generate a unique profile id let profile_id = common_utils::generate_profile_id_of_default_length(); let profile_name = self.profile_name.unwrap_or("default".to_string()); let current_time = date_time::now(); let webhook_details = self.webhook_details.map(ForeignInto::foreign_into); let payment_response_hash_key = self .payment_response_hash_key .or(merchant_context .get_merchant_account() .payment_response_hash_key .clone()) .unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64)); let payment_link_config = self.payment_link_config.map(ForeignInto::foreign_into); let key_manager_state = state.into(); let outgoing_webhook_custom_http_headers = self .outgoing_webhook_custom_http_headers .async_map(|headers| { cards::create_encrypted_data( &key_manager_state, merchant_context.get_merchant_key_store(), headers, ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?; let payout_link_config = self .payout_link_config .map(|payout_conf| match payout_conf.config.validate() { Ok(_) => Ok(payout_conf.foreign_into()), Err(e) => Err(error_stack::report!( errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() } )), }) .transpose()?; let key = merchant_context .get_merchant_key_store() .key .clone() .into_inner(); let key_manager_state = state.into(); let card_testing_secret_key = Some(Secret::new(utils::generate_id( consts::FINGERPRINT_SECRET_LENGTH, "fs", ))); let card_testing_guard_config = self .card_testing_guard_config .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")?; self.merchant_country_code .as_ref() .map(|country_code| country_code.validate_and_get_country_from_merchant_country_code()) .transpose() .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid merchant country code".to_string(), })?; Ok(domain::Profile::from(domain::ProfileSetter { profile_id, merchant_id: merchant_context.get_merchant_account().get_id().clone(), profile_name, created_at: current_time, modified_at: current_time, return_url: self .return_url .map(|return_url| return_url.to_string()) .or(merchant_context.get_merchant_account().return_url.clone()), enable_payment_response_hash: self.enable_payment_response_hash.unwrap_or( merchant_context .get_merchant_account() .enable_payment_response_hash, ), payment_response_hash_key: Some(payment_response_hash_key), redirect_to_merchant_with_http_post: self .redirect_to_merchant_with_http_post .unwrap_or( merchant_context .get_merchant_account() .redirect_to_merchant_with_http_post, ), webhook_details: webhook_details.or(merchant_context .get_merchant_account() .webhook_details .clone()), metadata: self.metadata, routing_algorithm: None, intent_fulfillment_time: self .intent_fulfillment_time .map(i64::from) .or(merchant_context .get_merchant_account() .intent_fulfillment_time) .or(Some(common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME)), frm_routing_algorithm: self.frm_routing_algorithm.or(merchant_context .get_merchant_account() .frm_routing_algorithm .clone()), #[cfg(feature = "payouts")] payout_routing_algorithm: self.payout_routing_algorithm.or(merchant_context .get_merchant_account() .payout_routing_algorithm .clone()), #[cfg(not(feature = "payouts"))] payout_routing_algorithm: None, is_recon_enabled: merchant_context.get_merchant_account().is_recon_enabled, applepay_verified_domains: self.applepay_verified_domains, payment_link_config, session_expiry: self .session_expiry .map(i64::from) .or(Some(common_utils::consts::DEFAULT_SESSION_EXPIRY)), authentication_connector_details: self .authentication_connector_details .map(ForeignInto::foreign_into), payout_link_config, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, is_extended_card_info_enabled: None, extended_card_info_config: None, use_billing_as_payment_method_billing: self .use_billing_as_payment_method_billing .or(Some(true)), collect_shipping_details_from_wallet_connector: self .collect_shipping_details_from_wallet_connector .or(Some(false)), collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector .or(Some(false)), outgoing_webhook_custom_http_headers, tax_connector_id: self.tax_connector_id, is_tax_connector_enabled: self.is_tax_connector_enabled, always_collect_billing_details_from_wallet_connector: self .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: 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), always_request_extended_authorization: self.always_request_extended_authorization, is_click_to_pay_enabled: self.is_click_to_pay_enabled, authentication_product_ids: self.authentication_product_ids, card_testing_guard_config, card_testing_secret_key: card_testing_secret_key .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, common_utils::type_name!(domain::Profile), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating card testing secret key")?, is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled.unwrap_or_default(), force_3ds_challenge: self.force_3ds_challenge.unwrap_or_default(), is_debit_routing_enabled: self.is_debit_routing_enabled.unwrap_or_default(), 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 .unwrap_or_default(), merchant_category_code: self.merchant_category_code, merchant_country_code: self.merchant_country_code, dispute_polling_interval: self.dispute_polling_interval, is_manual_retry_enabled: self.is_manual_retry_enabled, always_enable_overcapture: self.always_enable_overcapture, external_vault_details: domain::ExternalVaultDetails::try_from(( self.is_external_vault_enabled, self.external_vault_connector_details .map(ForeignFrom::foreign_from), )) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating external vault details")?, billing_processor_id: self.billing_processor_id, is_l2_l3_enabled: self.is_l2_l3_enabled.unwrap_or(false), })) } #[cfg(feature = "v2")] async fn create_domain_model_from_request( self, state: &SessionState, key_store: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, ) -> RouterResult<domain::Profile> { if let Some(session_expiry) = &self.session_expiry { helpers::validate_session_expiry(session_expiry.to_owned())?; } // Generate a unique profile id // TODO: the profile_id should be generated from the profile_name let profile_id = common_utils::generate_profile_id_of_default_length(); let profile_name = self.profile_name; let current_time = date_time::now(); let webhook_details = self.webhook_details.map(ForeignInto::foreign_into); let payment_response_hash_key = self .payment_response_hash_key .unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64)); let payment_link_config = self.payment_link_config.map(ForeignInto::foreign_into); let key_manager_state = state.into(); let outgoing_webhook_custom_http_headers = self .outgoing_webhook_custom_http_headers .async_map(|headers| { cards::create_encrypted_data(&key_manager_state, key_store, headers) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?; let payout_link_config = self .payout_link_config .map(|payout_conf| match payout_conf.config.validate() { Ok(_) => Ok(payout_conf.foreign_into()), Err(e) => Err(error_stack::report!( errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() } )), }) .transpose()?; let key = key_store.key.clone().into_inner(); let key_manager_state = state.into(); let card_testing_secret_key = Some(Secret::new(utils::generate_id( consts::FINGERPRINT_SECRET_LENGTH, "fs", ))); let card_testing_guard_config = self .card_testing_guard_config .map(CardTestingGuardConfig::foreign_from) .or(Some(CardTestingGuardConfig::default())); Ok(domain::Profile::from(domain::ProfileSetter { id: profile_id, merchant_id: merchant_id.clone(), profile_name, created_at: current_time, modified_at: current_time, return_url: self.return_url, enable_payment_response_hash: self.enable_payment_response_hash.unwrap_or(true), payment_response_hash_key: Some(payment_response_hash_key), redirect_to_merchant_with_http_post: self .redirect_to_merchant_with_http_post .unwrap_or(true), webhook_details, metadata: self.metadata, is_recon_enabled: false, applepay_verified_domains: self.applepay_verified_domains, payment_link_config, session_expiry: self .session_expiry .map(i64::from) .or(Some(common_utils::consts::DEFAULT_SESSION_EXPIRY)), authentication_connector_details: self .authentication_connector_details .map(ForeignInto::foreign_into), payout_link_config, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, is_extended_card_info_enabled: None, extended_card_info_config: None, use_billing_as_payment_method_billing: self .use_billing_as_payment_method_billing .or(Some(true)), collect_shipping_details_from_wallet_connector: self .collect_shipping_details_from_wallet_connector_if_required .or(Some(false)), collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector_if_required .or(Some(false)), outgoing_webhook_custom_http_headers, always_collect_billing_details_from_wallet_connector: self .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self .always_collect_shipping_details_from_wallet_connector, routing_algorithm_id: None, frm_routing_algorithm_id: None, payout_routing_algorithm_id: None, order_fulfillment_time: self .order_fulfillment_time .map(|order_fulfillment_time| order_fulfillment_time.into_inner()) .or(Some(common_utils::consts::DEFAULT_ORDER_FULFILLMENT_TIME)), order_fulfillment_time_origin: self.order_fulfillment_time_origin, default_fallback_routing: None, should_collect_cvv_during_payment: None, tax_connector_id: self.tax_connector_id, is_tax_connector_enabled: self.is_tax_connector_enabled, is_network_tokenization_enabled: self.is_network_tokenization_enabled, is_click_to_pay_enabled: self.is_click_to_pay_enabled, authentication_product_ids: self.authentication_product_ids, three_ds_decision_manager_config: None, card_testing_guard_config, card_testing_secret_key: card_testing_secret_key .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, common_utils::type_name!(domain::Profile), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating card testing secret key")?, is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled.unwrap_or_default(), is_debit_routing_enabled: self.is_debit_routing_enabled.unwrap_or_default(), merchant_business_country: self.merchant_business_country, revenue_recovery_retry_algorithm_type: None, revenue_recovery_retry_algorithm_data: None, is_iframe_redirection_enabled: None, is_external_vault_enabled: self.is_external_vault_enabled, external_vault_connector_details: self .external_vault_connector_details .map(ForeignInto::foreign_into), merchant_category_code: self.merchant_category_code, merchant_country_code: self.merchant_country_code, split_txns_enabled: self.split_txns_enabled.unwrap_or_default(), billing_processor_id: self.billing_processor_id, })) } } #[cfg(feature = "olap")] pub async fn create_profile( state: SessionState, request: api::ProfileCreate, merchant_context: domain::MerchantContext, ) -> RouterResponse<api_models::admin::ProfileResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); #[cfg(feature = "v1")] let business_profile = request .create_domain_model_from_request(&state, &merchant_context) .await?; #[cfg(feature = "v2")] let business_profile = request .create_domain_model_from_request( &state, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().get_id(), ) .await?; let profile_id = business_profile.get_id().to_owned(); let business_profile = db .insert_business_profile( key_manager_state, merchant_context.get_merchant_key_store(), business_profile, ) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: format!( "Business Profile with the profile_id {} already exists", profile_id.get_string_repr() ), }) .attach_printable("Failed to insert Business profile because of duplication error")?; #[cfg(feature = "v1")] if merchant_context .get_merchant_account() .default_profile .is_some() { let unset_default_profile = domain::MerchantAccountUpdate::UnsetDefaultProfile; db.update_merchant( key_manager_state, merchant_context.get_merchant_account().clone(), unset_default_profile, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; } Ok(service_api::ApplicationResponse::Json( api_models::admin::ProfileResponse::foreign_try_from(business_profile) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details")?, )) } #[cfg(feature = "olap")] pub async fn list_profile( state: SessionState, merchant_id: id_type::MerchantId, profile_id_list: Option<Vec<id_type::ProfileId>>, ) -> RouterResponse<Vec<api_models::admin::ProfileResponse>> { let db = state.store.as_ref(); let key_store = db .get_merchant_key_store_by_merchant_id( &(&state).into(), &merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let profiles = db .list_profile_by_merchant_id(&(&state).into(), &key_store, &merchant_id) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)? .clone(); let profiles = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, profiles); let mut business_profiles = Vec::new(); for profile in profiles { let business_profile = api_models::admin::ProfileResponse::foreign_try_from(profile) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details")?; business_profiles.push(business_profile); } Ok(service_api::ApplicationResponse::Json(business_profiles)) } pub async fn retrieve_profile( state: SessionState, profile_id: id_type::ProfileId, key_store: domain::MerchantKeyStore, ) -> RouterResponse<api_models::admin::ProfileResponse> { let db = state.store.as_ref(); let business_profile = db .find_business_profile_by_profile_id(&(&state).into(), &key_store, &profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(service_api::ApplicationResponse::Json( api_models::admin::ProfileResponse::foreign_try_from(business_profile) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details")?, )) } pub async fn delete_profile( state: SessionState, profile_id: id_type::ProfileId, merchant_id: &id_type::MerchantId, ) -> RouterResponse<bool> { let db = state.store.as_ref(); let delete_result = db .delete_profile_by_profile_id_merchant_id(&profile_id, merchant_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(service_api::ApplicationResponse::Json(delete_result)) } #[cfg(feature = "olap")] #[async_trait::async_trait] trait ProfileUpdateBridge { async fn get_update_profile_object( self, state: &SessionState, key_store: &domain::MerchantKeyStore, business_profile: &domain::Profile, ) -> RouterResult<domain::ProfileUpdate>; } #[cfg(all(feature = "olap", feature = "v1"))] #[async_trait::async_trait] impl ProfileUpdateBridge for api::ProfileUpdate { async fn get_update_profile_object( self, state: &SessionState, key_store: &domain::MerchantKeyStore, business_profile: &domain::Profile, ) -> RouterResult<domain::ProfileUpdate> { if let Some(session_expiry) = &self.session_expiry { helpers::validate_session_expiry(session_expiry.to_owned())?; } if let Some(intent_fulfillment_expiry) = self.intent_fulfillment_time { helpers::validate_intent_fulfillment_expiry(intent_fulfillment_expiry)?; } let webhook_details = self.webhook_details.map(ForeignInto::foreign_into); if let Some(ref routing_algorithm) = self.routing_algorithm { let _: api_models::routing::StaticRoutingAlgorithm = routing_algorithm .clone() .parse_value("RoutingAlgorithm") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "routing_algorithm", }) .attach_printable("Invalid routing algorithm given")?; } let payment_link_config = self .payment_link_config .map(|payment_link_conf| match payment_link_conf.validate() { Ok(_) => Ok(payment_link_conf.foreign_into()), Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() })), }) .transpose()?; let extended_card_info_config = self .extended_card_info_config .as_ref() .map(|config| { config.encode_to_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "extended_card_info_config", }, ) }) .transpose()? .map(Secret::new); let key_manager_state = state.into(); let outgoing_webhook_custom_http_headers = self .outgoing_webhook_custom_http_headers .async_map(|headers| { cards::create_encrypted_data(&key_manager_state, key_store, headers) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?; let payout_link_config = self .payout_link_config .map(|payout_conf| match payout_conf.config.validate() { Ok(_) => Ok(payout_conf.foreign_into()), Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() })), }) .transpose()?; let key = key_store.key.clone().into_inner(); let key_manager_state = state.into(); let card_testing_secret_key = match business_profile.card_testing_secret_key { Some(_) => None, None => { let card_testing_secret_key = Some(Secret::new(utils::generate_id( consts::FINGERPRINT_SECRET_LENGTH, "fs", ))); card_testing_secret_key .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, common_utils::type_name!(domain::Profile), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating card testing secret key")? } }; 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 }; self.merchant_country_code .as_ref() .map(|country_code| country_code.validate_and_get_country_from_merchant_country_code()) .transpose() .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid merchant country code".to_string(), })?; Ok(domain::ProfileUpdate::Update(Box::new( domain::ProfileGeneralUpdate { profile_name: self.profile_name, return_url: self.return_url.map(|return_url| return_url.to_string()), enable_payment_response_hash: self.enable_payment_response_hash, payment_response_hash_key: self.payment_response_hash_key, redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, webhook_details, metadata: self.metadata, routing_algorithm: self.routing_algorithm, intent_fulfillment_time: self.intent_fulfillment_time.map(i64::from), frm_routing_algorithm: self.frm_routing_algorithm, #[cfg(feature = "payouts")] payout_routing_algorithm: self.payout_routing_algorithm, #[cfg(not(feature = "payouts"))] payout_routing_algorithm: None, applepay_verified_domains: self.applepay_verified_domains, payment_link_config, session_expiry: self.session_expiry.map(i64::from), authentication_connector_details: self .authentication_connector_details .map(ForeignInto::foreign_into), payout_link_config, extended_card_info_config, use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector: self .collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, outgoing_webhook_custom_http_headers, always_collect_billing_details_from_wallet_connector: self .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self .always_collect_shipping_details_from_wallet_connector, always_request_extended_authorization: self.always_request_extended_authorization, tax_connector_id: self.tax_connector_id, is_tax_connector_enabled: self.is_tax_connector_enabled, 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), is_click_to_pay_enabled: self.is_click_to_pay_enabled, authentication_product_ids: self.authentication_product_ids, card_testing_guard_config: self .card_testing_guard_config .map(ForeignInto::foreign_into), 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, 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, merchant_country_code: self.merchant_country_code, dispute_polling_interval: self.dispute_polling_interval, is_manual_retry_enabled: self.is_manual_retry_enabled, always_enable_overcapture: self.always_enable_overcapture, is_external_vault_enabled: self.is_external_vault_enabled, external_vault_connector_details: self .external_vault_connector_details .map(ForeignInto::foreign_into), billing_processor_id: self.billing_processor_id, is_l2_l3_enabled: self.is_l2_l3_enabled, }, ))) } } #[cfg(all(feature = "olap", feature = "v2"))] #[async_trait::async_trait] impl ProfileUpdateBridge for api::ProfileUpdate { async fn get_update_profile_object( self, state: &SessionState, key_store: &domain::MerchantKeyStore, business_profile: &domain::Profile, ) -> RouterResult<domain::ProfileUpdate> { if let Some(session_expiry) = &self.session_expiry { helpers::validate_session_expiry(session_expiry.to_owned())?; } let webhook_details = self.webhook_details.map(ForeignInto::foreign_into); let payment_link_config = self .payment_link_config .map(|payment_link_conf| match payment_link_conf.validate() { Ok(_) => Ok(payment_link_conf.foreign_into()), Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() })), }) .transpose()?; let extended_card_info_config = self .extended_card_info_config .as_ref() .map(|config| { config.encode_to_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "extended_card_info_config", }, ) }) .transpose()? .map(Secret::new); let key_manager_state = state.into(); let outgoing_webhook_custom_http_headers = self .outgoing_webhook_custom_http_headers .async_map(|headers| { cards::create_encrypted_data(&key_manager_state, key_store, headers) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?; let payout_link_config = self .payout_link_config .map(|payout_conf| match payout_conf.config.validate() { Ok(_) => Ok(payout_conf.foreign_into()), Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() })), }) .transpose()?; let key = key_store.key.clone().into_inner(); let key_manager_state = state.into(); let card_testing_secret_key = match business_profile.card_testing_secret_key { Some(_) => None, None => { let card_testing_secret_key = Some(Secret::new(utils::generate_id( consts::FINGERPRINT_SECRET_LENGTH, "fs", ))); card_testing_secret_key .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, common_utils::type_name!(domain::Profile), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating card testing secret key")? } }; let revenue_recovery_retry_algorithm_type = self.revenue_recovery_retry_algorithm_type; Ok(domain::ProfileUpdate::Update(Box::new( domain::ProfileGeneralUpdate { profile_name: self.profile_name, return_url: self.return_url, enable_payment_response_hash: self.enable_payment_response_hash, payment_response_hash_key: self.payment_response_hash_key, redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, webhook_details, metadata: self.metadata, applepay_verified_domains: self.applepay_verified_domains, payment_link_config, session_expiry: self.session_expiry.map(i64::from), authentication_connector_details: self .authentication_connector_details .map(ForeignInto::foreign_into), payout_link_config, extended_card_info_config, use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector: self .collect_shipping_details_from_wallet_connector_if_required, collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector_if_required, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, outgoing_webhook_custom_http_headers, order_fulfillment_time: self .order_fulfillment_time .map(|order_fulfillment_time| order_fulfillment_time.into_inner()), order_fulfillment_time_origin: self.order_fulfillment_time_origin, always_collect_billing_details_from_wallet_connector: self .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self .always_collect_shipping_details_from_wallet_connector, is_network_tokenization_enabled: self.is_network_tokenization_enabled, is_click_to_pay_enabled: self.is_click_to_pay_enabled, authentication_product_ids: self.authentication_product_ids, three_ds_decision_manager_config: None, card_testing_guard_config: self .card_testing_guard_config .map(ForeignInto::foreign_into), card_testing_secret_key, 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, external_vault_connector_details: self .external_vault_connector_details .map(ForeignInto::foreign_into), merchant_category_code: self.merchant_category_code, merchant_country_code: self.merchant_country_code, revenue_recovery_retry_algorithm_type, split_txns_enabled: self.split_txns_enabled, billing_processor_id: self.billing_processor_id, }, ))) } } #[cfg(feature = "olap")] pub async fn update_profile( state: SessionState, profile_id: &id_type::ProfileId, key_store: domain::MerchantKeyStore, request: api::ProfileUpdate, ) -> RouterResponse<api::ProfileResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let business_profile = db .find_business_profile_by_profile_id(key_manager_state, &key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let profile_update = request .get_update_profile_object(&state, &key_store, &business_profile) .await?; let updated_business_profile = db .update_profile_by_profile_id( key_manager_state, &key_store, business_profile, profile_update, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(service_api::ApplicationResponse::Json( api_models::admin::ProfileResponse::foreign_try_from(updated_business_profile) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details")?, )) } #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub struct ProfileWrapper { pub profile: domain::Profile, } #[cfg(feature = "v2")] impl ProfileWrapper { pub fn new(profile: domain::Profile) -> Self { Self { profile } } fn get_routing_config_cache_key(self) -> storage_impl::redis::cache::CacheKind<'static> { let merchant_id = self.profile.merchant_id.clone(); let profile_id = self.profile.get_id().to_owned(); storage_impl::redis::cache::CacheKind::Routing( format!( "routing_config_{}_{}", merchant_id.get_string_repr(), profile_id.get_string_repr() ) .into(), ) } pub async fn update_profile_and_invalidate_routing_config_for_active_algorithm_id_update( self, db: &dyn StorageInterface, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, algorithm_id: id_type::RoutingId, transaction_type: &storage::enums::TransactionType, ) -> RouterResult<()> { let routing_cache_key = self.clone().get_routing_config_cache_key(); let (routing_algorithm_id, payout_routing_algorithm_id) = match transaction_type { storage::enums::TransactionType::Payment => (Some(algorithm_id), None), #[cfg(feature = "payouts")] storage::enums::TransactionType::Payout => (None, Some(algorithm_id)), //TODO: Handle ThreeDsAuthentication Transaction Type for Three DS Decision Rule Algorithm configuration storage::enums::TransactionType::ThreeDsAuthentication => todo!(), }; let profile_update = domain::ProfileUpdate::RoutingAlgorithmUpdate { routing_algorithm_id, payout_routing_algorithm_id, }; let profile = self.profile; 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 routing algorithm ref in business profile")?; storage_impl::redis::cache::redact_from_redis_and_publish( db.get_cache_store().as_ref(), [routing_cache_key], ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to invalidate routing cache")?; Ok(()) } pub fn get_routing_algorithm_id<'a>( &'a self, transaction_data: &'a routing::TransactionData<'_>, ) -> Option<id_type::RoutingId> { match transaction_data { routing::TransactionData::Payment(_) => self.profile.routing_algorithm_id.clone(), #[cfg(feature = "payouts")] routing::TransactionData::Payout(_) => self.profile.payout_routing_algorithm_id.clone(), } } pub fn get_default_fallback_list_of_connector_under_profile( &self, ) -> RouterResult<Vec<routing_types::RoutableConnectorChoice>> { let fallback_connectors = if let Some(default_fallback_routing) = self.profile.default_fallback_routing.clone() { default_fallback_routing .expose() .parse_value::<Vec<routing_types::RoutableConnectorChoice>>( "Vec<RoutableConnectorChoice>", ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Business Profile default config has invalid structure")? } else { Vec::new() }; Ok(fallback_connectors) } pub fn get_default_routing_configs_from_profile( &self, ) -> RouterResult<routing_types::ProfileDefaultRoutingConfig> { let profile_id = self.profile.get_id().to_owned(); let connectors = self.get_default_fallback_list_of_connector_under_profile()?; Ok(routing_types::ProfileDefaultRoutingConfig { profile_id, connectors, }) } pub async fn update_default_fallback_routing_of_connectors_under_profile( self, db: &dyn StorageInterface, updated_config: &Vec<routing_types::RoutableConnectorChoice>, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, ) -> RouterResult<()> { let default_fallback_routing = Secret::from( updated_config .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert routing ref to value")?, ); let profile_update = domain::ProfileUpdate::DefaultRoutingFallbackUpdate { default_fallback_routing: Some(default_fallback_routing), }; 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 routing algorithm ref in business profile")?; Ok(()) } 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, 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( state: SessionState, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, ext_card_info_choice: admin_types::ExtendedCardInfoChoice, ) -> RouterResponse<admin_types::ExtendedCardInfoChoice> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .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(errors::ApiErrorResponse::MerchantAccountNotFound) .attach_printable("Error while fetching the key store by merchant_id")?; let business_profile = db .find_business_profile_by_profile_id(key_manager_state, &key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; if business_profile.is_extended_card_info_enabled.is_none() || business_profile .is_extended_card_info_enabled .is_some_and(|existing_config| existing_config != ext_card_info_choice.enabled) { let profile_update = domain::ProfileUpdate::ExtendedCardInfoUpdate { is_extended_card_info_enabled: ext_card_info_choice.enabled, }; db.update_profile_by_profile_id( key_manager_state, &key_store, business_profile, profile_update, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; } Ok(service_api::ApplicationResponse::Json(ext_card_info_choice)) } pub async fn connector_agnostic_mit_toggle( state: SessionState, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, connector_agnostic_mit_choice: admin_types::ConnectorAgnosticMitChoice, ) -> RouterResponse<admin_types::ConnectorAgnosticMitChoice> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .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(errors::ApiErrorResponse::MerchantAccountNotFound) .attach_printable("Error while fetching the key store by merchant_id")?; let business_profile = db .find_business_profile_by_profile_id(key_manager_state, &key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; if business_profile.merchant_id != *merchant_id { Err(errors::ApiErrorResponse::AccessForbidden { resource: profile_id.get_string_repr().to_owned(), })? } if business_profile.is_connector_agnostic_mit_enabled != Some(connector_agnostic_mit_choice.enabled) { let profile_update = domain::ProfileUpdate::ConnectorAgnosticMitUpdate { is_connector_agnostic_mit_enabled: connector_agnostic_mit_choice.enabled, }; db.update_profile_by_profile_id( key_manager_state, &key_store, business_profile, profile_update, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; } Ok(service_api::ApplicationResponse::Json( connector_agnostic_mit_choice, )) } pub async fn transfer_key_store_to_key_manager( state: SessionState, req: admin_types::MerchantKeyTransferRequest, ) -> RouterResponse<admin_types::TransferKeyResponse> { let resp = transfer_encryption_key(&state, req).await?; Ok(service_api::ApplicationResponse::Json( admin_types::TransferKeyResponse { total_transferred: resp, }, )) } async fn process_open_banking_connectors( state: &SessionState, merchant_id: &id_type::MerchantId, auth: &types::ConnectorAuthType, connector_type: &api_enums::ConnectorType, connector: &api_enums::Connector, additional_merchant_data: types::AdditionalMerchantData, key_store: &domain::MerchantKeyStore, ) -> RouterResult<types::MerchantRecipientData> { let new_merchant_data = match additional_merchant_data { types::AdditionalMerchantData::OpenBankingRecipientData(merchant_data) => { if connector_type != &api_enums::ConnectorType::PaymentProcessor { return Err(errors::ApiErrorResponse::InvalidConnectorConfiguration { config: "OpenBanking connector for Payment Initiation should be a payment processor" .to_string(), } .into()); } match &merchant_data { types::MerchantRecipientData::AccountData(acc_data) => { core_utils::validate_bank_account_data(acc_data)?; let connector_name = api_enums::Connector::to_string(connector); let recipient_creation_not_supported = state .conf .locker_based_open_banking_connectors .connector_list .contains(connector_name.as_str()); let recipient_id = if recipient_creation_not_supported { locker_recipient_create_call(state, merchant_id, acc_data, key_store).await } else { connector_recipient_create_call( state, merchant_id, connector_name, auth, acc_data, ) .await } .attach_printable("failed to get recipient_id")?; let conn_recipient_id = if recipient_creation_not_supported { Some(types::RecipientIdType::LockerId(Secret::new(recipient_id))) } else { Some(types::RecipientIdType::ConnectorId(Secret::new( recipient_id, ))) }; let account_data = match &acc_data { types::MerchantAccountData::Iban { iban, name, .. } => { types::MerchantAccountData::Iban { iban: iban.clone(), name: name.clone(), connector_recipient_id: conn_recipient_id.clone(), } } types::MerchantAccountData::Bacs { account_number, sort_code, name, .. } => types::MerchantAccountData::Bacs { account_number: account_number.clone(), sort_code: sort_code.clone(), name: name.clone(), connector_recipient_id: conn_recipient_id.clone(), }, types::MerchantAccountData::FasterPayments { account_number, sort_code, name, .. } => types::MerchantAccountData::FasterPayments { account_number: account_number.clone(), sort_code: sort_code.clone(), name: name.clone(), connector_recipient_id: conn_recipient_id.clone(), }, types::MerchantAccountData::Sepa { iban, name, .. } => { types::MerchantAccountData::Sepa { iban: iban.clone(), name: name.clone(), connector_recipient_id: conn_recipient_id.clone(), } } types::MerchantAccountData::SepaInstant { iban, name, .. } => { types::MerchantAccountData::SepaInstant { iban: iban.clone(), name: name.clone(), connector_recipient_id: conn_recipient_id.clone(), } } types::MerchantAccountData::Elixir { account_number, iban, name, .. } => types::MerchantAccountData::Elixir { account_number: account_number.clone(), iban: iban.clone(), name: name.clone(), connector_recipient_id: conn_recipient_id.clone(), }, types::MerchantAccountData::Bankgiro { number, name, .. } => { types::MerchantAccountData::Bankgiro { number: number.clone(), name: name.clone(), connector_recipient_id: conn_recipient_id.clone(), } } types::MerchantAccountData::Plusgiro { number, name, .. } => { types::MerchantAccountData::Plusgiro { number: number.clone(), name: name.clone(), connector_recipient_id: conn_recipient_id.clone(), } } }; types::MerchantRecipientData::AccountData(account_data) } _ => merchant_data.clone(), } } }; Ok(new_merchant_data) } async fn connector_recipient_create_call( state: &SessionState, merchant_id: &id_type::MerchantId, connector_name: String, auth: &types::ConnectorAuthType, data: &types::MerchantAccountData, ) -> RouterResult<String> { let connector = pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name( connector_name.as_str(), )?; let auth = pm_auth_types::ConnectorAuthType::foreign_try_from(auth.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while converting ConnectorAuthType")?; let connector_integration: pm_auth_types::api::BoxedConnectorIntegration< '_, pm_auth_types::api::auth_service::RecipientCreate, pm_auth_types::RecipientCreateRequest, pm_auth_types::RecipientCreateResponse, > = connector.connector.get_connector_integration(); let req = pm_auth_types::RecipientCreateRequest::from(data); let router_data = pm_auth_types::RecipientCreateRouterData { flow: std::marker::PhantomData, merchant_id: Some(merchant_id.to_owned()), connector: Some(connector_name), request: req, response: Err(pm_auth_types::ErrorResponse { status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(), code: consts::NO_ERROR_CODE.to_string(), message: consts::UNSUPPORTED_ERROR_MESSAGE.to_string(), reason: None, }), connector_http_status_code: None, connector_auth_type: auth, }; let resp = payment_initiation_service::execute_connector_processing_step( state, connector_integration, &router_data, &connector.connector_name, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while calling recipient create connector api")?; let recipient_create_resp = resp.response .map_err(|err| errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: connector.connector_name.to_string(), status_code: err.status_code, reason: err.reason, })?; let recipient_id = recipient_create_resp.recipient_id; Ok(recipient_id) } async fn locker_recipient_create_call( state: &SessionState, merchant_id: &id_type::MerchantId, data: &types::MerchantAccountData, key_store: &domain::MerchantKeyStore, ) -> RouterResult<String> { let key_manager_state = &state.into(); let key = key_store.key.get_inner().peek(); let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone()); let data_json = serde_json::to_string(data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize MerchantAccountData to JSON")?; let encrypted_data = domain_types::crypto_operation( key_manager_state, type_name!(payment_method::PaymentMethod), domain_types::CryptoOperation::Encrypt(Secret::<String, masking::WithType>::new(data_json)), identifier, key, ) .await .and_then(|val| val.try_into_operation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encrypt merchant account data")?; let enc_data = hex::encode(encrypted_data.into_encrypted().expose()); let merchant_id_string = merchant_id.get_string_repr().to_owned(); let cust_id = id_type::CustomerId::try_from(std::borrow::Cow::from(merchant_id_string)) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert to CustomerId")?; let payload = transformers::StoreLockerReq::LockerGeneric(transformers::StoreGenericReq { merchant_id: merchant_id.to_owned(), merchant_customer_id: cust_id.clone(), enc_data, ttl: state.conf.locker.ttl_for_storage_in_secs, }); let store_resp = cards::add_card_to_hs_locker( state, &payload, &cust_id, api_enums::LockerChoice::HyperswitchCardVault, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encrypt merchant bank account data")?; Ok(store_resp.card_reference) } pub async fn enable_platform_account( state: SessionState, merchant_id: id_type::MerchantId, ) -> RouterResponse<()> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; db.update_merchant( key_manager_state, merchant_account, storage::MerchantAccountUpdate::ToPlatformAccount, &key_store, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while enabling platform merchant account") .map(|_| services::ApplicationResponse::StatusOk) } impl From<&types::MerchantAccountData> for pm_auth_types::RecipientCreateRequest { fn from(data: &types::MerchantAccountData) -> Self { let (name, account_data) = match data { types::MerchantAccountData::Iban { iban, name, .. } => ( name.clone(), pm_auth_types::RecipientAccountData::Iban(iban.clone()), ), types::MerchantAccountData::Bacs { account_number, sort_code, name, .. } => ( name.clone(), pm_auth_types::RecipientAccountData::Bacs { sort_code: sort_code.clone(), account_number: account_number.clone(), }, ), types::MerchantAccountData::FasterPayments { account_number, sort_code, name, .. } => ( name.clone(), pm_auth_types::RecipientAccountData::FasterPayments { sort_code: sort_code.clone(), account_number: account_number.clone(), }, ), types::MerchantAccountData::Sepa { iban, name, .. } => ( name.clone(), pm_auth_types::RecipientAccountData::Sepa(iban.clone()), ), types::MerchantAccountData::SepaInstant { iban, name, .. } => ( name.clone(), pm_auth_types::RecipientAccountData::SepaInstant(iban.clone()), ), types::MerchantAccountData::Elixir { account_number, iban, name, .. } => ( name.clone(), pm_auth_types::RecipientAccountData::Elixir { account_number: account_number.clone(), iban: iban.clone(), }, ), types::MerchantAccountData::Bankgiro { number, name, .. } => ( name.clone(), pm_auth_types::RecipientAccountData::Bankgiro(number.clone()), ), types::MerchantAccountData::Plusgiro { number, name, .. } => ( name.clone(), pm_auth_types::RecipientAccountData::Plusgiro(number.clone()), ), }; Self { name, account_data, address: None, } } }
{ "crate": "router", "file": "crates/router/src/core/admin.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_7447241032061784322
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/api_locking.rs // Contains: 1 structs, 2 enums use std::fmt::Debug; use actix_web::rt::time as actix_time; use error_stack::{report, ResultExt}; use redis_interface::{self as redis, RedisKey}; use router_env::{instrument, logger, tracing}; use super::errors::{self, RouterResult}; use crate::routes::{app::SessionStateInfo, lock_utils}; pub const API_LOCK_PREFIX: &str = "API_LOCK"; #[derive(Clone, Debug, Eq, PartialEq)] pub enum LockStatus { // status when the lock is acquired by the caller Acquired, // [#2129] pick up request_id from AppState and populate here // status when the lock is acquired by some other caller Busy, } #[derive(Clone, Debug)] pub enum LockAction { // Sleep until the lock is acquired Hold { input: LockingInput }, // Sleep until all locks are acquired HoldMultiple { inputs: Vec<LockingInput> }, // Queue it but return response as 2xx, could be used for webhooks QueueWithOk, // Return Error Drop, // Locking Not applicable NotApplicable, } #[derive(Clone, Debug)] pub struct LockingInput { pub unique_locking_key: String, pub api_identifier: lock_utils::ApiIdentifier, pub override_lock_retries: Option<u32>, } impl LockingInput { fn get_redis_locking_key(&self, merchant_id: &common_utils::id_type::MerchantId) -> String { format!( "{}_{}_{}_{}", API_LOCK_PREFIX, merchant_id.get_string_repr(), self.api_identifier, self.unique_locking_key ) } } impl LockAction { #[instrument(skip_all)] pub async fn perform_locking_action<A>( self, state: &A, merchant_id: common_utils::id_type::MerchantId, ) -> RouterResult<()> where A: SessionStateInfo, { match self { Self::HoldMultiple { inputs } => { let lock_retries = inputs .iter() .find_map(|input| input.override_lock_retries) .unwrap_or(state.conf().lock_settings.lock_retries); let request_id = state.get_request_id(); let redis_lock_expiry_seconds = state.conf().lock_settings.redis_lock_expiry_seconds; let redis_conn = state .store() .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError)?; let redis_key_values = inputs .iter() .map(|input| input.get_redis_locking_key(&merchant_id)) .map(|key| (RedisKey::from(key.as_str()), request_id.clone())) .collect::<Vec<_>>(); let delay_between_retries_in_milliseconds = state .conf() .lock_settings .delay_between_retries_in_milliseconds; for _retry in 0..lock_retries { let results: Vec<redis::SetGetReply<_>> = redis_conn .set_multiple_keys_if_not_exists_and_get_values( &redis_key_values, Some(i64::from(redis_lock_expiry_seconds)), ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; let lock_aqcuired = results.iter().all(|res| { // each redis value must match the request_id // if even 1 does match, the lock is not acquired *res.get_value() == request_id }); if lock_aqcuired { logger::info!("Lock acquired for locking inputs {:?}", inputs); return Ok(()); } else { actix_time::sleep(tokio::time::Duration::from_millis(u64::from( delay_between_retries_in_milliseconds, ))) .await; } } Err(report!(errors::ApiErrorResponse::ResourceBusy)) } Self::Hold { input } => { let redis_conn = state .store() .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError)?; let redis_locking_key = input.get_redis_locking_key(&merchant_id); let delay_between_retries_in_milliseconds = state .conf() .lock_settings .delay_between_retries_in_milliseconds; let redis_lock_expiry_seconds = state.conf().lock_settings.redis_lock_expiry_seconds; let lock_retries = input .override_lock_retries .unwrap_or(state.conf().lock_settings.lock_retries); for _retry in 0..lock_retries { let redis_lock_result = redis_conn .set_key_if_not_exists_with_expiry( &redis_locking_key.as_str().into(), state.get_request_id(), Some(i64::from(redis_lock_expiry_seconds)), ) .await; match redis_lock_result { Ok(redis::SetnxReply::KeySet) => { logger::info!("Lock acquired for locking input {:?}", input); tracing::Span::current() .record("redis_lock_acquired", redis_locking_key); return Ok(()); } Ok(redis::SetnxReply::KeyNotSet) => { logger::info!( "Lock busy by other request when tried for locking input {:?}", input ); actix_time::sleep(tokio::time::Duration::from_millis(u64::from( delay_between_retries_in_milliseconds, ))) .await; } Err(err) => { return Err(err) .change_context(errors::ApiErrorResponse::InternalServerError) } } } Err(report!(errors::ApiErrorResponse::ResourceBusy)) } Self::QueueWithOk | Self::Drop | Self::NotApplicable => Ok(()), } } #[instrument(skip_all)] pub async fn free_lock_action<A>( self, state: &A, merchant_id: common_utils::id_type::MerchantId, ) -> RouterResult<()> where A: SessionStateInfo, { match self { Self::HoldMultiple { inputs } => { let redis_conn = state .store() .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError)?; let redis_locking_keys = inputs .iter() .map(|input| RedisKey::from(input.get_redis_locking_key(&merchant_id).as_str())) .collect::<Vec<_>>(); let request_id = state.get_request_id(); let values = redis_conn .get_multiple_keys::<String>(&redis_locking_keys) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; let invalid_request_id_list = values .iter() .filter(|redis_value| **redis_value != request_id) .flatten() .collect::<Vec<_>>(); if !invalid_request_id_list.is_empty() { logger::error!( "The request_id which acquired the lock is not equal to the request_id requesting for releasing the lock. Current request_id: {:?}, Redis request_ids : {:?}", request_id, invalid_request_id_list ); Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("The request_id which acquired the lock is not equal to the request_id requesting for releasing the lock") } else { Ok(()) }?; let delete_result = redis_conn .delete_multiple_keys(&redis_locking_keys) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; let is_key_not_deleted = delete_result .into_iter() .any(|delete_reply| delete_reply.is_key_not_deleted()); if is_key_not_deleted { Err(errors::ApiErrorResponse::InternalServerError).attach_printable( "Status release lock called but key is not found in redis", ) } else { logger::info!("Lock freed for locking inputs {:?}", inputs); Ok(()) } } Self::Hold { input } => { let redis_conn = state .store() .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError)?; let redis_locking_key = input.get_redis_locking_key(&merchant_id); match redis_conn .get_key::<Option<String>>(&redis_locking_key.as_str().into()) .await { Ok(val) => { if val == state.get_request_id() { match redis_conn .delete_key(&redis_locking_key.as_str().into()) .await { Ok(redis::types::DelReply::KeyDeleted) => { logger::info!("Lock freed for locking input {:?}", input); tracing::Span::current() .record("redis_lock_released", redis_locking_key); Ok(()) } Ok(redis::types::DelReply::KeyNotDeleted) => { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Status release lock called but key is not found in redis", ) } Err(error) => Err(error) .change_context(errors::ApiErrorResponse::InternalServerError), } } else { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("The request_id which acquired the lock is not equal to the request_id requesting for releasing the lock") } } Err(error) => { Err(error).change_context(errors::ApiErrorResponse::InternalServerError) } } } Self::QueueWithOk | Self::Drop | Self::NotApplicable => Ok(()), } } } pub trait GetLockingInput { fn get_locking_input<F>(&self, flow: F) -> LockAction where F: router_env::types::FlowMetric, lock_utils::ApiIdentifier: From<F>; }
{ "crate": "router", "file": "crates/router/src/core/api_locking.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-6613686612692247165
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/types.rs // Contains: 3 structs, 1 enums use std::{collections::HashMap, num::TryFromIntError}; use api_models::payment_methods::SurchargeDetailsResponse; use common_utils::{ errors::CustomResult, ext_traits::{Encode, OptionExt}, types::{self as common_types, ConnectorTransactionIdTrait}, }; use error_stack::ResultExt; use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt; pub use hyperswitch_domain_models::router_request_types::{ AuthenticationData, SplitRefundsRequest, StripeSplitRefund, SurchargeDetails, }; use redis_interface::errors::RedisError; use router_env::{instrument, logger, tracing}; use crate::{ consts as router_consts, core::errors::{self, RouterResult}, routes::SessionState, types::{ domain::Profile, storage::{self, enums as storage_enums}, transformers::ForeignTryFrom, }, }; #[derive(Clone, Debug)] pub struct MultipleCaptureData { // key -> capture_id, value -> Capture all_captures: HashMap<String, storage::Capture>, latest_capture: storage::Capture, pub expand_captures: Option<bool>, _private: Private, // to restrict direct construction of MultipleCaptureData } #[derive(Clone, Debug)] struct Private {} impl MultipleCaptureData { pub fn new_for_sync( captures: Vec<storage::Capture>, expand_captures: Option<bool>, ) -> RouterResult<Self> { let latest_capture = captures .last() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Cannot create MultipleCaptureData with empty captures list")? .clone(); let multiple_capture_data = Self { all_captures: captures .into_iter() .map(|capture| (capture.capture_id.clone(), capture)) .collect(), latest_capture, _private: Private {}, expand_captures, }; Ok(multiple_capture_data) } pub fn new_for_create( mut previous_captures: Vec<storage::Capture>, new_capture: storage::Capture, ) -> Self { previous_captures.push(new_capture.clone()); Self { all_captures: previous_captures .into_iter() .map(|capture| (capture.capture_id.clone(), capture)) .collect(), latest_capture: new_capture, _private: Private {}, expand_captures: None, } } pub fn update_capture(&mut self, updated_capture: storage::Capture) { let capture_id = &updated_capture.capture_id; if self.all_captures.contains_key(capture_id) { self.all_captures .entry(capture_id.into()) .and_modify(|capture| *capture = updated_capture.clone()); } } pub fn get_total_blocked_amount(&self) -> common_types::MinorUnit { self.all_captures .iter() .fold(common_types::MinorUnit::new(0), |accumulator, capture| { accumulator + match capture.1.status { storage_enums::CaptureStatus::Charged | storage_enums::CaptureStatus::Pending => capture.1.amount, storage_enums::CaptureStatus::Started | storage_enums::CaptureStatus::Failed => common_types::MinorUnit::new(0), } }) } pub fn get_total_charged_amount(&self) -> common_types::MinorUnit { self.all_captures .iter() .fold(common_types::MinorUnit::new(0), |accumulator, capture| { accumulator + match capture.1.status { storage_enums::CaptureStatus::Charged => capture.1.amount, storage_enums::CaptureStatus::Pending | storage_enums::CaptureStatus::Started | storage_enums::CaptureStatus::Failed => common_types::MinorUnit::new(0), } }) } pub fn get_captures_count(&self) -> RouterResult<i16> { i16::try_from(self.all_captures.len()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while converting from usize to i16") } pub fn get_status_count(&self) -> HashMap<storage_enums::CaptureStatus, i16> { let mut hash_map: HashMap<storage_enums::CaptureStatus, i16> = HashMap::new(); hash_map.insert(storage_enums::CaptureStatus::Charged, 0); hash_map.insert(storage_enums::CaptureStatus::Pending, 0); hash_map.insert(storage_enums::CaptureStatus::Started, 0); hash_map.insert(storage_enums::CaptureStatus::Failed, 0); self.all_captures .iter() .fold(hash_map, |mut accumulator, capture| { let current_capture_status = capture.1.status; accumulator .entry(current_capture_status) .and_modify(|count| *count += 1); accumulator }) } pub fn get_attempt_status( &self, authorized_amount: common_types::MinorUnit, ) -> storage_enums::AttemptStatus { let total_captured_amount = self.get_total_charged_amount(); if authorized_amount == total_captured_amount { return storage_enums::AttemptStatus::Charged; } let status_count_map = self.get_status_count(); if status_count_map.get(&storage_enums::CaptureStatus::Charged) > Some(&0) { storage_enums::AttemptStatus::PartialChargedAndChargeable } else { storage_enums::AttemptStatus::CaptureInitiated } } pub fn get_pending_captures(&self) -> Vec<&storage::Capture> { self.all_captures .iter() .filter(|capture| capture.1.status == storage_enums::CaptureStatus::Pending) .map(|key_value| key_value.1) .collect() } pub fn get_all_captures(&self) -> Vec<&storage::Capture> { self.all_captures .iter() .map(|key_value| key_value.1) .collect() } pub fn get_capture_by_capture_id(&self, capture_id: String) -> Option<&storage::Capture> { self.all_captures.get(&capture_id) } pub fn get_capture_by_connector_capture_id( &self, connector_capture_id: &String, ) -> Option<&storage::Capture> { self.all_captures .iter() .find(|(_, capture)| { capture.get_optional_connector_transaction_id() == Some(connector_capture_id) }) .map(|(_, capture)| capture) } pub fn get_latest_capture(&self) -> &storage::Capture { &self.latest_capture } pub fn get_pending_connector_capture_ids(&self) -> Vec<String> { let pending_connector_capture_ids = self .get_pending_captures() .into_iter() .filter_map(|capture| capture.get_optional_connector_transaction_id().cloned()) .collect(); pending_connector_capture_ids } pub fn get_pending_captures_without_connector_capture_id(&self) -> Vec<&storage::Capture> { self.get_pending_captures() .into_iter() .filter(|capture| capture.get_optional_connector_transaction_id().is_none()) .collect() } } #[cfg(feature = "v2")] impl ForeignTryFrom<(&SurchargeDetails, &PaymentAttempt)> for SurchargeDetailsResponse { type Error = TryFromIntError; fn foreign_try_from( (surcharge_details, payment_attempt): (&SurchargeDetails, &PaymentAttempt), ) -> Result<Self, Self::Error> { todo!() } } #[cfg(feature = "v1")] impl ForeignTryFrom<(&SurchargeDetails, &PaymentAttempt)> for SurchargeDetailsResponse { type Error = TryFromIntError; fn foreign_try_from( (surcharge_details, payment_attempt): (&SurchargeDetails, &PaymentAttempt), ) -> Result<Self, Self::Error> { let currency = payment_attempt.currency.unwrap_or_default(); let display_surcharge_amount = currency .to_currency_base_unit_asf64(surcharge_details.surcharge_amount.get_amount_as_i64())?; let display_tax_on_surcharge_amount = currency.to_currency_base_unit_asf64( surcharge_details .tax_on_surcharge_amount .get_amount_as_i64(), )?; let display_total_surcharge_amount = currency.to_currency_base_unit_asf64( (surcharge_details.surcharge_amount + surcharge_details.tax_on_surcharge_amount) .get_amount_as_i64(), )?; Ok(Self { surcharge: surcharge_details.surcharge.clone().into(), tax_on_surcharge: surcharge_details.tax_on_surcharge.clone().map(Into::into), display_surcharge_amount, display_tax_on_surcharge_amount, display_total_surcharge_amount, }) } } #[derive(Eq, Hash, PartialEq, Clone, Debug, strum::Display)] pub enum SurchargeKey { Token(String), PaymentMethodData( common_enums::PaymentMethod, common_enums::PaymentMethodType, Option<common_enums::CardNetwork>, ), } #[derive(Clone, Debug)] pub struct SurchargeMetadata { surcharge_results: HashMap<SurchargeKey, SurchargeDetails>, pub payment_attempt_id: String, } impl SurchargeMetadata { pub fn new(payment_attempt_id: String) -> Self { Self { surcharge_results: HashMap::new(), payment_attempt_id, } } pub fn is_empty_result(&self) -> bool { self.surcharge_results.is_empty() } pub fn get_surcharge_results_size(&self) -> usize { self.surcharge_results.len() } pub fn insert_surcharge_details( &mut self, surcharge_key: SurchargeKey, surcharge_details: SurchargeDetails, ) { self.surcharge_results .insert(surcharge_key, surcharge_details); } pub fn get_surcharge_details(&self, surcharge_key: SurchargeKey) -> Option<&SurchargeDetails> { self.surcharge_results.get(&surcharge_key) } pub fn get_surcharge_metadata_redis_key(payment_attempt_id: &str) -> String { format!("surcharge_metadata_{payment_attempt_id}") } pub fn get_individual_surcharge_key_value_pairs(&self) -> Vec<(String, SurchargeDetails)> { self.surcharge_results .iter() .map(|(surcharge_key, surcharge_details)| { let key = Self::get_surcharge_details_redis_hashset_key(surcharge_key); (key, surcharge_details.to_owned()) }) .collect() } pub fn get_surcharge_details_redis_hashset_key(surcharge_key: &SurchargeKey) -> String { match surcharge_key { SurchargeKey::Token(token) => { format!("token_{token}") } SurchargeKey::PaymentMethodData(payment_method, payment_method_type, card_network) => { if let Some(card_network) = card_network { format!("{payment_method}_{payment_method_type}_{card_network}") } else { format!("{payment_method}_{payment_method_type}") } } } } #[instrument(skip_all)] pub async fn persist_individual_surcharge_details_in_redis( &self, state: &SessionState, business_profile: &Profile, ) -> RouterResult<()> { if !self.is_empty_result() { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let redis_key = Self::get_surcharge_metadata_redis_key(&self.payment_attempt_id); let mut value_list = Vec::with_capacity(self.get_surcharge_results_size()); for (key, value) in self.get_individual_surcharge_key_value_pairs().into_iter() { value_list.push(( key, value .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode to string of json")?, )); } let intent_fulfillment_time = business_profile .get_order_fulfillment_time() .unwrap_or(router_consts::DEFAULT_FULFILLMENT_TIME); redis_conn .set_hash_fields( &redis_key.as_str().into(), value_list, Some(intent_fulfillment_time), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to write to redis")?; logger::debug!("Surcharge results stored in redis with key = {}", redis_key); } Ok(()) } #[instrument(skip_all)] pub async fn get_individual_surcharge_detail_from_redis( state: &SessionState, surcharge_key: SurchargeKey, payment_attempt_id: &str, ) -> CustomResult<SurchargeDetails, RedisError> { let redis_conn = state .store .get_redis_conn() .attach_printable("Failed to get redis connection")?; let redis_key = Self::get_surcharge_metadata_redis_key(payment_attempt_id); let value_key = Self::get_surcharge_details_redis_hashset_key(&surcharge_key); let result = redis_conn .get_hash_field_and_deserialize( &redis_key.as_str().into(), &value_key, "SurchargeDetails", ) .await; logger::debug!( "Surcharge result fetched from redis with key = {} and {}", redis_key, value_key ); result } } impl ForeignTryFrom< &hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore, > for AuthenticationData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( authentication_store: &hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore, ) -> Result<Self, Self::Error> { let authentication = &authentication_store.authentication; if authentication.authentication_status == common_enums::AuthenticationStatus::Success { let threeds_server_transaction_id = authentication.threeds_server_transaction_id.clone(); let message_version = authentication.message_version.clone(); let cavv = authentication_store .cavv .clone() .get_required_value("cavv") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("cavv must not be null when authentication_status is success")?; Ok(Self { eci: authentication.eci.clone(), created_at: authentication.created_at, cavv, threeds_server_transaction_id, message_version, ds_trans_id: authentication.ds_trans_id.clone(), authentication_type: authentication.authentication_type, challenge_code: authentication.challenge_code.clone(), challenge_cancel: authentication.challenge_cancel.clone(), challenge_code_reason: authentication.challenge_code_reason.clone(), message_extension: authentication.message_extension.clone(), acs_trans_id: authentication.acs_trans_id.clone(), }) } else { Err(errors::ApiErrorResponse::PaymentAuthenticationFailed { data: None }.into()) } } }
{ "crate": "router", "file": "crates/router/src/core/payments/types.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_router_8706166631265127084
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/transformers.rs // Contains: 1 structs, 0 enums use std::{fmt::Debug, marker::PhantomData, str::FromStr}; #[cfg(feature = "v2")] use api_models::enums as api_enums; use api_models::payments::{ Address, ConnectorMandateReferenceId, CustomerDetails, CustomerDetailsResponse, FrmMessage, MandateIds, NetworkDetails, RequestSurchargeDetails, }; use common_enums::{Currency, RequestIncrementalAuthorization}; #[cfg(feature = "v1")] use common_utils::{ consts::X_HS_LATENCY, fp_utils, pii, types::{ self as common_utils_type, AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector, }, }; #[cfg(feature = "v2")] use common_utils::{ ext_traits::Encode, fp_utils, pii, types::{ self as common_utils_type, AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector, }, }; use diesel_models::{ ephemeral_key, payment_attempt::{ ConnectorMandateReferenceId as DieselConnectorMandateReferenceId, NetworkDetails as DieselNetworkDetails, }, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{payments::payment_intent::CustomerData, router_request_types}; #[cfg(feature = "v2")] use hyperswitch_domain_models::{ router_data_v2::{flow_common_types, RouterDataV2}, ApiModelToDieselModelConvertor, }; #[cfg(feature = "v2")] use hyperswitch_interfaces::api::ConnectorSpecifications; #[cfg(feature = "v2")] use hyperswitch_interfaces::connector_integration_interface::RouterDataConversion; use masking::{ExposeInterface, Maskable, Secret}; #[cfg(feature = "v2")] use masking::{ExposeOptionInterface, PeekInterface}; use router_env::{instrument, tracing}; use super::{flows::Feature, types::AuthenticationData, OperationSessionGetters, PaymentData}; use crate::{ configs::settings::ConnectorRequestReferenceIdConfig, core::{ errors::{self, RouterResponse, RouterResult}, payments::{self, helpers}, utils as core_utils, }, headers::{X_CONNECTOR_HTTP_STATUS_CODE, X_PAYMENT_CONFIRM_SOURCE}, routes::{metrics, SessionState}, services::{self, RedirectForm}, types::{ self, api::{self, ConnectorTransactionId}, domain, payment_methods as pm_types, storage::{self, enums}, transformers::{ForeignFrom, ForeignInto, ForeignTryFrom}, MultipleCaptureRequestData, }, utils::{OptionExt, ValueExt}, }; #[cfg(feature = "v2")] pub async fn construct_router_data_to_update_calculated_tax<'a, F, T>( state: &'a SessionState, payment_data: PaymentData<F>, connector_id: &str, merchant_context: &domain::MerchantContext, customer: &'a Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, ) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>> where T: TryFrom<PaymentAdditionalData<'a, F>>, types::RouterData<F, T, types::PaymentsResponseData>: Feature<F, T>, F: Clone, error_stack::Report<errors::ApiErrorResponse>: From<<T as TryFrom<PaymentAdditionalData<'a, F>>>::Error>, { todo!() } #[cfg(feature = "v1")] pub async fn construct_router_data_to_update_calculated_tax<'a, F, T>( state: &'a SessionState, payment_data: PaymentData<F>, connector_id: &str, merchant_context: &domain::MerchantContext, customer: &'a Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, ) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>> where T: TryFrom<PaymentAdditionalData<'a, F>>, types::RouterData<F, T, types::PaymentsResponseData>: Feature<F, T>, F: Clone, error_stack::Report<errors::ApiErrorResponse>: From<<T as TryFrom<PaymentAdditionalData<'a, F>>>::Error>, { 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")?; 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 connector_mandate_request_reference_id = payment_data .payment_attempt .connector_mandate_detail .as_ref() .and_then(|detail| detail.get_connector_mandate_request_reference_id()); let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_context.get_merchant_account().get_id().clone(), customer_id: None, connector: connector_id.to_owned(), payment_id: payment_data .payment_attempt .payment_id .get_string_repr() .to_owned(), tenant_id: state.tenant.tenant_id.clone(), attempt_id: payment_data.payment_attempt.get_id().to_owned(), status: payment_data.payment_attempt.status, payment_method: diesel_models::enums::PaymentMethod::default(), payment_method_type: payment_data.payment_attempt.payment_method_type, connector_auth_type: auth_type, description: None, address: payment_data.address.clone(), auth_type: payment_data .payment_attempt .authentication_type .unwrap_or_default(), connector_meta_data: None, connector_wallets_details: None, request: T::try_from(additional_data)?, response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), amount_captured: None, minor_amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_status: None, payment_method_token: None, connector_customer: None, recurring_mandate_payment_data: None, connector_request_reference_id: core_utils::get_connector_request_reference_id( &state.conf, merchant_context.get_merchant_account().get_id(), &payment_data.payment_intent, &payment_data.payment_attempt, connector_id, )?, preprocessing_id: None, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode, payment_method_balance: None, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: payment_data.payment_intent.is_payment_id_from_merchant, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, }; Ok(router_data) } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_external_vault_proxy_router_data_v2<'a>( state: &'a SessionState, merchant_account: &domain::MerchantAccount, merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails, payment_data: &hyperswitch_domain_models::payments::PaymentConfirmData<api::ExternalVaultProxy>, request: types::ExternalVaultProxyPaymentsData, connector_request_reference_id: String, connector_customer_id: Option<String>, customer_id: Option<common_utils::id_type::CustomerId>, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult< RouterDataV2< api::ExternalVaultProxy, hyperswitch_domain_models::router_data_v2::ExternalVaultProxyFlowData, types::ExternalVaultProxyPaymentsData, types::PaymentsResponseData, >, > { use hyperswitch_domain_models::router_data_v2::{ExternalVaultProxyFlowData, RouterDataV2}; let auth_type = merchant_connector_account .get_connector_account_details() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; let external_vault_proxy_flow_data = ExternalVaultProxyFlowData { merchant_id: merchant_account.get_id().clone(), customer_id, connector_customer: connector_customer_id, payment_id: payment_data .payment_attempt .payment_id .get_string_repr() .to_owned(), attempt_id: payment_data .payment_attempt .get_id() .get_string_repr() .to_owned(), status: payment_data.payment_attempt.status, payment_method: payment_data.payment_attempt.payment_method_type, description: payment_data .payment_intent .description .as_ref() .map(|description| description.get_string_repr()) .map(ToOwned::to_owned), address: payment_data.payment_address.clone(), auth_type: payment_data.payment_attempt.authentication_type, connector_meta_data: merchant_connector_account.get_metadata(), amount_captured: None, minor_amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_token: None, recurring_mandate_payment_data: None, preprocessing_id: payment_data.payment_attempt.preprocessing_step_id.clone(), payment_method_balance: None, connector_api_version: None, connector_request_reference_id, test_mode: Some(true), connector_http_status_code: None, external_latency: None, apple_pay_flow: None, connector_response: None, payment_method_status: None, }; let router_data_v2 = RouterDataV2 { flow: PhantomData, tenant_id: state.tenant.tenant_id.clone(), resource_common_data: external_vault_proxy_flow_data, connector_auth_type: auth_type, request, response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), }; Ok(router_data_v2) } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_payment_router_data_for_authorize<'a>( state: &'a SessionState, payment_data: hyperswitch_domain_models::payments::PaymentConfirmData<api::Authorize>, connector_id: &str, merchant_context: &domain::MerchantContext, customer: &'a Option<domain::Customer>, merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails, _merchant_recipient_data: Option<types::MerchantRecipientData>, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult<types::PaymentsAuthorizeRouterData> { use masking::ExposeOptionInterface; fp_utils::when(merchant_connector_account.is_disabled(), || { Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled) })?; let auth_type = merchant_connector_account .get_connector_account_details() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; // TODO: Take Globalid and convert to connector reference id let customer_id = customer .to_owned() .map(|customer| common_utils::id_type::CustomerId::try_from(customer.id.clone())) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Invalid global customer generated, not able to convert to reference id", )?; let connector_customer_id = payment_data.get_connector_customer_id(customer.as_ref(), merchant_connector_account); let payment_method = payment_data.payment_attempt.payment_method_type; let router_base_url = &state.base_url; let attempt = &payment_data.payment_attempt; let complete_authorize_url = Some(helpers::create_complete_authorize_url( router_base_url, attempt, connector_id, None, )); let webhook_url = match merchant_connector_account { domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount( merchant_connector_account, ) => Some(helpers::create_webhook_url( router_base_url, &attempt.merchant_id, merchant_connector_account.get_id().get_string_repr(), )), domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => { payment_data.webhook_url } }; let router_return_url = payment_data .payment_intent .create_finish_redirection_url( router_base_url, merchant_context .get_merchant_account() .publishable_key .as_ref(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to construct finish redirection url")? .to_string(); let connector_request_reference_id = payment_data .payment_attempt .connector_request_reference_id .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("connector_request_reference_id not found in payment_attempt")?; let email = customer .as_ref() .and_then(|customer| customer.email.clone()) .map(pii::Email::from); let browser_info = payment_data .payment_attempt .browser_info .clone() .map(types::BrowserInformation::from); let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> = payment_data.payment_attempt .payment_method_data .as_ref().map(|data| data.clone().parse_value("AdditionalPaymentData")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse AdditionalPaymentData from payment_data.payment_attempt.payment_method_data")?; let connector_metadata = payment_data.payment_intent.connector_metadata.clone(); let order_category = connector_metadata.as_ref().and_then(|cm| { cm.noon .as_ref() .and_then(|noon| noon.order_category.clone()) }); // TODO: few fields are repeated in both routerdata and request let request = types::PaymentsAuthorizeData { payment_method_data: payment_data .payment_method_data .get_required_value("payment_method_data")?, setup_future_usage: Some(payment_data.payment_intent.setup_future_usage), mandate_id: payment_data.mandate_data.clone(), off_session: None, setup_mandate_details: None, confirm: true, statement_descriptor_suffix: None, statement_descriptor: None, capture_method: Some(payment_data.payment_intent.capture_method), amount: payment_data .payment_attempt .amount_details .get_net_amount() .get_amount_as_i64(), minor_amount: payment_data.payment_attempt.amount_details.get_net_amount(), order_tax_amount: None, currency: payment_data.payment_intent.amount_details.currency, browser_info, email, customer_name: None, payment_experience: None, order_details: None, order_category, session_token: None, enrolled_for_3ds: true, related_transaction_id: None, payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype), router_return_url: Some(router_return_url), webhook_url, complete_authorize_url, customer_id: customer_id.clone(), surcharge_details: None, request_extended_authorization: None, request_incremental_authorization: matches!( payment_data .payment_intent .request_incremental_authorization, RequestIncrementalAuthorization::True ), metadata: payment_data.payment_intent.metadata.expose_option(), authentication_data: None, customer_acceptance: None, split_payments: None, merchant_order_reference_id: payment_data .payment_intent .merchant_reference_id .map(|reference_id| reference_id.get_string_repr().to_owned()), integrity_object: None, shipping_cost: payment_data.payment_intent.amount_details.shipping_cost, additional_payment_method_data, merchant_account_id: None, merchant_config_currency: None, connector_testing_data: None, order_id: None, locale: None, mit_category: None, payment_channel: None, enable_partial_authorization: payment_data.payment_intent.enable_partial_authorization, enable_overcapture: None, is_stored_credential: None, }; let connector_mandate_request_reference_id = payment_data .payment_attempt .connector_token_details .as_ref() .and_then(|detail| detail.get_connector_token_request_reference_id()); // TODO: evaluate the fields in router data, if they are required or not let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_context.get_merchant_account().get_id().clone(), tenant_id: state.tenant.tenant_id.clone(), // TODO: evaluate why we need customer id at the connector level. We already have connector customer id. customer_id, connector: connector_id.to_owned(), // TODO: evaluate why we need payment id at the connector level. We already have connector reference id payment_id: payment_data .payment_attempt .payment_id .get_string_repr() .to_owned(), // TODO: evaluate why we need attempt id at the connector level. We already have connector reference id attempt_id: payment_data .payment_attempt .get_id() .get_string_repr() .to_owned(), status: payment_data.payment_attempt.status, payment_method, payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype), connector_auth_type: auth_type, description: payment_data .payment_intent .description .as_ref() .map(|description| description.get_string_repr()) .map(ToOwned::to_owned), // TODO: Create unified address address: payment_data.payment_address.clone(), auth_type: payment_data.payment_attempt.authentication_type, connector_meta_data: merchant_connector_account.get_metadata(), connector_wallets_details: None, request, response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), 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: None, payment_method_token: None, connector_customer: connector_customer_id, recurring_mandate_payment_data: None, // TODO: This has to be generated as the reference id based on the connector configuration // Some connectros might not accept accept the global id. This has to be done when generating the reference id connector_request_reference_id, preprocessing_id: payment_data.payment_attempt.preprocessing_step_id, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, // TODO: take this based on the env test_mode: Some(true), payment_method_balance: None, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload, connector_mandate_request_reference_id, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: payment_data.payment_intent.is_payment_id_from_merchant, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, }; Ok(router_data) } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_external_vault_proxy_payment_router_data<'a>( state: &'a SessionState, payment_data: hyperswitch_domain_models::payments::PaymentConfirmData<api::ExternalVaultProxy>, connector_id: &str, merchant_context: &domain::MerchantContext, customer: &'a Option<domain::Customer>, merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails, _merchant_recipient_data: Option<types::MerchantRecipientData>, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult<types::ExternalVaultProxyPaymentsRouterData> { use masking::ExposeOptionInterface; fp_utils::when(merchant_connector_account.is_disabled(), || { Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled) })?; let auth_type = merchant_connector_account .get_connector_account_details() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; // TODO: Take Globalid and convert to connector reference id let customer_id = customer .to_owned() .map(|customer| common_utils::id_type::CustomerId::try_from(customer.id.clone())) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Invalid global customer generated, not able to convert to reference id", )?; let connector_customer_id = payment_data.get_connector_customer_id(customer.as_ref(), merchant_connector_account); let payment_method = payment_data.payment_attempt.payment_method_type; let router_base_url = &state.base_url; let attempt = &payment_data.payment_attempt; let complete_authorize_url = Some(helpers::create_complete_authorize_url( router_base_url, attempt, connector_id, None, )); let webhook_url = match merchant_connector_account { domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount( merchant_connector_account, ) => Some(helpers::create_webhook_url( router_base_url, &attempt.merchant_id, merchant_connector_account.get_id().get_string_repr(), )), domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => { payment_data.webhook_url.clone() } }; let router_return_url = payment_data .payment_intent .create_finish_redirection_url( router_base_url, merchant_context .get_merchant_account() .publishable_key .as_ref(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to construct finish redirection url")? .to_string(); let connector_request_reference_id = payment_data .payment_attempt .connector_request_reference_id .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("connector_request_reference_id not found in payment_attempt")?; let email = customer .as_ref() .and_then(|customer| customer.email.clone()) .map(pii::Email::from); let browser_info = payment_data .payment_attempt .browser_info .clone() .map(types::BrowserInformation::from); // TODO: few fields are repeated in both routerdata and request let request = types::ExternalVaultProxyPaymentsData { payment_method_data: payment_data .external_vault_pmd .clone() .get_required_value("external vault proxy payment_method_data")?, setup_future_usage: Some(payment_data.payment_intent.setup_future_usage), mandate_id: payment_data.mandate_data.clone(), off_session: None, setup_mandate_details: None, confirm: true, statement_descriptor_suffix: None, statement_descriptor: None, capture_method: Some(payment_data.payment_intent.capture_method), amount: payment_data .payment_attempt .amount_details .get_net_amount() .get_amount_as_i64(), minor_amount: payment_data.payment_attempt.amount_details.get_net_amount(), order_tax_amount: None, currency: payment_data.payment_intent.amount_details.currency, browser_info, email, customer_name: None, payment_experience: None, order_details: None, order_category: None, session_token: None, enrolled_for_3ds: true, related_transaction_id: None, payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype), router_return_url: Some(router_return_url), webhook_url, complete_authorize_url, customer_id: customer_id.clone(), surcharge_details: None, request_extended_authorization: None, request_incremental_authorization: matches!( payment_data .payment_intent .request_incremental_authorization, RequestIncrementalAuthorization::True ), metadata: payment_data.payment_intent.metadata.clone().expose_option(), authentication_data: None, customer_acceptance: None, split_payments: None, merchant_order_reference_id: payment_data.payment_intent.merchant_reference_id.clone(), integrity_object: None, shipping_cost: payment_data.payment_intent.amount_details.shipping_cost, additional_payment_method_data: None, merchant_account_id: None, merchant_config_currency: None, connector_testing_data: None, order_id: None, }; let connector_mandate_request_reference_id = payment_data .payment_attempt .connector_token_details .as_ref() .and_then(|detail| detail.get_connector_token_request_reference_id()); // Construct RouterDataV2 for external vault proxy let router_data_v2 = construct_external_vault_proxy_router_data_v2( state, merchant_context.get_merchant_account(), merchant_connector_account, &payment_data, request, connector_request_reference_id.clone(), connector_customer_id.clone(), customer_id.clone(), header_payload.clone(), ) .await?; // Convert RouterDataV2 to old RouterData (v1) using the existing RouterDataConversion trait let router_data = flow_common_types::ExternalVaultProxyFlowData::to_old_router_data(router_data_v2) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Cannot construct router data for making the unified connector service call", )?; Ok(router_data) } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_payment_router_data_for_capture<'a>( state: &'a SessionState, payment_data: hyperswitch_domain_models::payments::PaymentCaptureData<api::Capture>, connector_id: &str, merchant_context: &domain::MerchantContext, customer: &'a Option<domain::Customer>, merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails, _merchant_recipient_data: Option<types::MerchantRecipientData>, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult<types::PaymentsCaptureRouterData> { use masking::ExposeOptionInterface; fp_utils::when(merchant_connector_account.is_disabled(), || { Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled) })?; let auth_type = merchant_connector_account .get_connector_account_details() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; let customer_id = customer .to_owned() .map(|customer| common_utils::id_type::CustomerId::try_from(customer.id.clone())) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Invalid global customer generated, not able to convert to reference id", )?; let payment_method = payment_data.payment_attempt.payment_method_type; let connector_mandate_request_reference_id = payment_data .payment_attempt .connector_token_details .as_ref() .and_then(|detail| detail.get_connector_token_request_reference_id()); let connector = api::ConnectorData::get_connector_by_name( &state.conf.connectors, connector_id, api::GetToken::Connector, payment_data.payment_attempt.merchant_connector_id.clone(), )?; let connector_request_reference_id = payment_data .payment_attempt .connector_request_reference_id .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("connector_request_reference_id not found in payment_attempt")?; let amount_to_capture = payment_data .payment_attempt .amount_details .get_amount_to_capture() .unwrap_or(payment_data.payment_attempt.amount_details.get_net_amount()); let amount = payment_data.payment_attempt.amount_details.get_net_amount(); let request = types::PaymentsCaptureData { capture_method: Some(payment_data.payment_intent.capture_method), amount_to_capture: amount_to_capture.get_amount_as_i64(), // This should be removed once we start moving to connector module minor_amount_to_capture: amount_to_capture, currency: payment_data.payment_intent.amount_details.currency, connector_transaction_id: connector .connector .connector_transaction_id(&payment_data.payment_attempt)? .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?, payment_amount: amount.get_amount_as_i64(), // This should be removed once we start moving to connector module minor_payment_amount: amount, connector_meta: payment_data .payment_attempt .connector_metadata .clone() .expose_option(), // TODO: add multiple capture data multiple_capture_data: None, // TODO: why do we need browser info during capture? browser_info: None, metadata: payment_data.payment_intent.metadata.expose_option(), integrity_object: None, split_payments: None, webhook_url: None, }; // TODO: evaluate the fields in router data, if they are required or not let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_context.get_merchant_account().get_id().clone(), // TODO: evaluate why we need customer id at the connector level. We already have connector customer id. customer_id, connector: connector_id.to_owned(), tenant_id: state.tenant.tenant_id.clone(), // TODO: evaluate why we need payment id at the connector level. We already have connector reference id payment_id: payment_data .payment_attempt .payment_id .get_string_repr() .to_owned(), // TODO: evaluate why we need attempt id at the connector level. We already have connector reference id attempt_id: payment_data .payment_attempt .get_id() .get_string_repr() .to_owned(), status: payment_data.payment_attempt.status, payment_method, payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype), connector_auth_type: auth_type, description: payment_data .payment_intent .description .as_ref() .map(|description| description.get_string_repr()) .map(ToOwned::to_owned), // TODO: Create unified address address: hyperswitch_domain_models::payment_address::PaymentAddress::default(), auth_type: payment_data.payment_attempt.authentication_type, connector_meta_data: None, connector_wallets_details: None, request, response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), amount_captured: None, minor_amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_status: None, payment_method_token: None, connector_customer: None, recurring_mandate_payment_data: None, // TODO: This has to be generated as the reference id based on the connector configuration // Some connectros might not accept accept the global id. This has to be done when generating the reference id connector_request_reference_id, preprocessing_id: payment_data.payment_attempt.preprocessing_step_id, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, // TODO: take this based on the env test_mode: Some(true), payment_method_balance: None, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload, connector_mandate_request_reference_id, psd2_sca_exemption_type: None, authentication_id: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, }; Ok(router_data) } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_router_data_for_psync<'a>( state: &'a SessionState, payment_data: hyperswitch_domain_models::payments::PaymentStatusData<api::PSync>, connector_id: &str, merchant_context: &domain::MerchantContext, customer: &'a Option<domain::Customer>, merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails, _merchant_recipient_data: Option<types::MerchantRecipientData>, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult<types::PaymentsSyncRouterData> { use masking::ExposeOptionInterface; fp_utils::when(merchant_connector_account.is_disabled(), || { Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled) })?; // TODO: Take Globalid / CustomerReferenceId and convert to connector reference id let customer_id = None; let payment_intent = payment_data.payment_intent; let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; let attempt = &payment_data.payment_attempt; let connector_request_reference_id = payment_data .payment_attempt .connector_request_reference_id .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("connector_request_reference_id not found in payment_attempt")?; let request = types::PaymentsSyncData { amount: attempt.amount_details.get_net_amount(), integrity_object: None, mandate_id: None, connector_transaction_id: match attempt.get_connector_payment_id() { Some(connector_txn_id) => { types::ResponseId::ConnectorTransactionId(connector_txn_id.to_owned()) } None => types::ResponseId::NoResponseId, }, encoded_data: attempt.encoded_data.clone().expose_option(), capture_method: Some(payment_intent.capture_method), connector_meta: attempt.connector_metadata.clone().expose_option(), sync_type: types::SyncRequestType::SinglePaymentSync, payment_method_type: Some(attempt.payment_method_subtype), currency: payment_intent.amount_details.currency, // TODO: Get the charges object from feature metadata split_payments: None, payment_experience: None, connector_reference_id: attempt.connector_response_reference_id.clone(), setup_future_usage: Some(payment_intent.setup_future_usage), }; // TODO: evaluate the fields in router data, if they are required or not let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_context.get_merchant_account().get_id().clone(), // TODO: evaluate why we need customer id at the connector level. We already have connector customer id. customer_id, tenant_id: state.tenant.tenant_id.clone(), connector: connector_id.to_owned(), // TODO: evaluate why we need payment id at the connector level. We already have connector reference id payment_id: payment_intent.id.get_string_repr().to_owned(), // TODO: evaluate why we need attempt id at the connector level. We already have connector reference id attempt_id: attempt.get_id().get_string_repr().to_owned(), status: attempt.status, payment_method: attempt.payment_method_type, payment_method_type: Some(attempt.payment_method_subtype), connector_auth_type: auth_type, description: payment_intent .description .as_ref() .map(|description| description.get_string_repr()) .map(ToOwned::to_owned), // TODO: Create unified address address: hyperswitch_domain_models::payment_address::PaymentAddress::default(), auth_type: attempt.authentication_type, connector_meta_data: None, connector_wallets_details: None, request, response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), amount_captured: None, minor_amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_status: None, payment_method_token: None, connector_customer: None, recurring_mandate_payment_data: None, // TODO: This has to be generated as the reference id based on the connector configuration // Some connectros might not accept accept the global id. This has to be done when generating the reference id connector_request_reference_id, preprocessing_id: attempt.preprocessing_step_id.clone(), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, // TODO: take this based on the env test_mode: Some(true), payment_method_balance: None, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, }; Ok(router_data) } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_cancel_router_data_v2<'a>( state: &'a SessionState, merchant_account: &domain::MerchantAccount, merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails, payment_data: &hyperswitch_domain_models::payments::PaymentCancelData<api::Void>, request: types::PaymentsCancelData, connector_request_reference_id: String, customer_id: Option<common_utils::id_type::CustomerId>, connector_id: &str, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult< RouterDataV2< api::Void, flow_common_types::PaymentFlowData, types::PaymentsCancelData, types::PaymentsResponseData, >, > { let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; let payment_cancel_data = flow_common_types::PaymentFlowData { merchant_id: merchant_account.get_id().clone(), customer_id, connector_customer: None, connector: connector_id.to_owned(), payment_id: payment_data .payment_attempt .payment_id .get_string_repr() .to_owned(), attempt_id: payment_data .payment_attempt .get_id() .get_string_repr() .to_owned(), status: payment_data.payment_attempt.status, payment_method: payment_data.payment_attempt.payment_method_type, description: payment_data .payment_intent .description .as_ref() .map(|description| description.get_string_repr()) .map(ToOwned::to_owned), address: hyperswitch_domain_models::payment_address::PaymentAddress::default(), auth_type: payment_data.payment_attempt.authentication_type, connector_meta_data: merchant_connector_account.get_metadata(), amount_captured: None, minor_amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_token: None, recurring_mandate_payment_data: None, preprocessing_id: payment_data.payment_attempt.preprocessing_step_id.clone(), payment_method_balance: None, connector_api_version: None, connector_request_reference_id, test_mode: Some(true), connector_http_status_code: None, external_latency: None, apple_pay_flow: None, connector_response: None, payment_method_status: None, }; let router_data_v2 = RouterDataV2 { flow: PhantomData, tenant_id: state.tenant.tenant_id.clone(), resource_common_data: payment_cancel_data, connector_auth_type: auth_type, request, response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), }; Ok(router_data_v2) } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_router_data_for_cancel<'a>( state: &'a SessionState, payment_data: hyperswitch_domain_models::payments::PaymentCancelData< hyperswitch_domain_models::router_flow_types::Void, >, connector_id: &str, merchant_context: &domain::MerchantContext, customer: &'a Option<domain::Customer>, merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails, _merchant_recipient_data: Option<types::MerchantRecipientData>, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult<types::PaymentsCancelRouterData> { fp_utils::when(merchant_connector_account.is_disabled(), || { Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled) })?; // TODO: Take Globalid and convert to connector reference id let customer_id = customer .to_owned() .map(|customer| common_utils::id_type::CustomerId::try_from(customer.id.clone())) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Invalid global customer generated, not able to convert to reference id", )?; let payment_intent = payment_data.get_payment_intent(); let attempt = payment_data.get_payment_attempt(); let connector_request_reference_id = payment_data .payment_attempt .connector_request_reference_id .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("connector_request_reference_id not found in payment_attempt")?; let request = types::PaymentsCancelData { amount: Some(attempt.amount_details.get_net_amount().get_amount_as_i64()), currency: Some(payment_intent.amount_details.currency), connector_transaction_id: attempt .get_connector_payment_id() .unwrap_or_default() .to_string(), cancellation_reason: attempt.cancellation_reason.clone(), connector_meta: attempt.connector_metadata.clone().expose_option(), browser_info: None, metadata: None, minor_amount: Some(attempt.amount_details.get_net_amount()), webhook_url: None, capture_method: Some(payment_intent.capture_method), }; // Construct RouterDataV2 for cancel operation let router_data_v2 = construct_cancel_router_data_v2( state, merchant_context.get_merchant_account(), merchant_connector_account, &payment_data, request, connector_request_reference_id.clone(), customer_id.clone(), connector_id, header_payload.clone(), ) .await?; // Convert RouterDataV2 to old RouterData (v1) using the existing RouterDataConversion trait let router_data = flow_common_types::PaymentFlowData::to_old_router_data(router_data_v2) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Cannot construct router data for making the unified connector service call", )?; Ok(router_data) } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_payment_router_data_for_sdk_session<'a>( state: &'a SessionState, payment_data: hyperswitch_domain_models::payments::PaymentIntentData<api::Session>, connector_id: &str, merchant_context: &domain::MerchantContext, customer: &'a Option<domain::Customer>, merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails, _merchant_recipient_data: Option<types::MerchantRecipientData>, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult<types::PaymentsSessionRouterData> { fp_utils::when(merchant_connector_account.is_disabled(), || { Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled) })?; let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; // TODO: Take Globalid and convert to connector reference id let customer_id = customer .to_owned() .map(|customer| common_utils::id_type::CustomerId::try_from(customer.id.clone())) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Invalid global customer generated, not able to convert to reference id", )?; let billing_address = payment_data .payment_intent .billing_address .as_ref() .map(|billing_address| billing_address.clone().into_inner()); // fetch email from customer or billing address (fallback) let email = customer .as_ref() .and_then(|customer| customer.email.clone()) .map(pii::Email::from) .or(billing_address .as_ref() .and_then(|address| address.email.clone())); // fetch customer name from customer or billing address (fallback) let customer_name = customer .as_ref() .and_then(|customer| customer.name.clone()) .map(|name| name.into_inner()) .or(billing_address.and_then(|address| { address .address .as_ref() .and_then(|address_details| address_details.get_optional_full_name()) })); let order_details = payment_data .payment_intent .order_details .clone() .map(|order_details| { order_details .into_iter() .map(|order_detail| order_detail.expose()) .collect() }); let required_amount_type = StringMajorUnitForConnector; let apple_pay_amount = required_amount_type .convert( payment_data.payment_intent.amount_details.order_amount, payment_data.payment_intent.amount_details.currency, ) .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "Failed to convert amount to string major unit for applePay".to_string(), })?; let apple_pay_recurring_details = payment_data .payment_intent .feature_metadata .clone() .and_then(|feature_metadata| feature_metadata.apple_pay_recurring_details) .map(|apple_pay_recurring_details| { ForeignInto::foreign_into((apple_pay_recurring_details, apple_pay_amount)) }); let order_tax_amount = payment_data .payment_intent .amount_details .tax_details .clone() .and_then(|tax| tax.get_default_tax_amount()); let payment_attempt = payment_data.get_payment_attempt(); let payment_method = Some(payment_attempt.payment_method_type); let payment_method_type = Some(payment_attempt.payment_method_subtype); // TODO: few fields are repeated in both routerdata and request let request = types::PaymentsSessionData { amount: payment_data .payment_intent .amount_details .order_amount .get_amount_as_i64(), currency: payment_data.payment_intent.amount_details.currency, country: payment_data .payment_intent .billing_address .and_then(|billing_address| { billing_address .get_inner() .address .as_ref() .and_then(|address| address.country) }), // TODO: populate surcharge here surcharge_details: None, order_details, email, minor_amount: payment_data.payment_intent.amount_details.order_amount, apple_pay_recurring_details, customer_name, metadata: payment_data.payment_intent.metadata, order_tax_amount, shipping_cost: payment_data.payment_intent.amount_details.shipping_cost, payment_method, payment_method_type, }; // TODO: evaluate the fields in router data, if they are required or not let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_context.get_merchant_account().get_id().clone(), // TODO: evaluate why we need customer id at the connector level. We already have connector customer id. customer_id, connector: connector_id.to_owned(), tenant_id: state.tenant.tenant_id.clone(), // TODO: evaluate why we need payment id at the connector level. We already have connector reference id payment_id: payment_data.payment_intent.id.get_string_repr().to_owned(), // TODO: evaluate why we need attempt id at the connector level. We already have connector reference id attempt_id: "".to_string(), status: enums::AttemptStatus::Started, payment_method: enums::PaymentMethod::Wallet, payment_method_type, connector_auth_type: auth_type, description: payment_data .payment_intent .description .as_ref() .map(|description| description.get_string_repr()) .map(ToOwned::to_owned), // TODO: Create unified address address: hyperswitch_domain_models::payment_address::PaymentAddress::default(), auth_type: payment_data .payment_intent .authentication_type .unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), connector_wallets_details: None, request, response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), amount_captured: None, minor_amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_status: None, payment_method_token: None, connector_customer: None, recurring_mandate_payment_data: None, // TODO: This has to be generated as the reference id based on the connector configuration // Some connectros might not accept accept the global id. This has to be done when generating the reference id connector_request_reference_id: "".to_string(), preprocessing_id: None, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, // TODO: take this based on the env test_mode: Some(true), payment_method_balance: None, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload, connector_mandate_request_reference_id: None, psd2_sca_exemption_type: None, authentication_id: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, }; Ok(router_data) } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_payment_router_data_for_setup_mandate<'a>( state: &'a SessionState, payment_data: hyperswitch_domain_models::payments::PaymentConfirmData<api::SetupMandate>, connector_id: &str, merchant_context: &domain::MerchantContext, customer: &'a Option<domain::Customer>, merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails, _merchant_recipient_data: Option<types::MerchantRecipientData>, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult<types::SetupMandateRouterData> { fp_utils::when(merchant_connector_account.is_disabled(), || { Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled) })?; let auth_type = merchant_connector_account .get_connector_account_details() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; // TODO: Take Globalid and convert to connector reference id let customer_id = customer .to_owned() .map(|customer| common_utils::id_type::CustomerId::try_from(customer.id.clone())) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Invalid global customer generated, not able to convert to reference id", )?; let connector_customer_id = customer.as_ref().and_then(|customer| { customer .get_connector_customer_id(merchant_connector_account) .map(String::from) }); let payment_method = payment_data.payment_attempt.payment_method_type; let router_base_url = &state.base_url; let attempt = &payment_data.payment_attempt; let complete_authorize_url = Some(helpers::create_complete_authorize_url( router_base_url, attempt, connector_id, None, )); let webhook_url = match merchant_connector_account { domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount( merchant_connector_account, ) => Some(helpers::create_webhook_url( router_base_url, &attempt.merchant_id, merchant_connector_account.get_id().get_string_repr(), )), domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => { payment_data.webhook_url } }; let router_return_url = payment_data .payment_intent .create_finish_redirection_url( router_base_url, merchant_context .get_merchant_account() .publishable_key .as_ref(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to construct finish redirection url")? .to_string(); let connector_request_reference_id = payment_data .payment_attempt .connector_request_reference_id .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("connector_request_reference_id not found in payment_attempt")?; let email = customer .as_ref() .and_then(|customer| customer.email.clone()) .map(pii::Email::from); let browser_info = payment_data .payment_attempt .browser_info .clone() .map(types::BrowserInformation::from); // TODO: few fields are repeated in both routerdata and request let request = types::SetupMandateRequestData { currency: payment_data.payment_intent.amount_details.currency, payment_method_data: payment_data .payment_method_data .get_required_value("payment_method_data")?, amount: Some( payment_data .payment_attempt .amount_details .get_net_amount() .get_amount_as_i64(), ), confirm: true, statement_descriptor_suffix: None, customer_acceptance: None, mandate_id: None, setup_future_usage: Some(payment_data.payment_intent.setup_future_usage), off_session: None, setup_mandate_details: None, router_return_url: Some(router_return_url.clone()), webhook_url, browser_info, email, customer_name: None, return_url: Some(router_return_url), payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype), request_incremental_authorization: matches!( payment_data .payment_intent .request_incremental_authorization, RequestIncrementalAuthorization::True ), metadata: payment_data.payment_intent.metadata, minor_amount: Some(payment_data.payment_attempt.amount_details.get_net_amount()), shipping_cost: payment_data.payment_intent.amount_details.shipping_cost, capture_method: Some(payment_data.payment_intent.capture_method), complete_authorize_url, connector_testing_data: None, customer_id: None, enable_partial_authorization: None, payment_channel: None, enrolled_for_3ds: true, related_transaction_id: None, is_stored_credential: None, }; let connector_mandate_request_reference_id = payment_data .payment_attempt .connector_token_details .as_ref() .and_then(|detail| detail.get_connector_token_request_reference_id()); // TODO: evaluate the fields in router data, if they are required or not let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_context.get_merchant_account().get_id().clone(), tenant_id: state.tenant.tenant_id.clone(), // TODO: evaluate why we need customer id at the connector level. We already have connector customer id. customer_id, connector: connector_id.to_owned(), // TODO: evaluate why we need payment id at the connector level. We already have connector reference id payment_id: payment_data .payment_attempt .payment_id .get_string_repr() .to_owned(), // TODO: evaluate why we need attempt id at the connector level. We already have connector reference id attempt_id: payment_data .payment_attempt .get_id() .get_string_repr() .to_owned(), status: payment_data.payment_attempt.status, payment_method, payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype), connector_auth_type: auth_type, description: payment_data .payment_intent .description .as_ref() .map(|description| description.get_string_repr()) .map(ToOwned::to_owned), // TODO: Create unified address address: payment_data.payment_address.clone(), auth_type: payment_data.payment_attempt.authentication_type, connector_meta_data: None, connector_wallets_details: None, request, response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), amount_captured: None, minor_amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_status: None, payment_method_token: None, connector_customer: connector_customer_id, recurring_mandate_payment_data: None, // TODO: This has to be generated as the reference id based on the connector configuration // Some connectros might not accept accept the global id. This has to be done when generating the reference id connector_request_reference_id, preprocessing_id: payment_data.payment_attempt.preprocessing_step_id, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, // TODO: take this based on the env test_mode: Some(true), payment_method_balance: None, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload, connector_mandate_request_reference_id, authentication_id: None, psd2_sca_exemption_type: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, }; Ok(router_data) } #[cfg(feature = "v1")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_payment_router_data<'a, F, T>( state: &'a SessionState, payment_data: PaymentData<F>, 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>, payment_method: Option<common_enums::PaymentMethod>, payment_method_type: Option<common_enums::PaymentMethodType>, ) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>> where T: TryFrom<PaymentAdditionalData<'a, F>>, types::RouterData<F, T, types::PaymentsResponseData>: Feature<F, T>, F: Clone, error_stack::Report<errors::ApiErrorResponse>: From<<T as TryFrom<PaymentAdditionalData<'a, F>>>::Error>, { 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")?; let payment_method = payment_data .payment_attempt .payment_method .or(payment_method) .get_required_value("payment_method")?; let payment_method_type = payment_data .payment_attempt .payment_method_type .or(payment_method_type); let resource_id = match payment_data .payment_attempt .get_connector_payment_id() .map(ToString::to_string) { Some(id) => types::ResponseId::ConnectorTransactionId(id), None => types::ResponseId::NoResponseId, }; // [#44]: why should response be filled during request let response = Ok(types::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: None, incremental_authorization_allowed: None, charges: 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()); let order_details = payment_data .payment_intent .order_details .as_ref() .map(|order_details| { order_details .iter() .map(|data| { data.to_owned() .parse_value("OrderDetailsWithAmount") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "OrderDetailsWithAmount", }) .attach_printable("Unable to parse OrderDetailsWithAmount") }) .collect::<Result<Vec<_>, _>>() }) .transpose()?; let l2_l3_data = (state.conf.l2_l3_data_config.enabled && payment_data.is_l2_l3_enabled).then(|| { let shipping_address = unified_address.get_shipping(); let billing_address = unified_address.get_payment_billing(); let merchant_tax_registration_id = merchant_context .get_merchant_account() .get_merchant_tax_registration_id(); Box::new(types::L2L3Data { order_date: payment_data.payment_intent.order_date, tax_status: payment_data.payment_intent.tax_status, customer_tax_registration_id: customer.as_ref().and_then(|c| { c.tax_registration_id .as_ref() .map(|e| e.clone().into_inner()) }), order_details: order_details.clone(), discount_amount: payment_data.payment_intent.discount_amount, shipping_cost: payment_data.payment_intent.shipping_cost, shipping_amount_tax: payment_data.payment_intent.shipping_amount_tax, duty_amount: payment_data.payment_intent.duty_amount, order_tax_amount: payment_data .payment_attempt .net_amount .get_order_tax_amount(), merchant_order_reference_id: payment_data .payment_intent .merchant_order_reference_id .clone(), customer_id: payment_data.payment_intent.customer_id.clone(), billing_address_city: billing_address .as_ref() .and_then(|addr| addr.address.as_ref()) .and_then(|details| details.city.clone()), merchant_tax_registration_id, customer_name: customer .as_ref() .and_then(|c| c.name.as_ref().map(|e| e.clone().into_inner())), customer_email: payment_data.email, customer_phone_number: customer .as_ref() .and_then(|c| c.phone.as_ref().map(|e| e.clone().into_inner())), customer_phone_country_code: customer .as_ref() .and_then(|c| c.phone_country_code.clone()), shipping_details: shipping_address .and_then(|address| address.address.as_ref()) .cloned(), }) }); crate::logger::debug!("unified address details {:?}", unified_address); let 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, payment_method_type, 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: T::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_intent, &payment_data.payment_attempt, connector_id, )?, 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, raw_connector_response: None, is_payment_id_from_merchant: payment_data.payment_intent.is_payment_id_from_merchant, l2_l3_data, minor_amount_capturable: None, authorized_amount: None, }; Ok(router_data) } #[cfg(feature = "v1")] #[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, connector_metadata: 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, payment_method_type: payment_data.payment_attempt.payment_method_type, 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_intent, &payment_data.payment_attempt, connector_id, )?, 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, raw_connector_response: None, is_payment_id_from_merchant: payment_data.payment_intent.is_payment_id_from_merchant, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, }; Ok(router_data) } pub trait ToResponse<F, D, Op> where Self: Sized, Op: Debug, D: OperationSessionGetters<F>, { #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] fn generate_response( data: D, customer: Option<domain::Customer>, auth_flow: services::AuthFlow, 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>, ) -> RouterResponse<Self>; #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] fn generate_response( 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>; } /// Generate a response from the given Data. This should be implemented on a payment data object pub trait GenerateResponse<Response> where Self: Sized, { #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] fn generate_response( self, state: &SessionState, connector_http_status_code: Option<u16>, external_latency: Option<u128>, is_latency_header_enabled: Option<bool>, merchant_context: &domain::MerchantContext, profile: &domain::Profile, connector_response_data: Option<common_types::domain::ConnectorResponseData>, ) -> RouterResponse<Response>; } #[cfg(feature = "v2")] impl<F> GenerateResponse<api_models::payments::PaymentsCaptureResponse> for hyperswitch_domain_models::payments::PaymentCaptureData<F> where F: Clone, { fn generate_response( self, state: &SessionState, connector_http_status_code: Option<u16>, external_latency: Option<u128>, is_latency_header_enabled: Option<bool>, merchant_context: &domain::MerchantContext, profile: &domain::Profile, _connector_response_data: Option<common_types::domain::ConnectorResponseData>, ) -> RouterResponse<api_models::payments::PaymentsCaptureResponse> { let payment_intent = &self.payment_intent; let payment_attempt = &self.payment_attempt; let amount = api_models::payments::PaymentAmountDetailsResponse::foreign_from(( &payment_intent.amount_details, &payment_attempt.amount_details, )); let response = api_models::payments::PaymentsCaptureResponse { id: payment_intent.id.clone(), amount, status: payment_intent.status, }; let headers = connector_http_status_code .map(|status_code| { vec![( X_CONNECTOR_HTTP_STATUS_CODE.to_string(), Maskable::new_normal(status_code.to_string()), )] }) .unwrap_or_default(); Ok(services::ApplicationResponse::JsonWithHeaders(( response, headers, ))) } } #[cfg(feature = "v2")] impl<F> GenerateResponse<api_models::payments::PaymentsCancelResponse> for hyperswitch_domain_models::payments::PaymentCancelData<F> where F: Clone, { fn generate_response( self, state: &SessionState, connector_http_status_code: Option<u16>, external_latency: Option<u128>, is_latency_header_enabled: Option<bool>, merchant_context: &domain::MerchantContext, profile: &domain::Profile, _connector_response_data: Option<common_types::domain::ConnectorResponseData>, ) -> RouterResponse<api_models::payments::PaymentsCancelResponse> { let payment_intent = &self.payment_intent; let payment_attempt = &self.payment_attempt; let amount = api_models::payments::PaymentAmountDetailsResponse::foreign_from(( &payment_intent.amount_details, &payment_attempt.amount_details, )); let connector = payment_attempt .connector .as_ref() .and_then(|conn| api_enums::Connector::from_str(conn).ok()); let error = payment_attempt .error .as_ref() .map(api_models::payments::ErrorDetails::foreign_from); let response = api_models::payments::PaymentsCancelResponse { id: payment_intent.id.clone(), status: payment_intent.status, cancellation_reason: payment_attempt.cancellation_reason.clone(), amount, customer_id: payment_intent.customer_id.clone(), connector, created: payment_intent.created_at, payment_method_type: Some(payment_attempt.payment_method_type), payment_method_subtype: Some(payment_attempt.payment_method_subtype), attempts: None, return_url: payment_intent.return_url.clone(), error, }; let headers = connector_http_status_code .map(|status_code| { vec![( X_CONNECTOR_HTTP_STATUS_CODE.to_string(), Maskable::new_normal(status_code.to_string()), )] }) .unwrap_or_default(); Ok(services::ApplicationResponse::JsonWithHeaders(( response, headers, ))) } } #[cfg(feature = "v1")] impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsResponse where F: Clone, Op: Debug, D: OperationSessionGetters<F>, { #[allow(clippy::too_many_arguments)] fn generate_response( payment_data: D, customer: Option<domain::Customer>, auth_flow: services::AuthFlow, 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>, ) -> RouterResponse<Self> { let captures = payment_data .get_multiple_capture_data() .and_then(|multiple_capture_data| { multiple_capture_data .expand_captures .and_then(|should_expand| { should_expand.then_some( multiple_capture_data .get_all_captures() .into_iter() .cloned() .collect(), ) }) }); payments_to_payments_response( payment_data, captures, customer, auth_flow, base_url, &operation, connector_request_reference_id_config, connector_http_status_code, external_latency, is_latency_header_enabled, ) } } #[cfg(feature = "v1")] impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsSessionResponse where F: Clone, Op: Debug, D: OperationSessionGetters<F>, { #[allow(clippy::too_many_arguments)] fn generate_response( payment_data: D, _customer: Option<domain::Customer>, _auth_flow: services::AuthFlow, _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>, ) -> RouterResponse<Self> { Ok(services::ApplicationResponse::JsonWithHeaders(( Self { session_token: payment_data.get_sessions_token(), payment_id: payment_data.get_payment_attempt().payment_id.clone(), client_secret: payment_data .get_payment_intent() .client_secret .clone() .get_required_value("client_secret")? .into(), }, vec![], ))) } } #[cfg(feature = "v2")] impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsSessionResponse 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 { session_token: payment_data.get_sessions_token(), payment_id: payment_data.get_payment_intent().id.clone(), vault_details: payment_data.get_optional_external_vault_session_details(), }, vec![], ))) } } #[cfg(feature = "v1")] impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsDynamicTaxCalculationResponse where F: Clone, Op: Debug, D: OperationSessionGetters<F>, { #[allow(clippy::too_many_arguments)] fn generate_response( payment_data: D, _customer: Option<domain::Customer>, _auth_flow: services::AuthFlow, _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>, ) -> RouterResponse<Self> { let mut amount = payment_data.get_payment_intent().amount; let shipping_cost = payment_data.get_payment_intent().shipping_cost; if let Some(shipping_cost) = shipping_cost { amount = amount + shipping_cost; } let order_tax_amount = payment_data .get_payment_intent() .tax_details .clone() .and_then(|tax| { tax.payment_method_type .map(|a| a.order_tax_amount) .or_else(|| tax.default.map(|a| a.order_tax_amount)) }); if let Some(tax_amount) = order_tax_amount { amount = amount + tax_amount; } let currency = payment_data .get_payment_attempt() .currency .get_required_value("currency")?; Ok(services::ApplicationResponse::JsonWithHeaders(( Self { net_amount: amount, payment_id: payment_data.get_payment_attempt().payment_id.clone(), order_tax_amount, shipping_cost, display_amount: api_models::payments::DisplayAmountOnSdk::foreign_try_from(( amount, shipping_cost, order_tax_amount, currency, ))?, }, vec![], ))) } } #[cfg(feature = "v2")] impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsIntentResponse 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> { let payment_intent = payment_data.get_payment_intent(); let client_secret = payment_data.get_client_secret(); let is_cit_transaction = payment_intent.setup_future_usage.is_off_session(); let mandate_type = if payment_intent.customer_present == common_enums::PresenceOfCustomerDuringPayment::Absent { Some(api::MandateTransactionType::RecurringMandateTransaction) } else if is_cit_transaction { Some(api::MandateTransactionType::NewMandateTransaction) } else { None }; let payment_type = helpers::infer_payment_type( payment_intent.amount_details.order_amount.into(), mandate_type.as_ref(), ); Ok(services::ApplicationResponse::JsonWithHeaders(( Self { id: payment_intent.id.clone(), profile_id: payment_intent.profile_id.clone(), status: payment_intent.status, amount_details: api_models::payments::AmountDetailsResponse::foreign_from( payment_intent.amount_details.clone(), ), client_secret: client_secret.clone(), merchant_reference_id: payment_intent.merchant_reference_id.clone(), routing_algorithm_id: payment_intent.routing_algorithm_id.clone(), capture_method: payment_intent.capture_method, authentication_type: payment_intent.authentication_type, billing: payment_intent .billing_address .clone() .map(|billing| billing.into_inner()) .map(From::from), shipping: payment_intent .shipping_address .clone() .map(|shipping| shipping.into_inner()) .map(From::from), customer_id: payment_intent.customer_id.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, statement_descriptor: payment_intent.statement_descriptor.clone(), order_details: payment_intent.order_details.clone().map(|order_details| { order_details .into_iter() .map(|order_detail| order_detail.expose().convert_back()) .collect() }), allowed_payment_method_types: payment_intent.allowed_payment_method_types.clone(), metadata: payment_intent.metadata.clone(), connector_metadata: payment_intent.connector_metadata.clone(), feature_metadata: payment_intent .feature_metadata .clone() .map(|feature_metadata| feature_metadata.convert_back()), payment_link_enabled: payment_intent.enable_payment_link, payment_link_config: payment_intent .payment_link_config .clone() .map(ForeignFrom::foreign_from), request_incremental_authorization: payment_intent.request_incremental_authorization, split_txns_enabled: payment_intent.split_txns_enabled, 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, payment_type, enable_partial_authorization: payment_intent.enable_partial_authorization, }, vec![], ))) } } #[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> where F: Clone, { fn generate_response( self, state: &SessionState, connector_http_status_code: Option<u16>, external_latency: Option<u128>, is_latency_header_enabled: Option<bool>, merchant_context: &domain::MerchantContext, profile: &domain::Profile, connector_response_data: Option<common_types::domain::ConnectorResponseData>, ) -> RouterResponse<api_models::payments::PaymentsResponse> { let payment_intent = self.payment_intent; let payment_attempt = self.payment_attempt; let amount = api_models::payments::PaymentAmountDetailsResponse::foreign_from(( &payment_intent.amount_details, &payment_attempt.amount_details, )); let connector = payment_attempt .connector .clone() .get_required_value("connector") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Connector is none when constructing response")?; let merchant_connector_id = payment_attempt.merchant_connector_id.clone(); let error = payment_attempt .error .as_ref() .map(api_models::payments::ErrorDetails::foreign_from); let payment_address = self.payment_address; let raw_connector_response = connector_response_data.and_then(|data| data.raw_connector_response); let payment_method_data = Some(api_models::payments::PaymentMethodDataResponseWithBilling { payment_method_data: None, billing: payment_address .get_request_payment_method_billing() .cloned() .map(From::from), }); // TODO: Add support for other next actions, currently only supporting redirect to url let redirect_to_url = payment_intent.create_start_redirection_url( &state.base_url, merchant_context .get_merchant_account() .publishable_key .clone(), )?; let next_action = if payment_intent.status.is_in_terminal_state() { None } else { let next_action_containing_wait_screen = wait_screen_next_steps_check(payment_attempt.clone())?; let next_action_containing_sdk_upi_intent = extract_sdk_uri_information(payment_attempt.clone())?; payment_attempt .redirection_data .as_ref() .map(|_| api_models::payments::NextActionData::RedirectToUrl { redirect_to_url }) .or(next_action_containing_sdk_upi_intent.map(|sdk_uri_data| { api_models::payments::NextActionData::SdkUpiIntentInformation { sdk_uri: sdk_uri_data.sdk_uri, } })) .or(next_action_containing_wait_screen.map(|wait_screen_data| { api_models::payments::NextActionData::WaitScreenInformation { display_from_timestamp: wait_screen_data.display_from_timestamp, display_to_timestamp: wait_screen_data.display_to_timestamp, poll_config: wait_screen_data.poll_config, } })) }; let connector_token_details = payment_attempt .connector_token_details .and_then(Option::<api_models::payments::ConnectorTokenDetails>::foreign_from); let return_url = payment_intent .return_url .clone() .or(profile.return_url.clone()); let headers = connector_http_status_code .map(|status_code| { vec![( X_CONNECTOR_HTTP_STATUS_CODE.to_string(), Maskable::new_normal(status_code.to_string()), )] }) .unwrap_or_default(); let response = api_models::payments::PaymentsResponse { id: payment_intent.id.clone(), status: payment_intent.status, amount, customer_id: payment_intent.customer_id.clone(), connector: Some(connector), created: payment_intent.created_at, modified_at: payment_intent.modified_at, payment_method_data, payment_method_type: Some(payment_attempt.payment_method_type), payment_method_subtype: Some(payment_attempt.payment_method_subtype), next_action, connector_transaction_id: payment_attempt.connector_payment_id.clone(), connector_reference_id: payment_attempt.connector_response_reference_id.clone(), connector_token_details, merchant_connector_id, browser_info: None, error, return_url, authentication_type: payment_intent.authentication_type, authentication_type_applied: Some(payment_attempt.authentication_type), payment_method_id: payment_attempt.payment_method_id, attempts: None, billing: None, //TODO: add this shipping: None, //TODO: add this is_iframe_redirection_enabled: None, merchant_reference_id: payment_intent.merchant_reference_id.clone(), raw_connector_response, feature_metadata: payment_intent .feature_metadata .map(|feature_metadata| feature_metadata.convert_back()), metadata: payment_intent.metadata, }; Ok(services::ApplicationResponse::JsonWithHeaders(( response, headers, ))) } } #[cfg(feature = "v2")] impl<F> GenerateResponse<api_models::payments::PaymentsResponse> for hyperswitch_domain_models::payments::PaymentStatusData<F> where F: Clone, { fn generate_response( self, state: &SessionState, connector_http_status_code: Option<u16>, external_latency: Option<u128>, is_latency_header_enabled: Option<bool>, merchant_context: &domain::MerchantContext, profile: &domain::Profile, connector_response_data: Option<common_types::domain::ConnectorResponseData>, ) -> RouterResponse<api_models::payments::PaymentsResponse> { let payment_intent = self.payment_intent; let payment_attempt = &self.payment_attempt; let amount = api_models::payments::PaymentAmountDetailsResponse::foreign_from(( &payment_intent.amount_details, &payment_attempt.amount_details, )); let connector = payment_attempt.connector.clone(); let merchant_connector_id = payment_attempt.merchant_connector_id.clone(); let error = payment_attempt .error .as_ref() .map(api_models::payments::ErrorDetails::foreign_from); let attempts = self.attempts.as_ref().map(|attempts| { attempts .iter() .map(api_models::payments::PaymentAttemptResponse::foreign_from) .collect() }); let payment_method_data = Some(api_models::payments::PaymentMethodDataResponseWithBilling { payment_method_data: None, billing: self .payment_address .get_request_payment_method_billing() .cloned() .map(From::from), }); let raw_connector_response = connector_response_data.and_then(|data| data.raw_connector_response); let connector_token_details = self .payment_attempt .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()); let headers = connector_http_status_code .map(|status_code| { vec![( X_CONNECTOR_HTTP_STATUS_CODE.to_string(), Maskable::new_normal(status_code.to_string()), )] }) .unwrap_or_default(); let response = api_models::payments::PaymentsResponse { id: payment_intent.id.clone(), status: payment_intent.status, amount, customer_id: payment_intent.customer_id.clone(), connector, billing: self .payment_address .get_payment_billing() .cloned() .map(From::from), shipping: self.payment_address.get_shipping().cloned().map(From::from), created: payment_intent.created_at, modified_at: payment_intent.modified_at, payment_method_data, 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: payment_attempt.connector_response_reference_id.clone(), merchant_connector_id, browser_info: None, connector_token_details, payment_method_id: payment_attempt.payment_method_id.clone(), error, authentication_type_applied: payment_attempt.authentication_applied, authentication_type: payment_intent.authentication_type, next_action: None, attempts, return_url, is_iframe_redirection_enabled: payment_intent.is_iframe_redirection_enabled, merchant_reference_id: payment_intent.merchant_reference_id.clone(), raw_connector_response, feature_metadata: payment_intent .feature_metadata .map(|feature_metadata| feature_metadata.convert_back()), metadata: payment_intent.metadata, }; Ok(services::ApplicationResponse::JsonWithHeaders(( response, headers, ))) } } #[cfg(feature = "v2")] impl<F> GenerateResponse<api_models::payments::PaymentAttemptResponse> for hyperswitch_domain_models::payments::PaymentAttemptRecordData<F> where F: Clone, { fn generate_response( self, _state: &SessionState, _connector_http_status_code: Option<u16>, _external_latency: Option<u128>, _is_latency_header_enabled: Option<bool>, _merchant_context: &domain::MerchantContext, _profile: &domain::Profile, _connector_response_data: Option<common_types::domain::ConnectorResponseData>, ) -> RouterResponse<api_models::payments::PaymentAttemptResponse> { let payment_attempt = self.payment_attempt; let response = api_models::payments::PaymentAttemptResponse::foreign_from(&payment_attempt); Ok(services::ApplicationResponse::JsonWithHeaders(( response, vec![], ))) } } #[cfg(feature = "v2")] impl<F> GenerateResponse<api_models::payments::PaymentAttemptRecordResponse> for hyperswitch_domain_models::payments::PaymentAttemptRecordData<F> where F: Clone, { fn generate_response( self, _state: &SessionState, _connector_http_status_code: Option<u16>, _external_latency: Option<u128>, _is_latency_header_enabled: Option<bool>, _merchant_context: &domain::MerchantContext, _profile: &domain::Profile, _connector_response_data: Option<common_types::domain::ConnectorResponseData>, ) -> RouterResponse<api_models::payments::PaymentAttemptRecordResponse> { let payment_attempt = self.payment_attempt; let payment_intent = self.payment_intent; let response = api_models::payments::PaymentAttemptRecordResponse { 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() .map(api_models::payments::FeatureMetadata::foreign_from), payment_attempt_feature_metadata: payment_attempt .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, vec![], ))) } } #[cfg(feature = "v1")] impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsPostSessionTokensResponse where F: Clone, Op: Debug, D: OperationSessionGetters<F>, { fn generate_response( payment_data: D, _customer: Option<domain::Customer>, _auth_flow: services::AuthFlow, _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>, ) -> RouterResponse<Self> { let papal_sdk_next_action = paypal_sdk_next_steps_check(payment_data.get_payment_attempt().clone())?; let next_action = papal_sdk_next_action.map(|paypal_next_action_data| { api_models::payments::NextActionData::InvokeSdkClient { next_action_data: paypal_next_action_data, } }); Ok(services::ApplicationResponse::JsonWithHeaders(( Self { payment_id: payment_data.get_payment_intent().payment_id.clone(), next_action, status: payment_data.get_payment_intent().status, }, vec![], ))) } } #[cfg(feature = "v1")] impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsUpdateMetadataResponse where F: Clone, Op: Debug, D: OperationSessionGetters<F>, { fn generate_response( payment_data: D, _customer: Option<domain::Customer>, _auth_flow: services::AuthFlow, _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>, ) -> RouterResponse<Self> { Ok(services::ApplicationResponse::JsonWithHeaders(( Self { payment_id: payment_data.get_payment_intent().payment_id.clone(), metadata: payment_data .get_payment_intent() .metadata .clone() .map(Secret::new), }, vec![], ))) } } impl ForeignTryFrom<(MinorUnit, Option<MinorUnit>, Option<MinorUnit>, Currency)> for api_models::payments::DisplayAmountOnSdk { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( (net_amount, shipping_cost, order_tax_amount, currency): ( MinorUnit, Option<MinorUnit>, Option<MinorUnit>, Currency, ), ) -> Result<Self, Self::Error> { let major_unit_convertor = StringMajorUnitForConnector; let sdk_net_amount = major_unit_convertor .convert(net_amount, currency) .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "Failed to convert net_amount to base unit".to_string(), }) .attach_printable("Failed to convert net_amount to string major unit")?; let sdk_shipping_cost = shipping_cost .map(|cost| { major_unit_convertor .convert(cost, currency) .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "Failed to convert shipping_cost to base unit".to_string(), }) .attach_printable("Failed to convert shipping_cost to string major unit") }) .transpose()?; let sdk_order_tax_amount = order_tax_amount .map(|cost| { major_unit_convertor .convert(cost, currency) .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "Failed to convert order_tax_amount to base unit".to_string(), }) .attach_printable("Failed to convert order_tax_amount to string major unit") }) .transpose()?; Ok(Self { net_amount: sdk_net_amount, shipping_cost: sdk_shipping_cost, order_tax_amount: sdk_order_tax_amount, }) } } #[cfg(feature = "v1")] impl<F, Op, D> ToResponse<F, D, Op> for api::VerifyResponse where F: Clone, Op: Debug, D: OperationSessionGetters<F>, { #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] fn generate_response( _data: D, _customer: Option<domain::Customer>, _auth_flow: services::AuthFlow, _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>, ) -> RouterResponse<Self> { todo!() } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] fn generate_response( payment_data: D, customer: Option<domain::Customer>, _auth_flow: services::AuthFlow, _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>, ) -> RouterResponse<Self> { let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> = payment_data .get_payment_attempt() .payment_method_data .clone() .map(|data| data.parse_value("payment_method_data")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "payment_method_data", })?; let payment_method_data_response = additional_payment_method_data.map(api::PaymentMethodDataResponse::from); Ok(services::ApplicationResponse::JsonWithHeaders(( Self { verify_id: Some(payment_data.get_payment_intent().payment_id.clone()), merchant_id: Some(payment_data.get_payment_intent().merchant_id.clone()), client_secret: payment_data .get_payment_intent() .client_secret .clone() .map(Secret::new), customer_id: customer.as_ref().map(|x| x.customer_id.clone()), email: customer .as_ref() .and_then(|cus| cus.email.as_ref().map(|s| s.to_owned())), name: customer .as_ref() .and_then(|cus| cus.name.as_ref().map(|s| s.to_owned())), phone: customer .as_ref() .and_then(|cus| cus.phone.as_ref().map(|s| s.to_owned())), mandate_id: payment_data .get_mandate_id() .and_then(|mandate_ids| mandate_ids.mandate_id.clone()), payment_method: payment_data.get_payment_attempt().payment_method, payment_method_data: payment_method_data_response, payment_token: payment_data.get_token().map(ToString::to_string), error_code: payment_data.get_payment_attempt().clone().error_code, error_message: payment_data.get_payment_attempt().clone().error_message, }, vec![], ))) } } #[cfg(feature = "v2")] #[instrument(skip_all)] // try to use router data here so that already validated things , we don't want to repeat the validations. // Add internal value not found and external value not found so that we can give 500 / Internal server error for internal value not found #[allow(clippy::too_many_arguments)] pub fn payments_to_payments_response<Op, F: Clone, D>( _payment_data: D, _captures: Option<Vec<storage::Capture>>, _customer: Option<domain::Customer>, _auth_flow: services::AuthFlow, _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>, ) -> RouterResponse<api_models::payments::PaymentsResponse> where Op: Debug, D: OperationSessionGetters<F>, { todo!() } #[cfg(feature = "v1")] #[instrument(skip_all)] // try to use router data here so that already validated things , we don't want to repeat the validations. // Add internal value not found and external value not found so that we can give 500 / Internal server error for internal value not found #[allow(clippy::too_many_arguments)] pub fn payments_to_payments_response<Op, F: Clone, D>( payment_data: D, captures: Option<Vec<storage::Capture>>, customer: Option<domain::Customer>, _auth_flow: services::AuthFlow, 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>, ) -> RouterResponse<api::PaymentsResponse> where Op: Debug, D: OperationSessionGetters<F>, { use std::ops::Not; use hyperswitch_interfaces::consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}; let payment_attempt = payment_data.get_payment_attempt().clone(); let payment_intent = payment_data.get_payment_intent().clone(); let payment_link_data = payment_data.get_payment_link_data(); let currency = payment_attempt .currency .as_ref() .get_required_value("currency")?; let amount = currency .to_currency_base_unit( payment_attempt .net_amount .get_total_amount() .get_amount_as_i64(), ) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "amount", })?; let mandate_id = payment_attempt.mandate_id.clone(); let refunds_response = payment_data.get_refunds().is_empty().not().then(|| { payment_data .get_refunds() .into_iter() .map(ForeignInto::foreign_into) .collect() }); let disputes_response = payment_data.get_disputes().is_empty().not().then(|| { payment_data .get_disputes() .into_iter() .map(ForeignInto::foreign_into) .collect() }); let incremental_authorizations_response = payment_data.get_authorizations().is_empty().not().then(|| { payment_data .get_authorizations() .into_iter() .map(ForeignInto::foreign_into) .collect() }); let external_authentication_details = payment_data .get_authentication() .map(ForeignInto::foreign_into); let attempts_response = payment_data.get_attempts().map(|attempts| { attempts .into_iter() .map(ForeignInto::foreign_into) .collect() }); let captures_response = captures.map(|captures| { captures .into_iter() .map(ForeignInto::foreign_into) .collect() }); let merchant_id = payment_attempt.merchant_id.to_owned(); let payment_method_type = payment_attempt .payment_method_type .as_ref() .map(ToString::to_string) .unwrap_or("".to_owned()); let payment_method = payment_attempt .payment_method .as_ref() .map(ToString::to_string) .unwrap_or("".to_owned()); let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> = payment_attempt .payment_method_data .clone() .and_then(|data| match data { serde_json::Value::Null => None, // This is to handle the case when the payment_method_data is null _ => Some(data.parse_value("AdditionalPaymentData")), }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse the AdditionalPaymentData from payment_attempt.payment_method_data")?; let surcharge_details = payment_attempt .net_amount .get_surcharge_amount() .map(|surcharge_amount| RequestSurchargeDetails { surcharge_amount, tax_amount: payment_attempt.net_amount.get_tax_on_surcharge(), }); let merchant_decision = payment_intent.merchant_decision.to_owned(); let frm_message = payment_data.get_frm_message().map(FrmMessage::foreign_from); let payment_method_data = additional_payment_method_data.map(api::PaymentMethodDataResponse::from); let payment_method_data_response = (payment_method_data.is_some() || payment_data .get_address() .get_request_payment_method_billing() .is_some()) .then_some(api_models::payments::PaymentMethodDataResponseWithBilling { payment_method_data, billing: payment_data .get_address() .get_request_payment_method_billing() .cloned() .map(From::from), }); let mut headers = connector_http_status_code .map(|status_code| { vec![( X_CONNECTOR_HTTP_STATUS_CODE.to_string(), Maskable::new_normal(status_code.to_string()), )] }) .unwrap_or_default(); if let Some(payment_confirm_source) = payment_intent.payment_confirm_source { headers.push(( X_PAYMENT_CONFIRM_SOURCE.to_string(), Maskable::new_normal(payment_confirm_source.to_string()), )) } // For the case when we don't have Customer data directly stored in Payment intent let customer_table_response: Option<CustomerDetailsResponse> = customer.as_ref().map(ForeignInto::foreign_into); // If we have customer data in Payment Intent and if the customer is not deleted, We are populating the Retrieve response from the // same. If the customer is deleted then we use the customer table to populate customer details let customer_details_response = if let Some(customer_details_raw) = payment_intent.customer_details.clone() { let customer_details_encrypted = serde_json::from_value::<CustomerData>(customer_details_raw.into_inner().expose()); if let Ok(customer_details_encrypted_data) = customer_details_encrypted { Some(CustomerDetailsResponse { id: customer_table_response .as_ref() .and_then(|customer_data| customer_data.id.clone()), name: customer_table_response .as_ref() .and_then(|customer_data| customer_data.name.clone()) .or(customer_details_encrypted_data .name .or(customer.as_ref().and_then(|customer| { customer.name.as_ref().map(|name| name.clone().into_inner()) }))), email: customer_table_response .as_ref() .and_then(|customer_data| customer_data.email.clone()) .or(customer_details_encrypted_data.email.or(customer .as_ref() .and_then(|customer| customer.email.clone().map(pii::Email::from)))), phone: customer_table_response .as_ref() .and_then(|customer_data| customer_data.phone.clone()) .or(customer_details_encrypted_data .phone .or(customer.as_ref().and_then(|customer| { customer .phone .as_ref() .map(|phone| phone.clone().into_inner()) }))), phone_country_code: customer_table_response .as_ref() .and_then(|customer_data| customer_data.phone_country_code.clone()) .or(customer_details_encrypted_data .phone_country_code .or(customer .as_ref() .and_then(|customer| customer.phone_country_code.clone()))), }) } else { customer_table_response } } else { customer_table_response }; headers.extend( external_latency .map(|latency| { vec![( X_HS_LATENCY.to_string(), Maskable::new_normal(latency.to_string()), )] }) .unwrap_or_default(), ); let connector_name = payment_attempt.connector.as_deref().unwrap_or_default(); let router_return_url = helpers::create_redirect_url( &base_url.to_string(), &payment_attempt, connector_name, payment_data.get_creds_identifier(), ); let output = if payments::is_start_pay(&operation) && payment_attempt.authentication_data.is_some() { let redirection_data = payment_attempt .authentication_data .clone() .get_required_value("redirection_data")?; let form: RedirectForm = serde_json::from_value(redirection_data) .map_err(|_| errors::ApiErrorResponse::InternalServerError)?; services::ApplicationResponse::Form(Box::new(services::RedirectionFormData { redirect_form: form, payment_method_data: payment_data.get_payment_method_data().cloned(), amount, currency: currency.to_string(), })) } else { let mut next_action_response = None; // Early exit for terminal payment statuses - don't evaluate next_action at all if payment_intent.status.is_in_terminal_state() { next_action_response = None; } else { let bank_transfer_next_steps = bank_transfer_next_steps_check(payment_attempt.clone())?; let next_action_voucher = voucher_next_steps_check(payment_attempt.clone())?; let next_action_mobile_payment = mobile_payment_next_steps_check(&payment_attempt)?; let next_action_containing_qr_code_url = qr_code_next_steps_check(payment_attempt.clone())?; let papal_sdk_next_action = paypal_sdk_next_steps_check(payment_attempt.clone())?; let next_action_containing_fetch_qr_code_url = fetch_qr_code_url_next_steps_check(payment_attempt.clone())?; let next_action_containing_wait_screen = wait_screen_next_steps_check(payment_attempt.clone())?; let next_action_containing_sdk_upi_intent = extract_sdk_uri_information(payment_attempt.clone())?; let next_action_invoke_hidden_frame = next_action_invoke_hidden_frame(&payment_attempt)?; if payment_intent.status == enums::IntentStatus::RequiresCustomerAction || bank_transfer_next_steps.is_some() || next_action_voucher.is_some() || next_action_containing_qr_code_url.is_some() || next_action_containing_wait_screen.is_some() || next_action_containing_sdk_upi_intent.is_some() || papal_sdk_next_action.is_some() || next_action_containing_fetch_qr_code_url.is_some() || payment_data.get_authentication().is_some() { next_action_response = bank_transfer_next_steps .map(|bank_transfer| { api_models::payments::NextActionData::DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: bank_transfer, } }) .or(next_action_voucher.map(|voucher_data| { api_models::payments::NextActionData::DisplayVoucherInformation { voucher_details: voucher_data, } })) .or(next_action_mobile_payment.map(|mobile_payment_data| { api_models::payments::NextActionData::CollectOtp { consent_data_required: mobile_payment_data.consent_data_required, } })) .or(next_action_containing_qr_code_url.map(|qr_code_data| { api_models::payments::NextActionData::foreign_from(qr_code_data) })) .or(next_action_containing_fetch_qr_code_url.map(|fetch_qr_code_data| { api_models::payments::NextActionData::FetchQrCodeInformation { qr_code_fetch_url: fetch_qr_code_data.qr_code_fetch_url } })) .or(papal_sdk_next_action.map(|paypal_next_action_data| { api_models::payments::NextActionData::InvokeSdkClient{ next_action_data: paypal_next_action_data } })) .or(next_action_containing_sdk_upi_intent.map(|sdk_uri_data| { api_models::payments::NextActionData::SdkUpiIntentInformation { sdk_uri: sdk_uri_data.sdk_uri, } })) .or(next_action_containing_wait_screen.map(|wait_screen_data| { api_models::payments::NextActionData::WaitScreenInformation { display_from_timestamp: wait_screen_data.display_from_timestamp, display_to_timestamp: wait_screen_data.display_to_timestamp, poll_config: wait_screen_data.poll_config, } })) .or(payment_attempt.authentication_data.as_ref().map(|_| { // Check if iframe redirection is enabled in the business profile let redirect_url = helpers::create_startpay_url( base_url, &payment_attempt, &payment_intent, ); // Check if redirection inside popup is enabled in the payment intent if payment_intent.is_iframe_redirection_enabled.unwrap_or(false) { api_models::payments::NextActionData::RedirectInsidePopup { popup_url: redirect_url, redirect_response_url:router_return_url } } else { api_models::payments::NextActionData::RedirectToUrl { redirect_to_url: redirect_url, } } })) .or(match payment_data.get_authentication(){ Some(authentication_store) => { let authentication = &authentication_store.authentication; if payment_intent.status == common_enums::IntentStatus::RequiresCustomerAction && authentication_store.cavv.is_none() && authentication.is_separate_authn_required(){ // if preAuthn and separate authentication needed. let poll_config = payment_data.get_poll_config().unwrap_or_default(); let request_poll_id = core_utils::get_external_authentication_request_poll_id(&payment_intent.payment_id); let payment_connector_name = payment_attempt.connector .as_ref() .get_required_value("connector")?; let is_jwt_flow = authentication.is_jwt_flow() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to determine if the authentication is JWT flow")?; Some(api_models::payments::NextActionData::ThreeDsInvoke { three_ds_data: api_models::payments::ThreeDsData { three_ds_authentication_url: helpers::create_authentication_url(base_url, &payment_attempt), three_ds_authorize_url: helpers::create_authorize_url( base_url, &payment_attempt, payment_connector_name, ), three_ds_method_details: authentication.three_ds_method_url.as_ref().zip(authentication.three_ds_method_data.as_ref()).map(|(three_ds_method_url,three_ds_method_data )|{ api_models::payments::ThreeDsMethodData::AcsThreeDsMethodData { three_ds_method_data_submission: true, three_ds_method_data: Some(three_ds_method_data.clone()), three_ds_method_url: Some(three_ds_method_url.to_owned()), three_ds_method_key: if is_jwt_flow { Some(api_models::payments::ThreeDsMethodKey::JWT) } else { Some(api_models::payments::ThreeDsMethodKey::ThreeDsMethodData) }, // In JWT flow, we need to wait for post message to get the result consume_post_message_for_three_ds_method_completion: is_jwt_flow, } }).unwrap_or(api_models::payments::ThreeDsMethodData::AcsThreeDsMethodData { three_ds_method_data_submission: false, three_ds_method_data: None, three_ds_method_url: None, three_ds_method_key: None, consume_post_message_for_three_ds_method_completion: false, }), poll_config: api_models::payments::PollConfigResponse {poll_id: request_poll_id, delay_in_secs: poll_config.delay_in_secs, frequency: poll_config.frequency}, message_version: authentication.message_version.as_ref() .map(|version| version.to_string()), directory_server_id: authentication.directory_server_id.clone(), }, }) }else{ None } }, None => None }) .or(match next_action_invoke_hidden_frame{ Some(threeds_invoke_data) => Some(construct_connector_invoke_hidden_frame( threeds_invoke_data, )?), None => None }); } }; // next action check for third party sdk session (for ex: Apple pay through trustpay has third party sdk session response) if third_party_sdk_session_next_action(&payment_attempt, operation) { next_action_response = Some( api_models::payments::NextActionData::ThirdPartySdkSessionToken { session_token: payment_data.get_sessions_token().first().cloned(), }, ) } let routed_through = payment_attempt.connector.clone(); let connector_label = routed_through.as_ref().and_then(|connector_name| { core_utils::get_connector_label( payment_intent.business_country, payment_intent.business_label.as_ref(), payment_attempt.business_sub_label.as_ref(), connector_name, ) }); let mandate_data = payment_data.get_setup_mandate().map(|d| api::MandateData { 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 { amount: i.amount, currency: i.currency, start_date: i.start_date, end_date: i.end_date, metadata: i.metadata, })) } hyperswitch_domain_models::mandates::MandateDataType::SingleUse(i) => { api::MandateType::SingleUse(api::payments::MandateAmountData { amount: i.amount, currency: i.currency, start_date: i.start_date, end_date: i.end_date, metadata: i.metadata, }) } hyperswitch_domain_models::mandates::MandateDataType::MultiUse(None) => { api::MandateType::MultiUse(None) } }), update_mandate_id: d.update_mandate_id.clone(), }); let order_tax_amount = payment_data .get_payment_attempt() .net_amount .get_order_tax_amount() .or_else(|| { payment_data .get_payment_intent() .tax_details .clone() .and_then(|tax| { tax.payment_method_type .map(|a| a.order_tax_amount) .or_else(|| tax.default.map(|a| a.order_tax_amount)) }) }); let connector_mandate_id = payment_data.get_mandate_id().and_then(|mandate| { mandate .mandate_reference_id .as_ref() .and_then(|mandate_ref| match mandate_ref { api_models::payments::MandateReferenceId::ConnectorMandateId( connector_mandate_reference_id, ) => connector_mandate_reference_id.get_connector_mandate_id(), _ => None, }) }); let connector_transaction_id = payment_attempt .get_connector_payment_id() .map(ToString::to_string); let manual_retry_allowed = match payment_data.get_is_manual_retry_enabled() { Some(true) => helpers::is_manual_retry_allowed( &payment_intent.status, &payment_attempt.status, connector_request_reference_id_config, &merchant_id, ), Some(false) | None => None, }; let payments_response = api::PaymentsResponse { payment_id: payment_intent.payment_id, merchant_id: payment_intent.merchant_id, status: payment_intent.status, amount: payment_attempt.net_amount.get_order_amount(), net_amount: payment_attempt.get_total_amount(), amount_capturable: payment_attempt.amount_capturable, amount_received: payment_intent.amount_captured, connector: routed_through, client_secret: payment_intent.client_secret.map(Secret::new), created: Some(payment_intent.created_at), currency: currency.to_string(), customer_id: customer.as_ref().map(|cus| cus.clone().customer_id), customer: customer_details_response, description: payment_intent.description, refunds: refunds_response, disputes: disputes_response, attempts: attempts_response, captures: captures_response, mandate_id, mandate_data, setup_future_usage: payment_attempt.setup_future_usage_applied, off_session: payment_intent.off_session, capture_on: None, capture_method: payment_attempt.capture_method, payment_method: payment_attempt.payment_method, payment_method_data: payment_method_data_response, payment_token: payment_attempt.payment_token, shipping: payment_data .get_address() .get_shipping() .cloned() .map(From::from), billing: payment_data .get_address() .get_payment_billing() .cloned() .map(From::from), order_details: payment_intent.order_details, email: customer .as_ref() .and_then(|cus| cus.email.as_ref().map(|s| s.to_owned())), name: customer .as_ref() .and_then(|cus| cus.name.as_ref().map(|s| s.to_owned())), phone: customer .as_ref() .and_then(|cus| cus.phone.as_ref().map(|s| s.to_owned())), return_url: payment_intent.return_url, authentication_type: payment_attempt.authentication_type, statement_descriptor_name: payment_intent.statement_descriptor_name, statement_descriptor_suffix: payment_intent.statement_descriptor_suffix, next_action: next_action_response, cancellation_reason: payment_attempt.cancellation_reason, error_code: payment_attempt .error_code .filter(|code| code != NO_ERROR_CODE), error_message: payment_attempt .error_reason .or(payment_attempt.error_message) .filter(|message| message != NO_ERROR_MESSAGE), unified_code: payment_attempt.unified_code, unified_message: payment_attempt.unified_message, payment_experience: payment_attempt.payment_experience, payment_method_type: payment_attempt.payment_method_type, connector_label, business_country: payment_intent.business_country, business_label: payment_intent.business_label, business_sub_label: payment_attempt.business_sub_label, allowed_payment_method_types: payment_intent.allowed_payment_method_types, ephemeral_key: payment_data .get_ephemeral_key() .map(ForeignFrom::foreign_from), manual_retry_allowed, connector_transaction_id, frm_message, metadata: payment_intent.metadata, connector_metadata: payment_intent.connector_metadata, feature_metadata: payment_intent.feature_metadata, reference_id: payment_attempt.connector_response_reference_id, payment_link: payment_link_data, profile_id: payment_intent.profile_id, surcharge_details, attempt_count: payment_intent.attempt_count, merchant_decision, merchant_connector_id: payment_attempt.merchant_connector_id, incremental_authorization_allowed: payment_intent.incremental_authorization_allowed, authorization_count: payment_intent.authorization_count, incremental_authorizations: incremental_authorizations_response, external_authentication_details, external_3ds_authentication_attempted: payment_attempt .external_three_ds_authentication_attempted, expires_on: payment_intent.session_expiry, fingerprint: payment_intent.fingerprint_id, browser_info: payment_attempt.browser_info, payment_method_id: payment_attempt.payment_method_id, network_transaction_id: payment_attempt.network_transaction_id, payment_method_status: payment_data .get_payment_method_info() .map(|info| info.status), updated: Some(payment_intent.modified_at), split_payments: payment_attempt.charges, frm_metadata: payment_intent.frm_metadata, merchant_order_reference_id: payment_intent.merchant_order_reference_id, order_tax_amount, connector_mandate_id, mit_category: payment_intent.mit_category, shipping_cost: payment_intent.shipping_cost, capture_before: payment_attempt.capture_before, extended_authorization_applied: payment_attempt.extended_authorization_applied, card_discovery: payment_attempt.card_discovery, force_3ds_challenge: payment_intent.force_3ds_challenge, force_3ds_challenge_trigger: payment_intent.force_3ds_challenge_trigger, 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(), payment_channel: payment_intent.payment_channel, enable_partial_authorization: payment_intent.enable_partial_authorization, enable_overcapture: payment_intent.enable_overcapture, is_overcapture_enabled: payment_attempt.is_overcapture_enabled, network_details: payment_attempt .network_details .map(NetworkDetails::foreign_from), is_stored_credential: payment_attempt.is_stored_credential, request_extended_authorization: payment_attempt.request_extended_authorization, }; services::ApplicationResponse::JsonWithHeaders((payments_response, headers)) }; metrics::PAYMENT_OPS_COUNT.add( 1, router_env::metric_attributes!( ("operation", format!("{:?}", operation)), ("merchant", merchant_id.clone()), ("payment_method_type", payment_method_type), ("payment_method", payment_method), ), ); Ok(output) } #[cfg(feature = "v1")] pub fn third_party_sdk_session_next_action<Op>( payment_attempt: &storage::PaymentAttempt, operation: &Op, ) -> bool where Op: Debug, { // If the operation is confirm, we will send session token response in next action if format!("{operation:?}").eq("PaymentConfirm") { let condition1 = payment_attempt .connector .as_ref() .map(|connector| { matches!(connector.as_str(), "trustpay") || matches!(connector.as_str(), "payme") }) .and_then(|is_connector_supports_third_party_sdk| { if is_connector_supports_third_party_sdk { payment_attempt .payment_method .map(|pm| matches!(pm, diesel_models::enums::PaymentMethod::Wallet)) } else { Some(false) } }) .unwrap_or(false); // This condition to be triggered for open banking connectors, third party SDK session token will be provided let condition2 = payment_attempt .connector .as_ref() .map(|connector| matches!(connector.as_str(), "plaid")) .and_then(|is_connector_supports_third_party_sdk| { if is_connector_supports_third_party_sdk { payment_attempt .payment_method .map(|pm| matches!(pm, diesel_models::enums::PaymentMethod::OpenBanking)) .and_then(|first_match| { payment_attempt .payment_method_type .map(|pmt| { matches!( pmt, diesel_models::enums::PaymentMethodType::OpenBankingPIS ) }) .map(|second_match| first_match && second_match) }) } else { Some(false) } }) .unwrap_or(false); condition1 || condition2 } else { false } } pub fn qr_code_next_steps_check( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::QrCodeInformation>> { let qr_code_steps: Option<Result<api_models::payments::QrCodeInformation, _>> = payment_attempt .connector_metadata .map(|metadata| metadata.parse_value("QrCodeInformation")); let qr_code_instructions = qr_code_steps.transpose().ok().flatten(); Ok(qr_code_instructions) } pub fn paypal_sdk_next_steps_check( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::SdkNextActionData>> { let paypal_connector_metadata: Option<Result<api_models::payments::SdkNextActionData, _>> = payment_attempt.connector_metadata.map(|metadata| { metadata.parse_value("SdkNextActionData").map_err(|_| { crate::logger::warn!( "SdkNextActionData parsing failed for paypal_connector_metadata" ) }) }); let paypal_next_steps = paypal_connector_metadata.transpose().ok().flatten(); Ok(paypal_next_steps) } pub fn fetch_qr_code_url_next_steps_check( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::FetchQrCodeInformation>> { let qr_code_steps: Option<Result<api_models::payments::FetchQrCodeInformation, _>> = payment_attempt .connector_metadata .map(|metadata| metadata.parse_value("FetchQrCodeInformation")); let qr_code_fetch_url = qr_code_steps.transpose().ok().flatten(); Ok(qr_code_fetch_url) } pub fn extract_sdk_uri_information( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::SdkUpiIntentInformation>> { let sdk_uri_steps: Option<Result<api_models::payments::SdkUpiIntentInformation, _>> = payment_attempt .connector_metadata .map(|metadata| metadata.parse_value("SdkUpiIntentInformation")); let sdk_uri_information = sdk_uri_steps.transpose().ok().flatten(); Ok(sdk_uri_information) } pub fn wait_screen_next_steps_check( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::WaitScreenInstructions>> { let display_info_with_timer_steps: Option< Result<api_models::payments::WaitScreenInstructions, _>, > = payment_attempt .connector_metadata .map(|metadata| metadata.parse_value("WaitScreenInstructions")); let display_info_with_timer_instructions = display_info_with_timer_steps.transpose().ok().flatten(); Ok(display_info_with_timer_instructions) } pub fn next_action_invoke_hidden_frame( payment_attempt: &storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::PaymentsConnectorThreeDsInvokeData>> { let connector_three_ds_invoke_data: Option< Result<api_models::payments::PaymentsConnectorThreeDsInvokeData, _>, > = payment_attempt .connector_metadata .clone() .map(|metadata| metadata.parse_value("PaymentsConnectorThreeDsInvokeData")); let three_ds_invoke_data = connector_three_ds_invoke_data.transpose().ok().flatten(); Ok(three_ds_invoke_data) } pub fn construct_connector_invoke_hidden_frame( connector_three_ds_invoke_data: api_models::payments::PaymentsConnectorThreeDsInvokeData, ) -> RouterResult<api_models::payments::NextActionData> { let iframe_data = api_models::payments::IframeData::ThreedsInvokeAndCompleteAutorize { three_ds_method_data_submission: connector_three_ds_invoke_data .three_ds_method_data_submission, three_ds_method_data: Some(connector_three_ds_invoke_data.three_ds_method_data), three_ds_method_url: connector_three_ds_invoke_data.three_ds_method_url, directory_server_id: connector_three_ds_invoke_data.directory_server_id, message_version: connector_three_ds_invoke_data.message_version, }; Ok(api_models::payments::NextActionData::InvokeHiddenIframe { iframe_data }) } #[cfg(feature = "v1")] impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::PaymentsResponse { fn foreign_from((pi, pa): (storage::PaymentIntent, storage::PaymentAttempt)) -> Self { let connector_transaction_id = pa.get_connector_payment_id().map(ToString::to_string); Self { payment_id: pi.payment_id, merchant_id: pi.merchant_id, status: pi.status, amount: pi.amount, amount_capturable: pa.amount_capturable, client_secret: pi.client_secret.map(|s| s.into()), created: Some(pi.created_at), currency: pi.currency.map(|c| c.to_string()).unwrap_or_default(), description: pi.description, metadata: pi.metadata, order_details: pi.order_details, customer_id: pi.customer_id.clone(), connector: pa.connector, payment_method: pa.payment_method, payment_method_type: pa.payment_method_type, business_label: pi.business_label, business_country: pi.business_country, business_sub_label: pa.business_sub_label, setup_future_usage: pi.setup_future_usage, capture_method: pa.capture_method, authentication_type: pa.authentication_type, connector_transaction_id, attempt_count: pi.attempt_count, profile_id: pi.profile_id, merchant_connector_id: pa.merchant_connector_id, payment_method_data: pa.payment_method_data.and_then(|data| { match data.parse_value("PaymentMethodDataResponseWithBilling") { Ok(parsed_data) => Some(parsed_data), Err(e) => { router_env::logger::error!("Failed to parse 'PaymentMethodDataResponseWithBilling' from payment method data. Error: {e:?}"); None } } }), merchant_order_reference_id: pi.merchant_order_reference_id, customer: pi.customer_details.and_then(|customer_details| match customer_details.into_inner().expose().parse_value::<CustomerData>("CustomerData"){ Ok(parsed_data) => Some( CustomerDetailsResponse { id: pi.customer_id, name: parsed_data.name, phone: parsed_data.phone, email: parsed_data.email, phone_country_code:parsed_data.phone_country_code }), Err(e) => { router_env::logger::error!("Failed to parse 'CustomerDetailsResponse' from payment method data. Error: {e:?}"); None } } ), billing: pi.billing_details.and_then(|billing_details| match billing_details.into_inner().expose().parse_value::<Address>("Address") { Ok(parsed_data) => Some(parsed_data), Err(e) => { router_env::logger::error!("Failed to parse 'BillingAddress' from payment method data. Error: {e:?}"); None } } ), shipping: pi.shipping_details.and_then(|shipping_details| match shipping_details.into_inner().expose().parse_value::<Address>("Address") { Ok(parsed_data) => Some(parsed_data), Err(e) => { router_env::logger::error!("Failed to parse 'ShippingAddress' from payment method data. Error: {e:?}"); None } } ), // TODO: fill in details based on requirement net_amount: pa.net_amount.get_total_amount(), amount_received: None, refunds: None, disputes: None, attempts: None, captures: None, mandate_id: None, mandate_data: None, off_session: None, capture_on: None, payment_token: None, email: None, name: None, phone: None, return_url: None, statement_descriptor_name: None, statement_descriptor_suffix: None, next_action: None, cancellation_reason: None, error_code: None, error_message: None, unified_code: None, unified_message: None, payment_experience: None, connector_label: None, allowed_payment_method_types: None, ephemeral_key: None, manual_retry_allowed: None, frm_message: None, connector_metadata: None, feature_metadata: None, reference_id: None, payment_link: None, surcharge_details: None, merchant_decision: None, incremental_authorization_allowed: None, authorization_count: None, incremental_authorizations: None, external_authentication_details: None, external_3ds_authentication_attempted: None, expires_on: None, fingerprint: None, browser_info: None, payment_method_id: None, payment_method_status: None, updated: None, split_payments: None, frm_metadata: None, capture_before: pa.capture_before, extended_authorization_applied: pa.extended_authorization_applied, order_tax_amount: None, connector_mandate_id:None, shipping_cost: None, card_discovery: pa.card_discovery, mit_category: pi.mit_category, 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, payment_channel: pi.payment_channel, network_transaction_id: None, enable_partial_authorization: pi.enable_partial_authorization, enable_overcapture: pi.enable_overcapture, is_overcapture_enabled: pa.is_overcapture_enabled, network_details: pa.network_details.map(NetworkDetails::foreign_from), is_stored_credential:pa.is_stored_credential, request_extended_authorization: pa.request_extended_authorization, } } } #[cfg(feature = "v2")] impl ForeignFrom<(storage::PaymentIntent, Option<storage::PaymentAttempt>)> for api_models::payments::PaymentsListResponseItem { fn foreign_from((pi, pa): (storage::PaymentIntent, Option<storage::PaymentAttempt>)) -> Self { Self { id: pi.id, merchant_id: pi.merchant_id, profile_id: pi.profile_id, customer_id: pi.customer_id, payment_method_id: pa.as_ref().and_then(|p| p.payment_method_id.clone()), status: pi.status, amount: api_models::payments::PaymentAmountDetailsResponse::foreign_from(( &pi.amount_details, pa.as_ref().map(|p| &p.amount_details), )), created: pi.created_at, payment_method_type: pa.as_ref().and_then(|p| p.payment_method_type.into()), payment_method_subtype: pa.as_ref().and_then(|p| p.payment_method_subtype.into()), connector: pa.as_ref().and_then(|p| p.connector.clone()), merchant_connector_id: pa.as_ref().and_then(|p| p.merchant_connector_id.clone()), customer: None, merchant_reference_id: pi.merchant_reference_id, connector_payment_id: pa.as_ref().and_then(|p| p.connector_payment_id.clone()), connector_response_reference_id: pa .as_ref() .and_then(|p| p.connector_response_reference_id.clone()), metadata: pi.metadata, description: pi.description.map(|val| val.get_string_repr().to_string()), authentication_type: pi.authentication_type, capture_method: Some(pi.capture_method), setup_future_usage: Some(pi.setup_future_usage), attempt_count: pi.attempt_count, error: pa .as_ref() .and_then(|p| p.error.as_ref()) .map(api_models::payments::ErrorDetails::foreign_from), cancellation_reason: pa.as_ref().and_then(|p| p.cancellation_reason.clone()), order_details: None, return_url: pi.return_url, statement_descriptor: pi.statement_descriptor, allowed_payment_method_types: pi.allowed_payment_method_types, authorization_count: pi.authorization_count, modified_at: pa.as_ref().map(|p| p.modified_at), } } } #[cfg(feature = "v1")] impl ForeignFrom<ephemeral_key::EphemeralKey> for api::ephemeral_key::EphemeralKeyCreateResponse { fn foreign_from(from: ephemeral_key::EphemeralKey) -> Self { Self { customer_id: from.customer_id, created_at: from.created_at, expires: from.expires, secret: from.secret, } } } #[cfg(feature = "v1")] pub fn bank_transfer_next_steps_check( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::BankTransferNextStepsData>> { let bank_transfer_next_step = if let Some(diesel_models::enums::PaymentMethod::BankTransfer) = payment_attempt.payment_method { if payment_attempt.payment_method_type != Some(diesel_models::enums::PaymentMethodType::Pix) { let bank_transfer_next_steps: Option<api_models::payments::BankTransferNextStepsData> = payment_attempt .connector_metadata .map(|metadata| { metadata .parse_value("NextStepsRequirements") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to parse the Value to NextRequirements struct", ) }) .transpose()?; bank_transfer_next_steps } else { None } } else { None }; Ok(bank_transfer_next_step) } #[cfg(feature = "v1")] pub fn voucher_next_steps_check( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::VoucherNextStepData>> { let voucher_next_step = if let Some(diesel_models::enums::PaymentMethod::Voucher) = payment_attempt.payment_method { let voucher_next_steps: Option<api_models::payments::VoucherNextStepData> = payment_attempt .connector_metadata .map(|metadata| { metadata .parse_value("NextStepsRequirements") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse the Value to NextRequirements struct") }) .transpose()?; voucher_next_steps } else { None }; Ok(voucher_next_step) } #[cfg(feature = "v1")] pub fn mobile_payment_next_steps_check( payment_attempt: &storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::MobilePaymentNextStepData>> { let mobile_payment_next_step = if let Some(diesel_models::enums::PaymentMethod::MobilePayment) = payment_attempt.payment_method { let mobile_paymebnt_next_steps: Option<api_models::payments::MobilePaymentNextStepData> = payment_attempt .connector_metadata .clone() .map(|metadata| { metadata .parse_value("MobilePaymentNextStepData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse the Value to NextRequirements struct") }) .transpose()?; mobile_paymebnt_next_steps } else { None }; Ok(mobile_payment_next_step) } impl ForeignFrom<api_models::payments::QrCodeInformation> for api_models::payments::NextActionData { fn foreign_from(qr_info: api_models::payments::QrCodeInformation) -> Self { match qr_info { api_models::payments::QrCodeInformation::QrCodeUrl { image_data_url, qr_code_url, display_to_timestamp, } => Self::QrCodeInformation { image_data_url: Some(image_data_url), qr_code_url: Some(qr_code_url), display_to_timestamp, border_color: None, display_text: None, }, api_models::payments::QrCodeInformation::QrDataUrl { image_data_url, display_to_timestamp, } => Self::QrCodeInformation { image_data_url: Some(image_data_url), display_to_timestamp, qr_code_url: None, border_color: None, display_text: None, }, api_models::payments::QrCodeInformation::QrCodeImageUrl { qr_code_url, display_to_timestamp, } => Self::QrCodeInformation { qr_code_url: Some(qr_code_url), image_data_url: None, display_to_timestamp, border_color: None, display_text: None, }, api_models::payments::QrCodeInformation::QrColorDataUrl { color_image_data_url, display_to_timestamp, border_color, display_text, } => Self::QrCodeInformation { qr_code_url: None, image_data_url: Some(color_image_data_url), display_to_timestamp, border_color, display_text, }, } } } #[derive(Clone)] pub struct PaymentAdditionalData<'a, F> where F: Clone, { router_base_url: String, connector_name: String, payment_data: PaymentData<F>, state: &'a SessionState, customer_data: &'a Option<domain::Customer>, } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthorizeData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data.clone(); let router_base_url = &additional_data.router_base_url; let connector_name = &additional_data.connector_name; let attempt = &payment_data.payment_attempt; let browser_info: Option<types::BrowserInformation> = attempt .browser_info .clone() .map(types::BrowserInformation::from); let complete_authorize_url = Some(helpers::create_complete_authorize_url( router_base_url, attempt, connector_name, payment_data.creds_identifier.as_deref(), )); let merchant_connector_account_id_or_connector_name = payment_data .payment_attempt .merchant_connector_id .as_ref() .map(|mca_id| mca_id.get_string_repr()) .unwrap_or(connector_name); let webhook_url = Some(helpers::create_webhook_url( router_base_url, &attempt.merchant_id, merchant_connector_account_id_or_connector_name, )); let router_return_url = Some(helpers::create_redirect_url( router_base_url, attempt, connector_name, payment_data.creds_identifier.as_deref(), )); let payment_method_data = payment_data.payment_method_data.or_else(|| { if payment_data.mandate_id.is_some() { Some(domain::PaymentMethodData::MandatePayment) } else { None } }); let amount = payment_data .payment_attempt .get_total_amount() .get_amount_as_i64(); let customer_name = additional_data .customer_data .as_ref() .and_then(|customer_data| { customer_data .name .as_ref() .map(|customer| customer.clone().into_inner()) }); let customer_id = additional_data .customer_data .as_ref() .and_then(|data| data.get_id().clone().try_into().ok()); let merchant_order_reference_id = payment_data .payment_intent .merchant_reference_id .map(|s| s.get_string_repr().to_string()); let shipping_cost = payment_data.payment_intent.amount_details.shipping_cost; Ok(Self { payment_method_data: payment_method_data .unwrap_or(domain::PaymentMethodData::Card(domain::Card::default())), amount, order_tax_amount: None, // V2 doesn't currently support order tax amount email: None, // V2 doesn't store email directly in payment_intent customer_name, currency: payment_data.currency, confirm: true, statement_descriptor_suffix: None, statement_descriptor: None, capture_method: Some(payment_data.payment_intent.capture_method), router_return_url, webhook_url, complete_authorize_url, setup_future_usage: Some(payment_data.payment_intent.setup_future_usage), mandate_id: payment_data.mandate_id.clone(), off_session: get_off_session(payment_data.mandate_id.as_ref(), None), customer_acceptance: None, setup_mandate_details: None, browser_info, order_details: None, order_category: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None, payment_experience: None, payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype), surcharge_details: None, customer_id, request_incremental_authorization: false, metadata: payment_data .payment_intent .metadata .clone() .map(|m| m.expose()), authentication_data: None, request_extended_authorization: None, split_payments: None, minor_amount: payment_data.payment_attempt.get_total_amount(), merchant_order_reference_id, integrity_object: None, shipping_cost, additional_payment_method_data: None, merchant_account_id: None, merchant_config_currency: None, connector_testing_data: None, order_id: None, mit_category: None, locale: None, payment_channel: None, enable_partial_authorization: None, enable_overcapture: None, is_stored_credential: None, }) } } fn get_off_session( mandate_id: Option<&MandateIds>, off_session_flag: Option<bool>, ) -> Option<bool> { match (mandate_id, off_session_flag) { (_, Some(false)) => Some(false), (Some(_), _) | (_, Some(true)) => Some(true), (None, None) => None, } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthorizeData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data.clone(); let router_base_url = &additional_data.router_base_url; let connector_name = &additional_data.connector_name; let attempt = &payment_data.payment_attempt; let browser_info: Option<types::BrowserInformation> = attempt .browser_info .clone() .map(|b| b.parse_value("BrowserInformation")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; let connector_metadata = additional_data .payment_data .payment_intent .connector_metadata .clone() .map(|cm| { cm.parse_value::<api_models::payments::ConnectorMetadata>("ConnectorMetadata") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed parsing ConnectorMetadata") }) .transpose()?; let order_category = connector_metadata.as_ref().and_then(|cm| { cm.noon .as_ref() .and_then(|noon| noon.order_category.clone()) }); let braintree_metadata = connector_metadata .as_ref() .and_then(|cm| cm.braintree.clone()); let merchant_account_id = braintree_metadata .as_ref() .and_then(|braintree| braintree.merchant_account_id.clone()); let merchant_config_currency = braintree_metadata.and_then(|braintree| braintree.merchant_config_currency); let order_details = additional_data .payment_data .payment_intent .order_details .map(|order_details| { order_details .iter() .map(|data| { data.to_owned() .parse_value("OrderDetailsWithAmount") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "OrderDetailsWithAmount", }) .attach_printable("Unable to parse OrderDetailsWithAmount") }) .collect::<Result<Vec<_>, _>>() }) .transpose()?; let complete_authorize_url = Some(helpers::create_complete_authorize_url( router_base_url, attempt, connector_name, payment_data.creds_identifier.as_deref(), )); let merchant_connector_account_id_or_connector_name = payment_data .payment_attempt .merchant_connector_id .as_ref() .map(|mca_id| mca_id.get_string_repr()) .unwrap_or(connector_name); let webhook_url = Some(helpers::create_webhook_url( router_base_url, &attempt.merchant_id, merchant_connector_account_id_or_connector_name, )); let router_return_url = Some(helpers::create_redirect_url( router_base_url, attempt, connector_name, payment_data.creds_identifier.as_deref(), )); let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> = payment_data.payment_attempt .payment_method_data .as_ref().map(|data| data.clone().parse_value("AdditionalPaymentData")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse AdditionalPaymentData from payment_data.payment_attempt.payment_method_data")?; let payment_method_data = payment_data.payment_method_data.or_else(|| { if payment_data.mandate_id.is_some() { Some(domain::PaymentMethodData::MandatePayment) } else { None } }); let amount = payment_data.payment_attempt.get_total_amount(); let customer_name = additional_data .customer_data .as_ref() .and_then(|customer_data| { customer_data .name .as_ref() .map(|customer| customer.clone().into_inner()) }); let customer_id = additional_data .customer_data .as_ref() .map(|data| data.customer_id.clone()); let split_payments = payment_data.payment_intent.split_payments.clone(); let merchant_order_reference_id = payment_data .payment_intent .merchant_order_reference_id .clone(); let shipping_cost = payment_data.payment_intent.shipping_cost; let connector = api_models::enums::Connector::from_str(connector_name) .change_context(errors::ConnectorError::InvalidConnectorName) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "connector", }) .attach_printable_lazy(|| { format!("unable to parse connector name {connector_name:?}") })?; let connector_testing_data = connector_metadata .and_then(|cm| match connector { api_models::enums::Connector::Adyen => cm .adyen .map(|adyen_cm| adyen_cm.testing) .map(|testing_data| { serde_json::to_value(testing_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse Adyen testing data") }), _ => None, }) .transpose()? .map(pii::SecretSerdeValue::new); let is_off_session = get_off_session( payment_data.mandate_id.as_ref(), payment_data.payment_intent.off_session, ); Ok(Self { payment_method_data: (payment_method_data.get_required_value("payment_method_data")?), setup_future_usage: payment_data.payment_attempt.setup_future_usage_applied, mandate_id: payment_data.mandate_id.clone(), off_session: is_off_session, setup_mandate_details: payment_data.setup_mandate.clone(), confirm: payment_data.payment_attempt.confirm, statement_descriptor_suffix: payment_data.payment_intent.statement_descriptor_suffix, statement_descriptor: payment_data.payment_intent.statement_descriptor_name, capture_method: payment_data.payment_attempt.capture_method, amount: amount.get_amount_as_i64(), order_tax_amount: payment_data .payment_attempt .net_amount .get_order_tax_amount(), minor_amount: amount, currency: payment_data.currency, browser_info, email: payment_data.email, customer_name, payment_experience: payment_data.payment_attempt.payment_experience, order_details, order_category, session_token: None, enrolled_for_3ds: true, related_transaction_id: None, payment_method_type: payment_data.payment_attempt.payment_method_type, router_return_url, webhook_url, complete_authorize_url, customer_id, surcharge_details: payment_data.surcharge_details, request_incremental_authorization: matches!( payment_data .payment_intent .request_incremental_authorization, Some(RequestIncrementalAuthorization::True) ), metadata: additional_data.payment_data.payment_intent.metadata, authentication_data: payment_data .authentication .as_ref() .map(AuthenticationData::foreign_try_from) .transpose()?, customer_acceptance: payment_data.customer_acceptance, request_extended_authorization: attempt.request_extended_authorization, split_payments, merchant_order_reference_id, integrity_object: None, additional_payment_method_data, shipping_cost, merchant_account_id, merchant_config_currency, connector_testing_data, mit_category: payment_data.payment_intent.mit_category, order_id: None, locale: Some(additional_data.state.locale.clone()), payment_channel: payment_data.payment_intent.payment_channel, enable_partial_authorization: payment_data.payment_intent.enable_partial_authorization, enable_overcapture: payment_data.payment_intent.enable_overcapture, is_stored_credential: payment_data.payment_attempt.is_stored_credential, }) } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsExtendAuthorizationData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { todo!() } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsExtendAuthorizationData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let connector = api::ConnectorData::get_connector_by_name( &additional_data.state.conf.connectors, &additional_data.connector_name, api::GetToken::Connector, payment_data.payment_attempt.merchant_connector_id.clone(), )?; let amount = payment_data.payment_attempt.get_total_amount(); Ok(Self { minor_amount: amount, currency: payment_data.currency, connector_transaction_id: connector .connector .connector_transaction_id(&payment_data.payment_attempt)? .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?, connector_meta: payment_data.payment_attempt.connector_metadata, }) } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { todo!() } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let capture_method = payment_data.get_capture_method(); let amount = payment_data.payment_attempt.get_total_amount(); let payment_method_type = payment_data .payment_attempt .get_payment_method_type() .to_owned(); Ok(Self { amount, integrity_object: None, mandate_id: payment_data.mandate_id.clone(), connector_transaction_id: match payment_data.payment_attempt.get_connector_payment_id() { Some(connector_txn_id) => { types::ResponseId::ConnectorTransactionId(connector_txn_id.to_owned()) } None => types::ResponseId::NoResponseId, }, encoded_data: payment_data.payment_attempt.encoded_data, capture_method, connector_meta: payment_data.payment_attempt.connector_metadata, sync_type: match payment_data.multiple_capture_data { Some(multiple_capture_data) => types::SyncRequestType::MultipleCaptureSync( multiple_capture_data.get_pending_connector_capture_ids(), ), None => types::SyncRequestType::SinglePaymentSync, }, payment_method_type, currency: payment_data.currency, split_payments: payment_data.payment_intent.split_payments, payment_experience: payment_data.payment_attempt.payment_experience, connector_reference_id: payment_data .payment_attempt .connector_response_reference_id .clone(), setup_future_usage: payment_data.payment_intent.setup_future_usage, }) } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsIncrementalAuthorizationData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let payment_attempt = &payment_data.payment_attempt; let connector = api::ConnectorData::get_connector_by_name( &additional_data.state.conf.connectors, &additional_data.connector_name, api::GetToken::Connector, payment_attempt.merchant_connector_id.clone(), )?; let incremental_details = payment_data .incremental_authorization_details .as_ref() .ok_or( report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing incremental_authorization_details in payment_data"), )?; Ok(Self { total_amount: incremental_details.total_amount.get_amount_as_i64(), additional_amount: incremental_details.additional_amount.get_amount_as_i64(), reason: incremental_details.reason.clone(), currency: payment_data.currency, connector_transaction_id: connector .connector .connector_transaction_id(payment_attempt)? .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?, connector_meta: payment_attempt.connector_metadata.clone(), }) } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsIncrementalAuthorizationData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let connector = api::ConnectorData::get_connector_by_name( &additional_data.state.conf.connectors, &additional_data.connector_name, api::GetToken::Connector, payment_data.payment_attempt.merchant_connector_id.clone(), )?; let incremental_details = payment_data .incremental_authorization_details .as_ref() .ok_or( report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing incremental_authorization_details in payment_data"), )?; Ok(Self { total_amount: incremental_details.total_amount.get_amount_as_i64(), additional_amount: incremental_details.additional_amount.get_amount_as_i64(), reason: incremental_details.reason.clone(), currency: payment_data.currency, connector_transaction_id: connector .connector .connector_transaction_id(&payment_data.payment_attempt)? .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?, connector_meta: payment_data .payment_attempt .connector_metadata .map(|secret| secret.expose()), }) } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCaptureData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { use masking::ExposeOptionInterface; let payment_data = additional_data.payment_data; let connector = api::ConnectorData::get_connector_by_name( &additional_data.state.conf.connectors, &additional_data.connector_name, api::GetToken::Connector, payment_data.payment_attempt.merchant_connector_id.clone(), )?; let amount_to_capture = payment_data .payment_attempt .amount_details .get_amount_to_capture() .unwrap_or(payment_data.payment_attempt.get_total_amount()); let amount = payment_data.payment_attempt.get_total_amount(); Ok(Self { capture_method: Some(payment_data.payment_intent.capture_method), amount_to_capture: amount_to_capture.get_amount_as_i64(), // This should be removed once we start moving to connector module minor_amount_to_capture: amount_to_capture, currency: payment_data.currency, connector_transaction_id: connector .connector .connector_transaction_id(&payment_data.payment_attempt)? .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?, payment_amount: amount.get_amount_as_i64(), // This should be removed once we start moving to connector module minor_payment_amount: amount, connector_meta: payment_data .payment_attempt .connector_metadata .expose_option(), // TODO: add multiple capture data multiple_capture_data: None, // TODO: why do we need browser info during capture? browser_info: None, metadata: payment_data.payment_intent.metadata.expose_option(), integrity_object: None, split_payments: None, webhook_url: None, }) } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCaptureData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let connector = api::ConnectorData::get_connector_by_name( &additional_data.state.conf.connectors, &additional_data.connector_name, api::GetToken::Connector, payment_data.payment_attempt.merchant_connector_id.clone(), )?; let amount_to_capture = payment_data .payment_attempt .amount_to_capture .unwrap_or(payment_data.payment_attempt.get_total_amount()); let browser_info: Option<types::BrowserInformation> = payment_data .payment_attempt .browser_info .clone() .map(|b| b.parse_value("BrowserInformation")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; let amount = payment_data.payment_attempt.get_total_amount(); let router_base_url = &additional_data.router_base_url; let attempt = &payment_data.payment_attempt; let merchant_connector_account_id = payment_data .payment_attempt .merchant_connector_id .as_ref() .map(|mca_id| mca_id.get_string_repr()) .ok_or(errors::ApiErrorResponse::MerchantAccountNotFound)?; let webhook_url: Option<_> = Some(helpers::create_webhook_url( router_base_url, &attempt.merchant_id, merchant_connector_account_id, )); Ok(Self { capture_method: payment_data.get_capture_method(), amount_to_capture: amount_to_capture.get_amount_as_i64(), // This should be removed once we start moving to connector module minor_amount_to_capture: amount_to_capture, currency: payment_data.currency, connector_transaction_id: connector .connector .connector_transaction_id(&payment_data.payment_attempt)? .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?, payment_amount: amount.get_amount_as_i64(), // This should be removed once we start moving to connector module minor_payment_amount: amount, connector_meta: payment_data.payment_attempt.connector_metadata, multiple_capture_data: match payment_data.multiple_capture_data { Some(multiple_capture_data) => Some(MultipleCaptureRequestData { capture_sequence: multiple_capture_data.get_captures_count()?, capture_reference: multiple_capture_data .get_latest_capture() .capture_id .clone(), }), None => None, }, browser_info, metadata: payment_data.payment_intent.metadata, integrity_object: None, split_payments: payment_data.payment_intent.split_payments, webhook_url, }) } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCancelData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let connector = api::ConnectorData::get_connector_by_name( &additional_data.state.conf.connectors, &additional_data.connector_name, api::GetToken::Connector, payment_data.payment_attempt.merchant_connector_id.clone(), )?; let browser_info: Option<types::BrowserInformation> = payment_data .payment_attempt .browser_info .clone() .map(types::BrowserInformation::from); let amount = payment_data.payment_attempt.amount_details.get_net_amount(); let router_base_url = &additional_data.router_base_url; let attempt = &payment_data.payment_attempt; let merchant_connector_account_id = payment_data .payment_attempt .merchant_connector_id .as_ref() .map(|mca_id| mca_id.get_string_repr()) .ok_or(errors::ApiErrorResponse::MerchantAccountNotFound)?; let webhook_url: Option<_> = Some(helpers::create_webhook_url( router_base_url, &attempt.merchant_id, merchant_connector_account_id, )); let capture_method = payment_data.payment_intent.capture_method; Ok(Self { amount: Some(amount.get_amount_as_i64()), // This should be removed once we start moving to connector module minor_amount: Some(amount), currency: Some(payment_data.payment_intent.amount_details.currency), connector_transaction_id: connector .connector .connector_transaction_id(&payment_data.payment_attempt)? .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?, cancellation_reason: payment_data.payment_attempt.cancellation_reason, connector_meta: payment_data .payment_attempt .connector_metadata .clone() .expose_option(), browser_info, metadata: payment_data.payment_intent.metadata.expose_option(), webhook_url, capture_method: Some(capture_method), }) } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCancelData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let connector = api::ConnectorData::get_connector_by_name( &additional_data.state.conf.connectors, &additional_data.connector_name, api::GetToken::Connector, payment_data.payment_attempt.merchant_connector_id.clone(), )?; let browser_info: Option<types::BrowserInformation> = payment_data .payment_attempt .browser_info .clone() .map(|b| b.parse_value("BrowserInformation")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; let amount = payment_data.payment_attempt.get_total_amount(); let router_base_url = &additional_data.router_base_url; let attempt = &payment_data.payment_attempt; let merchant_connector_account_id = payment_data .payment_attempt .merchant_connector_id .as_ref() .map(|mca_id| mca_id.get_string_repr()) .ok_or(errors::ApiErrorResponse::MerchantAccountNotFound)?; let webhook_url: Option<_> = Some(helpers::create_webhook_url( router_base_url, &attempt.merchant_id, merchant_connector_account_id, )); let capture_method = payment_data.payment_attempt.capture_method; Ok(Self { amount: Some(amount.get_amount_as_i64()), // This should be removed once we start moving to connector module minor_amount: Some(amount), currency: Some(payment_data.currency), connector_transaction_id: connector .connector .connector_transaction_id(&payment_data.payment_attempt)? .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?, cancellation_reason: payment_data.payment_attempt.cancellation_reason, connector_meta: payment_data.payment_attempt.connector_metadata, browser_info, metadata: payment_data.payment_intent.metadata, webhook_url, capture_method, }) } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCancelPostCaptureData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { todo!() } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCancelPostCaptureData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let connector = api::ConnectorData::get_connector_by_name( &additional_data.state.conf.connectors, &additional_data.connector_name, api::GetToken::Connector, payment_data.payment_attempt.merchant_connector_id.clone(), )?; let amount = payment_data.payment_attempt.get_total_amount(); Ok(Self { minor_amount: Some(amount), currency: Some(payment_data.currency), connector_transaction_id: connector .connector .connector_transaction_id(&payment_data.payment_attempt)? .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?, cancellation_reason: payment_data.payment_attempt.cancellation_reason, connector_meta: payment_data.payment_attempt.connector_metadata, }) } } impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsApproveData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let amount = payment_data.payment_attempt.get_total_amount(); Ok(Self { amount: Some(amount.get_amount_as_i64()), //need to change after we move to connector module currency: Some(payment_data.currency), }) } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SdkPaymentsSessionUpdateData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { todo!() } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SdkPaymentsSessionUpdateData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let order_tax_amount = payment_data .payment_intent .tax_details .clone() .and_then(|tax| tax.payment_method_type.map(|pmt| pmt.order_tax_amount)) .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "order_tax_amount", })?; let surcharge_amount = payment_data .surcharge_details .as_ref() .map(|surcharge_details| surcharge_details.get_total_surcharge_amount()) .unwrap_or_default(); let shipping_cost = payment_data .payment_intent .shipping_cost .unwrap_or_default(); // net_amount here would include amount, order_tax_amount, surcharge_amount and shipping_cost let net_amount = payment_data.payment_intent.amount + order_tax_amount + shipping_cost + surcharge_amount; Ok(Self { amount: net_amount, order_tax_amount, currency: payment_data.currency, order_amount: payment_data.payment_intent.amount, session_id: payment_data.session_id, shipping_cost: payment_data.payment_intent.shipping_cost, }) } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPostSessionTokensData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { todo!() } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPostSessionTokensData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data.clone(); let surcharge_amount = payment_data .surcharge_details .as_ref() .map(|surcharge_details| surcharge_details.get_total_surcharge_amount()) .unwrap_or_default(); let shipping_cost = payment_data .payment_intent .shipping_cost .unwrap_or_default(); // amount here would include amount, surcharge_amount and shipping_cost let amount = payment_data.payment_intent.amount + shipping_cost + surcharge_amount; let merchant_order_reference_id = payment_data .payment_intent .merchant_order_reference_id .clone(); let router_base_url = &additional_data.router_base_url; let connector_name = &additional_data.connector_name; let attempt = &payment_data.payment_attempt; let router_return_url = Some(helpers::create_redirect_url( router_base_url, attempt, connector_name, payment_data.creds_identifier.as_deref(), )); Ok(Self { amount, //need to change after we move to connector module order_amount: payment_data.payment_intent.amount, currency: payment_data.currency, merchant_order_reference_id, capture_method: payment_data.payment_attempt.capture_method, shipping_cost: payment_data.payment_intent.shipping_cost, setup_future_usage: payment_data.payment_attempt.setup_future_usage_applied, router_return_url, }) } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsUpdateMetadataData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { todo!() } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsUpdateMetadataData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data.clone(); let connector = api::ConnectorData::get_connector_by_name( &additional_data.state.conf.connectors, &additional_data.connector_name, api::GetToken::Connector, payment_data.payment_attempt.merchant_connector_id.clone(), )?; Ok(Self { metadata: payment_data .payment_intent .metadata .map(Secret::new) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("payment_intent.metadata not found")?, connector_transaction_id: connector .connector .connector_transaction_id(&payment_data.payment_attempt)? .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?, }) } } impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsRejectData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let amount = payment_data.payment_attempt.get_total_amount(); Ok(Self { amount: Some(amount.get_amount_as_i64()), //need to change after we move to connector module currency: Some(payment_data.currency), }) } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data.clone(); let order_details = additional_data .payment_data .payment_intent .order_details .map(|order_details| { order_details .iter() .map(|data| data.to_owned().expose()) .collect() }); let surcharge_amount = payment_data .surcharge_details .as_ref() .map(|surcharge_details| surcharge_details.get_total_surcharge_amount()) .unwrap_or_default(); let amount = payment_data.payment_intent.amount_details.order_amount; let shipping_cost = payment_data .payment_intent .amount_details .shipping_cost .unwrap_or_default(); // net_amount here would include amount, surcharge_amount and shipping_cost let net_amount = amount + surcharge_amount + shipping_cost; let required_amount_type = StringMajorUnitForConnector; let apple_pay_amount = required_amount_type .convert(net_amount, payment_data.currency) .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "Failed to convert amount to string major unit for applePay".to_string(), })?; let apple_pay_recurring_details = payment_data .payment_intent .feature_metadata .and_then(|feature_metadata| feature_metadata.apple_pay_recurring_details) .map(|apple_pay_recurring_details| { ForeignInto::foreign_into((apple_pay_recurring_details, apple_pay_amount)) }); let order_tax_amount = payment_data .payment_intent .amount_details .tax_details .clone() .and_then(|tax| tax.get_default_tax_amount()); Ok(Self { amount: amount.get_amount_as_i64(), //need to change once we move to connector module minor_amount: amount, currency: payment_data.currency, country: payment_data.address.get_payment_method_billing().and_then( |billing_address| { billing_address .address .as_ref() .and_then(|address| address.country) }, ), order_details, surcharge_details: payment_data.surcharge_details, email: payment_data.email, apple_pay_recurring_details, customer_name: None, metadata: payment_data.payment_intent.metadata, order_tax_amount, shipping_cost: payment_data.payment_intent.amount_details.shipping_cost, payment_method: Some(payment_data.payment_attempt.payment_method_type), payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype), }) } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data.clone(); let order_details = additional_data .payment_data .payment_intent .order_details .map(|order_details| { order_details .iter() .map(|data| { data.to_owned() .parse_value("OrderDetailsWithAmount") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "OrderDetailsWithAmount", }) .attach_printable("Unable to parse OrderDetailsWithAmount") }) .collect::<Result<Vec<_>, _>>() }) .transpose()?; let surcharge_amount = payment_data .surcharge_details .as_ref() .map(|surcharge_details| surcharge_details.get_total_surcharge_amount()) .unwrap_or_default(); let amount = payment_data.payment_intent.amount; let shipping_cost = payment_data .payment_intent .shipping_cost .unwrap_or_default(); // net_amount here would include amount, surcharge_amount and shipping_cost let net_amount = amount + surcharge_amount + shipping_cost; let required_amount_type = StringMajorUnitForConnector; let apple_pay_amount = required_amount_type .convert(net_amount, payment_data.currency) .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "Failed to convert amount to string major unit for applePay".to_string(), })?; let apple_pay_recurring_details = payment_data .payment_intent .feature_metadata .map(|feature_metadata| { feature_metadata .parse_value::<diesel_models::types::FeatureMetadata>("FeatureMetadata") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed parsing FeatureMetadata") }) .transpose()? .and_then(|feature_metadata| feature_metadata.apple_pay_recurring_details) .map(|apple_pay_recurring_details| { ForeignFrom::foreign_from((apple_pay_recurring_details, apple_pay_amount)) }); let order_tax_amount = payment_data .payment_intent .tax_details .clone() .and_then(|tax| tax.get_default_tax_amount()); let shipping_cost = payment_data.payment_intent.shipping_cost; let metadata = payment_data .payment_intent .metadata .clone() .map(Secret::new); Ok(Self { amount: net_amount.get_amount_as_i64(), //need to change once we move to connector module minor_amount: amount, currency: payment_data.currency, country: payment_data.address.get_payment_method_billing().and_then( |billing_address| { billing_address .address .as_ref() .and_then(|address| address.country) }, ), order_details, email: payment_data.email, surcharge_details: payment_data.surcharge_details, apple_pay_recurring_details, customer_name: None, order_tax_amount, shipping_cost, metadata, payment_method: payment_data.payment_attempt.payment_method, payment_method_type: payment_data.payment_attempt.payment_method_type, }) } } impl ForeignFrom<( diesel_models::types::ApplePayRecurringDetails, StringMajorUnit, )> for api_models::payments::ApplePayRecurringPaymentRequest { fn foreign_from( (apple_pay_recurring_details, net_amount): ( diesel_models::types::ApplePayRecurringDetails, StringMajorUnit, ), ) -> Self { Self { payment_description: apple_pay_recurring_details.payment_description, regular_billing: api_models::payments::ApplePayRegularBillingRequest { amount: net_amount, label: apple_pay_recurring_details.regular_billing.label, payment_timing: api_models::payments::ApplePayPaymentTiming::Recurring, recurring_payment_start_date: apple_pay_recurring_details .regular_billing .recurring_payment_start_date, recurring_payment_end_date: apple_pay_recurring_details .regular_billing .recurring_payment_end_date, recurring_payment_interval_unit: apple_pay_recurring_details .regular_billing .recurring_payment_interval_unit .map(ForeignFrom::foreign_from), recurring_payment_interval_count: apple_pay_recurring_details .regular_billing .recurring_payment_interval_count, }, billing_agreement: apple_pay_recurring_details.billing_agreement, management_u_r_l: apple_pay_recurring_details.management_url, } } } impl ForeignFrom<diesel_models::types::ApplePayRecurringDetails> for api_models::payments::ApplePayRecurringDetails { fn foreign_from( apple_pay_recurring_details: diesel_models::types::ApplePayRecurringDetails, ) -> Self { Self { payment_description: apple_pay_recurring_details.payment_description, regular_billing: ForeignFrom::foreign_from(apple_pay_recurring_details.regular_billing), billing_agreement: apple_pay_recurring_details.billing_agreement, management_url: apple_pay_recurring_details.management_url, } } } impl ForeignFrom<diesel_models::types::ApplePayRegularBillingDetails> for api_models::payments::ApplePayRegularBillingDetails { fn foreign_from( apple_pay_regular_billing: diesel_models::types::ApplePayRegularBillingDetails, ) -> Self { Self { label: apple_pay_regular_billing.label, recurring_payment_start_date: apple_pay_regular_billing.recurring_payment_start_date, recurring_payment_end_date: apple_pay_regular_billing.recurring_payment_end_date, recurring_payment_interval_unit: apple_pay_regular_billing .recurring_payment_interval_unit .map(ForeignFrom::foreign_from), recurring_payment_interval_count: apple_pay_regular_billing .recurring_payment_interval_count, } } } impl ForeignFrom<diesel_models::types::RecurringPaymentIntervalUnit> for api_models::payments::RecurringPaymentIntervalUnit { fn foreign_from( apple_pay_recurring_payment_interval_unit: diesel_models::types::RecurringPaymentIntervalUnit, ) -> Self { match apple_pay_recurring_payment_interval_unit { diesel_models::types::RecurringPaymentIntervalUnit::Day => Self::Day, diesel_models::types::RecurringPaymentIntervalUnit::Month => Self::Month, diesel_models::types::RecurringPaymentIntervalUnit::Year => Self::Year, diesel_models::types::RecurringPaymentIntervalUnit::Hour => Self::Hour, diesel_models::types::RecurringPaymentIntervalUnit::Minute => Self::Minute, } } } impl ForeignFrom<diesel_models::types::RedirectResponse> for api_models::payments::RedirectResponse { fn foreign_from(redirect_res: diesel_models::types::RedirectResponse) -> Self { Self { param: redirect_res.param, json_payload: redirect_res.json_payload, } } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequestData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let router_base_url = &additional_data.router_base_url; let connector_name = &additional_data.connector_name; let attempt = &payment_data.payment_attempt; let router_return_url = Some(helpers::create_redirect_url( router_base_url, attempt, connector_name, payment_data.creds_identifier.as_deref(), )); let browser_info: Option<types::BrowserInformation> = attempt .browser_info .clone() .map(|b| b.parse_value("BrowserInformation")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; let customer_name = additional_data .customer_data .as_ref() .and_then(|customer_data| { customer_data .name .as_ref() .map(|customer| customer.clone().into_inner()) }); let amount = payment_data.payment_attempt.get_total_amount(); let merchant_connector_account_id_or_connector_name = payment_data .payment_attempt .merchant_connector_id .as_ref() .map(|mca_id| mca_id.get_string_repr()) .unwrap_or(connector_name); let webhook_url = Some(helpers::create_webhook_url( router_base_url, &attempt.merchant_id, merchant_connector_account_id_or_connector_name, )); let complete_authorize_url = Some(helpers::create_complete_authorize_url( router_base_url, attempt, connector_name, payment_data.creds_identifier.as_deref(), )); let connector = api_models::enums::Connector::from_str(connector_name) .change_context(errors::ConnectorError::InvalidConnectorName) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "connector", }) .attach_printable_lazy(|| { format!("unable to parse connector name {connector_name:?}") })?; let connector_testing_data = payment_data .payment_intent .connector_metadata .as_ref() .map(|cm| { cm.clone() .parse_value::<api_models::payments::ConnectorMetadata>("ConnectorMetadata") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed parsing ConnectorMetadata") }) .transpose()? .and_then(|cm| match connector { api_models::enums::Connector::Adyen => cm .adyen .map(|adyen_cm| adyen_cm.testing) .map(|testing_data| { serde_json::to_value(testing_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse Adyen testing data") }), _ => None, }) .transpose()? .map(pii::SecretSerdeValue::new); let is_off_session = get_off_session( payment_data.mandate_id.as_ref(), payment_data.payment_intent.off_session, ); Ok(Self { currency: payment_data.currency, confirm: true, amount: Some(amount.get_amount_as_i64()), //need to change once we move to connector module minor_amount: Some(amount), payment_method_data: (payment_data .payment_method_data .get_required_value("payment_method_data")?), statement_descriptor_suffix: payment_data.payment_intent.statement_descriptor_suffix, setup_future_usage: payment_data.payment_attempt.setup_future_usage_applied, off_session: is_off_session, mandate_id: payment_data.mandate_id.clone(), setup_mandate_details: payment_data.setup_mandate, customer_acceptance: payment_data.customer_acceptance, router_return_url, email: payment_data.email, customer_name, return_url: payment_data.payment_intent.return_url, browser_info, payment_method_type: attempt.payment_method_type, request_incremental_authorization: matches!( payment_data .payment_intent .request_incremental_authorization, Some(RequestIncrementalAuthorization::True) ), metadata: payment_data.payment_intent.metadata.clone().map(Into::into), shipping_cost: payment_data.payment_intent.shipping_cost, webhook_url, complete_authorize_url, capture_method: payment_data.payment_attempt.capture_method, connector_testing_data, customer_id: payment_data.payment_intent.customer_id, enable_partial_authorization: payment_data.payment_intent.enable_partial_authorization, payment_channel: payment_data.payment_intent.payment_channel, related_transaction_id: None, enrolled_for_3ds: true, is_stored_credential: payment_data.payment_attempt.is_stored_credential, }) } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequestData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { todo!() } } impl ForeignTryFrom<types::CaptureSyncResponse> for storage::CaptureUpdate { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( capture_sync_response: types::CaptureSyncResponse, ) -> Result<Self, Self::Error> { match capture_sync_response { types::CaptureSyncResponse::Success { resource_id, status, connector_response_reference_id, .. } => { let (connector_capture_id, processor_capture_data) = match resource_id { types::ResponseId::EncodedData(_) | types::ResponseId::NoResponseId => { (None, None) } types::ResponseId::ConnectorTransactionId(id) => { let (txn_id, txn_data) = common_utils_type::ConnectorTransactionId::form_id_and_data(id); (Some(txn_id), txn_data) } }; Ok(Self::ResponseUpdate { status: enums::CaptureStatus::foreign_try_from(status)?, connector_capture_id, connector_response_reference_id, processor_capture_data, }) } types::CaptureSyncResponse::Error { code, message, reason, status_code, .. } => Ok(Self::ErrorUpdate { status: match status_code { 500..=511 => enums::CaptureStatus::Pending, _ => enums::CaptureStatus::Failed, }, error_code: Some(code), error_message: Some(message), error_reason: reason, }), } } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthorizeData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let router_base_url = &additional_data.router_base_url; let connector_name = &additional_data.connector_name; let attempt = &payment_data.payment_attempt; let browser_info: Option<types::BrowserInformation> = payment_data .payment_attempt .browser_info .clone() .map(|b| b.parse_value("BrowserInformation")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; let redirect_response = payment_data.redirect_response.map(|redirect| { types::CompleteAuthorizeRedirectResponse { params: redirect.param, payload: redirect.json_payload, } }); let amount = payment_data.payment_attempt.get_total_amount(); let complete_authorize_url = Some(helpers::create_complete_authorize_url( router_base_url, attempt, connector_name, payment_data.creds_identifier.as_deref(), )); let braintree_metadata = payment_data .payment_intent .connector_metadata .clone() .map(|cm| { cm.parse_value::<api_models::payments::ConnectorMetadata>("ConnectorMetadata") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed parsing ConnectorMetadata") }) .transpose()? .and_then(|cm| cm.braintree); let merchant_account_id = braintree_metadata .as_ref() .and_then(|braintree| braintree.merchant_account_id.clone()); let merchant_config_currency = braintree_metadata.and_then(|braintree| braintree.merchant_config_currency); let is_off_session = get_off_session( payment_data.mandate_id.as_ref(), payment_data.payment_intent.off_session, ); Ok(Self { setup_future_usage: payment_data.payment_intent.setup_future_usage, mandate_id: payment_data.mandate_id.clone(), off_session: is_off_session, setup_mandate_details: payment_data.setup_mandate.clone(), confirm: payment_data.payment_attempt.confirm, statement_descriptor_suffix: payment_data.payment_intent.statement_descriptor_suffix, capture_method: payment_data.payment_attempt.capture_method, amount: amount.get_amount_as_i64(), // need to change once we move to connector module minor_amount: amount, currency: payment_data.currency, browser_info, email: payment_data.email, payment_method_data: payment_data.payment_method_data, connector_transaction_id: payment_data .payment_attempt .get_connector_payment_id() .map(ToString::to_string), redirect_response, connector_meta: payment_data.payment_attempt.connector_metadata, complete_authorize_url, metadata: payment_data.payment_intent.metadata, customer_acceptance: payment_data.customer_acceptance, merchant_account_id, merchant_config_currency, threeds_method_comp_ind: payment_data.threeds_method_comp_ind, is_stored_credential: payment_data.payment_attempt.is_stored_credential, }) } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthorizeData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { todo!() } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPreProcessingData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { todo!() } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPreProcessingData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let payment_method_data = payment_data.payment_method_data; let router_base_url = &additional_data.router_base_url; let attempt = &payment_data.payment_attempt; let connector_name = &additional_data.connector_name; let order_details = payment_data .payment_intent .order_details .map(|order_details| { order_details .iter() .map(|data| { data.to_owned() .parse_value("OrderDetailsWithAmount") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "OrderDetailsWithAmount", }) .attach_printable("Unable to parse OrderDetailsWithAmount") }) .collect::<Result<Vec<_>, _>>() }) .transpose()?; let merchant_connector_account_id_or_connector_name = payment_data .payment_attempt .merchant_connector_id .as_ref() .map(|mca_id| mca_id.get_string_repr()) .unwrap_or(connector_name); let webhook_url = Some(helpers::create_webhook_url( router_base_url, &attempt.merchant_id, merchant_connector_account_id_or_connector_name, )); let router_return_url = Some(helpers::create_redirect_url( router_base_url, attempt, connector_name, payment_data.creds_identifier.as_deref(), )); let complete_authorize_url = Some(helpers::create_complete_authorize_url( router_base_url, attempt, connector_name, payment_data.creds_identifier.as_deref(), )); let browser_info: Option<types::BrowserInformation> = payment_data .payment_attempt .browser_info .clone() .map(|b| b.parse_value("BrowserInformation")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; let amount = payment_data.payment_attempt.get_total_amount(); Ok(Self { payment_method_data, email: payment_data.email, currency: Some(payment_data.currency), amount: Some(amount.get_amount_as_i64()), // need to change this once we move to connector module minor_amount: Some(amount), payment_method_type: payment_data.payment_attempt.payment_method_type, setup_mandate_details: payment_data.setup_mandate, capture_method: payment_data.payment_attempt.capture_method, order_details, router_return_url, webhook_url, complete_authorize_url, browser_info, surcharge_details: payment_data.surcharge_details, connector_transaction_id: payment_data .payment_attempt .get_connector_payment_id() .map(ToString::to_string), redirect_response: None, mandate_id: payment_data.mandate_id, related_transaction_id: None, enrolled_for_3ds: true, split_payments: payment_data.payment_intent.split_payments, metadata: payment_data.payment_intent.metadata.map(Secret::new), customer_acceptance: payment_data.customer_acceptance, setup_future_usage: payment_data.payment_intent.setup_future_usage, is_stored_credential: payment_data.payment_attempt.is_stored_credential, }) } } impl ForeignFrom<payments::FraudCheck> for FrmMessage { fn foreign_from(fraud_check: payments::FraudCheck) -> Self { Self { frm_name: fraud_check.frm_name, frm_transaction_id: fraud_check.frm_transaction_id, frm_transaction_type: Some(fraud_check.frm_transaction_type.to_string()), frm_status: Some(fraud_check.frm_status.to_string()), frm_score: fraud_check.frm_score, frm_reason: fraud_check.frm_reason, frm_error: fraud_check.frm_error, } } } impl ForeignFrom<CustomerDetails> for router_request_types::CustomerDetails { fn foreign_from(customer: CustomerDetails) -> Self { Self { customer_id: Some(customer.id), name: customer.name, email: customer.email, phone: customer.phone, phone_country_code: customer.phone_country_code, tax_registration_id: customer.tax_registration_id, } } } /// The response amount details in the confirm intent response will have the combined fields from /// intent amount details and attempt amount details. #[cfg(feature = "v2")] impl ForeignFrom<( &hyperswitch_domain_models::payments::AmountDetails, &hyperswitch_domain_models::payments::payment_attempt::AttemptAmountDetails, )> for api_models::payments::PaymentAmountDetailsResponse { fn foreign_from( (intent_amount_details, attempt_amount_details): ( &hyperswitch_domain_models::payments::AmountDetails, &hyperswitch_domain_models::payments::payment_attempt::AttemptAmountDetails, ), ) -> Self { Self { order_amount: intent_amount_details.order_amount, currency: intent_amount_details.currency, shipping_cost: attempt_amount_details.get_shipping_cost(), order_tax_amount: attempt_amount_details.get_order_tax_amount(), external_tax_calculation: intent_amount_details.skip_external_tax_calculation, surcharge_calculation: intent_amount_details.skip_surcharge_calculation, surcharge_amount: attempt_amount_details.get_surcharge_amount(), tax_on_surcharge: attempt_amount_details.get_tax_on_surcharge(), net_amount: attempt_amount_details.get_net_amount(), amount_to_capture: attempt_amount_details.get_amount_to_capture(), amount_capturable: attempt_amount_details.get_amount_capturable(), amount_captured: intent_amount_details.amount_captured, } } } /// The response amount details in the confirm intent response will have the combined fields from /// intent amount details and attempt amount details. #[cfg(feature = "v2")] impl ForeignFrom<( &hyperswitch_domain_models::payments::AmountDetails, Option<&hyperswitch_domain_models::payments::payment_attempt::AttemptAmountDetails>, )> for api_models::payments::PaymentAmountDetailsResponse { fn foreign_from( (intent_amount_details, attempt_amount_details): ( &hyperswitch_domain_models::payments::AmountDetails, Option<&hyperswitch_domain_models::payments::payment_attempt::AttemptAmountDetails>, ), ) -> Self { Self { order_amount: intent_amount_details.order_amount, currency: intent_amount_details.currency, shipping_cost: attempt_amount_details .and_then(|attempt_amount| attempt_amount.get_shipping_cost()) .or(intent_amount_details.shipping_cost), order_tax_amount: attempt_amount_details .and_then(|attempt_amount| attempt_amount.get_order_tax_amount()) .or(intent_amount_details .tax_details .as_ref() .and_then(|tax_details| tax_details.get_default_tax_amount())), external_tax_calculation: intent_amount_details.skip_external_tax_calculation, surcharge_calculation: intent_amount_details.skip_surcharge_calculation, surcharge_amount: attempt_amount_details .and_then(|attempt| attempt.get_surcharge_amount()) .or(intent_amount_details.surcharge_amount), tax_on_surcharge: attempt_amount_details .and_then(|attempt| attempt.get_tax_on_surcharge()) .or(intent_amount_details.tax_on_surcharge), net_amount: attempt_amount_details .map(|attempt| attempt.get_net_amount()) .unwrap_or(intent_amount_details.calculate_net_amount()), amount_to_capture: attempt_amount_details .and_then(|attempt| attempt.get_amount_to_capture()), amount_capturable: attempt_amount_details .map(|attempt| attempt.get_amount_capturable()) .unwrap_or(MinorUnit::zero()), amount_captured: intent_amount_details.amount_captured, } } } #[cfg(feature = "v2")] impl ForeignFrom<&hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt> for api_models::payments::PaymentAttemptResponse { fn foreign_from( attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> Self { let payment_method_data: Option< api_models::payments::PaymentMethodDataResponseWithBilling, > = attempt .payment_method_data .clone() .and_then(|data| serde_json::from_value(data.expose().clone()).ok()); Self { id: attempt.get_id().to_owned(), status: attempt.status, amount: api_models::payments::PaymentAttemptAmountDetails::foreign_from( &attempt.amount_details, ), connector: attempt.connector.clone(), error: attempt .error .as_ref() .map(api_models::payments::ErrorDetails::foreign_from), authentication_type: attempt.authentication_type, created_at: attempt.created_at, modified_at: attempt.modified_at, cancellation_reason: attempt.cancellation_reason.clone(), payment_token: attempt .connector_token_details .as_ref() .and_then(|details| details.connector_mandate_id.clone()), connector_metadata: attempt.connector_metadata.clone(), payment_experience: attempt.payment_experience, payment_method_type: attempt.payment_method_type, connector_reference_id: attempt.connector_response_reference_id.clone(), payment_method_subtype: attempt.get_payment_method_type(), connector_payment_id: attempt .get_connector_payment_id() .map(|str| common_utils::types::ConnectorTransactionId::from(str.to_owned())), payment_method_id: attempt.payment_method_id.clone(), client_source: attempt.client_source.clone(), client_version: attempt.client_version.clone(), feature_metadata: attempt .feature_metadata .as_ref() .map(api_models::payments::PaymentAttemptFeatureMetadata::foreign_from), payment_method_data, } } } #[cfg(feature = "v2")] impl ForeignFrom<&hyperswitch_domain_models::payments::payment_attempt::AttemptAmountDetails> for api_models::payments::PaymentAttemptAmountDetails { fn foreign_from( amount: &hyperswitch_domain_models::payments::payment_attempt::AttemptAmountDetails, ) -> Self { Self { net_amount: amount.get_net_amount(), amount_to_capture: amount.get_amount_to_capture(), surcharge_amount: amount.get_surcharge_amount(), tax_on_surcharge: amount.get_tax_on_surcharge(), amount_capturable: amount.get_amount_capturable(), shipping_cost: amount.get_shipping_cost(), order_tax_amount: amount.get_order_tax_amount(), } } } #[cfg(feature = "v2")] impl ForeignFrom<&diesel_models::types::BillingConnectorPaymentDetails> for api_models::payments::BillingConnectorPaymentDetails { fn foreign_from(metadata: &diesel_models::types::BillingConnectorPaymentDetails) -> Self { Self { payment_processor_token: metadata.payment_processor_token.clone(), connector_customer_id: metadata.connector_customer_id.clone(), } } } #[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 { fn foreign_from( error_details: &hyperswitch_domain_models::payments::payment_attempt::ErrorDetails, ) -> Self { Self { code: error_details.code.to_owned(), message: error_details.message.to_owned(), reason: error_details.reason.clone(), unified_code: error_details.unified_code.clone(), unified_message: error_details.unified_message.clone(), network_advice_code: error_details.network_advice_code.clone(), network_decline_code: error_details.network_decline_code.clone(), network_error_message: error_details.network_error_message.clone(), } } } #[cfg(feature = "v2")] impl ForeignFrom< &hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptFeatureMetadata, > for api_models::payments::PaymentAttemptFeatureMetadata { fn foreign_from( feature_metadata: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptFeatureMetadata, ) -> Self { let revenue_recovery = feature_metadata.revenue_recovery.as_ref().map(|recovery| { api_models::payments::PaymentAttemptRevenueRecoveryData { attempt_triggered_by: recovery.attempt_triggered_by, charge_id: recovery.charge_id.clone(), } }); Self { revenue_recovery } } } #[cfg(feature = "v2")] impl ForeignFrom<&diesel_models::types::FeatureMetadata> for api_models::payments::FeatureMetadata { fn foreign_from(feature_metadata: &diesel_models::types::FeatureMetadata) -> Self { let revenue_recovery = feature_metadata .payment_revenue_recovery_metadata .as_ref() .map(|payment_revenue_recovery_metadata| { api_models::payments::PaymentRevenueRecoveryMetadata { total_retry_count: payment_revenue_recovery_metadata.total_retry_count, payment_connector_transmission: Some( payment_revenue_recovery_metadata.payment_connector_transmission, ), connector: payment_revenue_recovery_metadata.connector, billing_connector_id: payment_revenue_recovery_metadata .billing_connector_id .clone(), active_attempt_payment_connector_id: payment_revenue_recovery_metadata .active_attempt_payment_connector_id .clone(), payment_method_type: payment_revenue_recovery_metadata.payment_method_type, payment_method_subtype: payment_revenue_recovery_metadata .payment_method_subtype, billing_connector_payment_details: api_models::payments::BillingConnectorPaymentDetails::foreign_from( &payment_revenue_recovery_metadata.billing_connector_payment_details, ), 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(), invoice_billing_started_at_time: payment_revenue_recovery_metadata .invoice_billing_started_at_time, } }); let apple_pay_details = feature_metadata .apple_pay_recurring_details .clone() .map(api_models::payments::ApplePayRecurringDetails::foreign_from); let redirect_res = feature_metadata .redirect_response .clone() .map(api_models::payments::RedirectResponse::foreign_from); Self { revenue_recovery, apple_pay_recurring_details: apple_pay_details, redirect_response: redirect_res, search_tags: feature_metadata.search_tags.clone(), } } } #[cfg(feature = "v2")] impl ForeignFrom<hyperswitch_domain_models::payments::AmountDetails> for api_models::payments::AmountDetailsResponse { fn foreign_from(amount_details: hyperswitch_domain_models::payments::AmountDetails) -> Self { Self { order_amount: amount_details.order_amount, currency: amount_details.currency, shipping_cost: amount_details.shipping_cost, order_tax_amount: amount_details.tax_details.and_then(|tax_details| { tax_details.default.map(|default| default.order_tax_amount) }), external_tax_calculation: amount_details.skip_external_tax_calculation, surcharge_calculation: amount_details.skip_surcharge_calculation, surcharge_amount: amount_details.surcharge_amount, tax_on_surcharge: amount_details.tax_on_surcharge, } } } #[cfg(feature = "v2")] impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest> for diesel_models::PaymentLinkConfigRequestForPayments { fn foreign_from(config: api_models::admin::PaymentLinkConfigRequest) -> Self { Self { theme: config.theme, logo: config.logo, seller_name: config.seller_name, sdk_layout: config.sdk_layout, display_sdk_only: config.display_sdk_only, enabled_saved_payment_method: config.enabled_saved_payment_method, hide_card_nickname_field: config.hide_card_nickname_field, show_card_form_by_default: config.show_card_form_by_default, details_layout: config.details_layout, transaction_details: config.transaction_details.map(|transaction_details| { transaction_details .iter() .map(|details| { diesel_models::PaymentLinkTransactionDetails::foreign_from(details.clone()) }) .collect() }), background_image: config.background_image.map(|background_image| { diesel_models::business_profile::PaymentLinkBackgroundImageConfig::foreign_from( background_image.clone(), ) }), payment_button_text: config.payment_button_text, custom_message_for_card_terms: config.custom_message_for_card_terms, payment_button_colour: config.payment_button_colour, skip_status_screen: config.skip_status_screen, background_colour: config.background_colour, payment_button_text_colour: config.payment_button_text_colour, sdk_ui_rules: config.sdk_ui_rules, payment_link_ui_rules: config.payment_link_ui_rules, enable_button_only_on_form_ready: config.enable_button_only_on_form_ready, payment_form_header_text: config.payment_form_header_text, 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, } } } #[cfg(feature = "v2")] impl ForeignFrom<api_models::admin::PaymentLinkTransactionDetails> for diesel_models::PaymentLinkTransactionDetails { fn foreign_from(from: api_models::admin::PaymentLinkTransactionDetails) -> Self { Self { key: from.key, value: from.value, ui_configuration: from .ui_configuration .map(diesel_models::TransactionDetailsUiConfiguration::foreign_from), } } } #[cfg(feature = "v2")] impl ForeignFrom<api_models::admin::TransactionDetailsUiConfiguration> for diesel_models::TransactionDetailsUiConfiguration { fn foreign_from(from: api_models::admin::TransactionDetailsUiConfiguration) -> Self { Self { position: from.position, is_key_bold: from.is_key_bold, is_value_bold: from.is_value_bold, } } } #[cfg(feature = "v2")] impl ForeignFrom<diesel_models::PaymentLinkConfigRequestForPayments> for api_models::admin::PaymentLinkConfigRequest { fn foreign_from(config: diesel_models::PaymentLinkConfigRequestForPayments) -> Self { Self { theme: config.theme, logo: config.logo, seller_name: config.seller_name, sdk_layout: config.sdk_layout, display_sdk_only: config.display_sdk_only, enabled_saved_payment_method: config.enabled_saved_payment_method, hide_card_nickname_field: config.hide_card_nickname_field, show_card_form_by_default: config.show_card_form_by_default, details_layout: config.details_layout, transaction_details: config.transaction_details.map(|transaction_details| { transaction_details .iter() .map(|details| { api_models::admin::PaymentLinkTransactionDetails::foreign_from( details.clone(), ) }) .collect() }), background_image: config.background_image.map(|background_image| { api_models::admin::PaymentLinkBackgroundImageConfig::foreign_from( background_image.clone(), ) }), payment_button_text: config.payment_button_text, custom_message_for_card_terms: config.custom_message_for_card_terms, payment_button_colour: config.payment_button_colour, skip_status_screen: config.skip_status_screen, background_colour: config.background_colour, payment_button_text_colour: config.payment_button_text_colour, sdk_ui_rules: config.sdk_ui_rules, payment_link_ui_rules: config.payment_link_ui_rules, enable_button_only_on_form_ready: config.enable_button_only_on_form_ready, payment_form_header_text: config.payment_form_header_text, 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, } } } #[cfg(feature = "v2")] impl ForeignFrom<diesel_models::PaymentLinkTransactionDetails> for api_models::admin::PaymentLinkTransactionDetails { fn foreign_from(from: diesel_models::PaymentLinkTransactionDetails) -> Self { Self { key: from.key, value: from.value, ui_configuration: from .ui_configuration .map(api_models::admin::TransactionDetailsUiConfiguration::foreign_from), } } } #[cfg(feature = "v2")] impl ForeignFrom<diesel_models::TransactionDetailsUiConfiguration> for api_models::admin::TransactionDetailsUiConfiguration { fn foreign_from(from: diesel_models::TransactionDetailsUiConfiguration) -> Self { Self { position: from.position, is_key_bold: from.is_key_bold, is_value_bold: from.is_value_bold, } } } impl ForeignFrom<DieselConnectorMandateReferenceId> for ConnectorMandateReferenceId { fn foreign_from(value: DieselConnectorMandateReferenceId) -> Self { Self::new( value.connector_mandate_id, value.payment_method_id, None, value.mandate_metadata, value.connector_mandate_request_reference_id, ) } } impl ForeignFrom<ConnectorMandateReferenceId> for DieselConnectorMandateReferenceId { fn foreign_from(value: ConnectorMandateReferenceId) -> Self { Self { connector_mandate_id: value.get_connector_mandate_id(), payment_method_id: value.get_payment_method_id(), mandate_metadata: value.get_mandate_metadata(), connector_mandate_request_reference_id: value .get_connector_mandate_request_reference_id(), } } } impl ForeignFrom<DieselNetworkDetails> for NetworkDetails { fn foreign_from(value: DieselNetworkDetails) -> Self { Self { network_advice_code: value.network_advice_code, } } } impl ForeignFrom<NetworkDetails> for DieselNetworkDetails { fn foreign_from(value: NetworkDetails) -> Self { Self { network_advice_code: value.network_advice_code, } } } #[cfg(feature = "v2")] impl ForeignFrom<diesel_models::ConnectorTokenDetails> for Option<api_models::payments::ConnectorTokenDetails> { fn foreign_from(value: diesel_models::ConnectorTokenDetails) -> Self { let connector_token_request_reference_id = value.connector_token_request_reference_id.clone(); value.connector_mandate_id.clone().map(|mandate_id| { api_models::payments::ConnectorTokenDetails { token: mandate_id, connector_token_request_reference_id, } }) } } impl ForeignFrom<( Self, Option<&api_models::payments::AdditionalPaymentData>, Option<enums::PaymentMethod>, )> for Option<enums::PaymentMethodType> { fn foreign_from( req: ( Self, Option<&api_models::payments::AdditionalPaymentData>, Option<enums::PaymentMethod>, ), ) -> Self { let (payment_method_type, additional_pm_data, payment_method) = req; match (additional_pm_data, payment_method, payment_method_type) { ( Some(api_models::payments::AdditionalPaymentData::Card(card_info)), Some(enums::PaymentMethod::Card), original_type, ) => { let bin_card_type = card_info.card_type.as_ref().and_then(|card_type_str| { let normalized_type = card_type_str.trim().to_lowercase(); if normalized_type.is_empty() { return None; } api_models::enums::PaymentMethodType::from_str(&normalized_type) .map_err(|_| { crate::logger::warn!("Invalid BIN card_type: '{}'", card_type_str); }) .ok() }); match (original_type, bin_card_type) { // Override when there's a mismatch ( Some( original @ (enums::PaymentMethodType::Debit | enums::PaymentMethodType::Credit), ), Some(bin_type), ) if original != bin_type => { crate::logger::info!("BIN lookup override: {} -> {}", original, bin_type); bin_card_type } // Use BIN lookup if no original type exists (None, Some(bin_type)) => { crate::logger::info!( "BIN lookup override: No original payment method type, using BIN result={}", bin_type ); Some(bin_type) } // Default _ => original_type, } } // Skip BIN lookup for non-card payments _ => payment_method_type, } } } #[cfg(feature = "v1")] impl From<pm_types::TokenResponse> for domain::NetworkTokenData { fn from(token_response: pm_types::TokenResponse) -> Self { Self { token_number: token_response.authentication_details.token, token_exp_month: token_response.token_details.exp_month, token_exp_year: token_response.token_details.exp_year, token_cryptogram: Some(token_response.authentication_details.cryptogram), card_issuer: None, card_network: Some(token_response.network), card_type: None, card_issuing_country: None, bank_code: None, nick_name: None, eci: None, } } } impl ForeignFrom<&hyperswitch_domain_models::router_data::ErrorResponse> for DieselNetworkDetails { fn foreign_from(err: &hyperswitch_domain_models::router_data::ErrorResponse) -> Self { Self { network_advice_code: err.network_advice_code.clone(), } } } impl ForeignFrom<common_types::three_ds_decision_rule_engine::ThreeDSDecision> for common_enums::AuthenticationType { fn foreign_from( three_ds_decision: common_types::three_ds_decision_rule_engine::ThreeDSDecision, ) -> Self { match three_ds_decision { common_types::three_ds_decision_rule_engine::ThreeDSDecision::NoThreeDs => Self::NoThreeDs, common_types::three_ds_decision_rule_engine::ThreeDSDecision::ChallengeRequested | common_types::three_ds_decision_rule_engine::ThreeDSDecision::ChallengePreferred | common_types::three_ds_decision_rule_engine::ThreeDSDecision::ThreeDsExemptionRequestedTra | common_types::three_ds_decision_rule_engine::ThreeDSDecision::ThreeDsExemptionRequestedLowValue | common_types::three_ds_decision_rule_engine::ThreeDSDecision::IssuerThreeDsExemptionRequested => Self::ThreeDs, } } } impl ForeignFrom<common_types::three_ds_decision_rule_engine::ThreeDSDecision> for Option<common_enums::ScaExemptionType> { fn foreign_from( three_ds_decision: common_types::three_ds_decision_rule_engine::ThreeDSDecision, ) -> Self { match three_ds_decision { common_types::three_ds_decision_rule_engine::ThreeDSDecision::ThreeDsExemptionRequestedTra => { Some(common_enums::ScaExemptionType::TransactionRiskAnalysis) } common_types::three_ds_decision_rule_engine::ThreeDSDecision::ThreeDsExemptionRequestedLowValue => { Some(common_enums::ScaExemptionType::LowValue) } common_types::three_ds_decision_rule_engine::ThreeDSDecision::NoThreeDs | common_types::three_ds_decision_rule_engine::ThreeDSDecision::ChallengeRequested | common_types::three_ds_decision_rule_engine::ThreeDSDecision::ChallengePreferred | common_types::three_ds_decision_rule_engine::ThreeDSDecision::IssuerThreeDsExemptionRequested => { None } } } }
{ "crate": "router", "file": "crates/router/src/core/payments/transformers.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-9082738910631379345
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/helpers.rs // Contains: 8 structs, 3 enums use std::{borrow::Cow, collections::HashSet, net::IpAddr, ops::Deref, str::FromStr}; pub use ::payment_methods::helpers::{ populate_bin_details_for_payment_method_create, validate_payment_method_type_against_payment_method, }; #[cfg(feature = "v2")] use api_models::ephemeral_key::ClientSecretResponse; use api_models::{ mandates::RecurringDetails, payments::{additional_info as payment_additional_types, RequestSurchargeDetails}, }; use base64::Engine; #[cfg(feature = "v1")] use common_enums::enums::{CallConnectorAction, ExecutionMode, GatewaySystem}; use common_enums::ConnectorType; #[cfg(feature = "v2")] use common_utils::id_type::GenerateId; use common_utils::{ crypto::Encryptable, ext_traits::{AsyncExt, ByteSliceExt, Encode, ValueExt}, fp_utils, generate_id, id_type::{self}, new_type::{MaskedIban, MaskedSortCode}, pii, type_name, types::{ keymanager::{Identifier, KeyManagerState, ToEncryptable}, MinorUnit, }, }; use diesel_models::enums; // TODO : Evaluate all the helper functions () use error_stack::{report, ResultExt}; #[cfg(feature = "v1")] use external_services::grpc_client; use futures::future::Either; #[cfg(feature = "v1")] use hyperswitch_domain_models::payments::payment_intent::CustomerData; use hyperswitch_domain_models::{ mandates::MandateData, payment_method_data::{GetPaymentMethodType, PazeWalletData}, payments::{ self as domain_payments, payment_attempt::PaymentAttempt, payment_intent::PaymentIntentFetchConstraints, PaymentIntent, }, router_data::KlarnaSdkResponse, }; pub use hyperswitch_interfaces::{ api::ConnectorSpecifications, configs::MerchantConnectorAccountType, integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject}, }; use josekit::jwe; use masking::{ExposeInterface, PeekInterface, SwitchStrategy}; use num_traits::{FromPrimitive, ToPrimitive}; use openssl::{ derive::Deriver, pkey::PKey, symm::{decrypt_aead, Cipher}, }; use rand::Rng; #[cfg(feature = "v2")] use redis_interface::errors::RedisError; use router_env::{instrument, logger, tracing}; use rust_decimal::Decimal; use serde::{Deserialize, Serialize}; use uuid::Uuid; use x509_parser::parse_x509_certificate; use super::{ operations::{BoxedOperation, Operation, PaymentResponse}, CustomerDetails, PaymentData, }; #[cfg(feature = "v1")] use crate::core::{ payments::{ call_connector_service, flows::{ConstructFlowSpecificData, Feature}, operations::ValidateResult as OperationsValidateResult, should_add_task_to_process_tracker, OperationSessionGetters, OperationSessionSetters, TokenizationAction, }, unified_connector_service::{ send_comparison_data, update_gateway_system_in_feature_metadata, ComparisonData, }, }; #[cfg(feature = "v1")] use crate::routes; use crate::{ configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig}, connector, consts::{self, BASE64_ENGINE}, core::{ authentication, errors::{self, CustomResult, RouterResult, StorageErrorExt}, mandate::helpers::MandateGenericData, payment_methods::{ self, cards::{self}, network_tokenization, vault, }, payments, pm_auth::retrieve_payment_method_from_auth_service, }, db::StorageInterface, routes::{metrics, payment_methods as payment_methods_handler, SessionState}, services, types::{ api::{self, admin, enums as api_enums, MandateValidationFieldsExt}, domain::{self, types}, storage::{self, enums as storage_enums, ephemeral_key, CardTokenData}, transformers::{ForeignFrom, ForeignTryFrom}, AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse, MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData, RecipientIdType, RecurringMandatePaymentData, RouterData, }, utils::{ self, crypto::{self, SignMessage}, OptionExt, StringExt, }, }; #[cfg(feature = "v2")] use crate::{core::admin as core_admin, headers, types::ConnectorAuthType}; #[cfg(feature = "v1")] use crate::{ core::payment_methods::cards::create_encrypted_data, types::storage::CustomerUpdate::Update, }; #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn create_or_update_address_for_payment_by_request( session_state: &SessionState, req_address: Option<&api::Address>, address_id: Option<&str>, merchant_id: &id_type::MerchantId, customer_id: Option<&id_type::CustomerId>, merchant_key_store: &domain::MerchantKeyStore, payment_id: &id_type::PaymentId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> { let key = merchant_key_store.key.get_inner().peek(); let db = &session_state.store; let key_manager_state = &session_state.into(); Ok(match address_id { Some(id) => match req_address { Some(address) => { let encrypted_data = types::crypto_operation( &session_state.into(), type_name!(domain::Address), types::CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address.address.as_ref().and_then(|a| a.line1.clone()), line2: address.address.as_ref().and_then(|a| a.line2.clone()), line3: address.address.as_ref().and_then(|a| a.line3.clone()), state: address.address.as_ref().and_then(|a| a.state.clone()), first_name: address .address .as_ref() .and_then(|a| a.first_name.clone()), last_name: address .address .as_ref() .and_then(|a| a.last_name.clone()), zip: address.address.as_ref().and_then(|a| a.zip.clone()), phone_number: address .phone .as_ref() .and_then(|phone| phone.number.clone()), email: address .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), origin_zip: address .address .as_ref() .and_then(|a| a.origin_zip.clone()), }, ), ), Identifier::Merchant(merchant_key_store.merchant_id.clone()), key, ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting address")?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting address")?; let address_update = storage::AddressUpdate::Update { city: address .address .as_ref() .and_then(|value| value.city.clone()), country: address.address.as_ref().and_then(|value| value.country), line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, state: encryptable_address.state, zip: encryptable_address.zip, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: address .phone .as_ref() .and_then(|value| value.country_code.clone()), updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), origin_zip: encryptable_address.origin_zip, }; let address = db .find_address_by_merchant_id_payment_id_address_id( key_manager_state, merchant_id, payment_id, id, merchant_key_store, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while fetching address")?; Some( db.update_address_for_payments( key_manager_state, address, address_update, payment_id.to_owned(), merchant_key_store, storage_scheme, ) .await .map(|payment_address| payment_address.address) .to_not_found_response(errors::ApiErrorResponse::AddressNotFound)?, ) } None => Some( db.find_address_by_merchant_id_payment_id_address_id( key_manager_state, merchant_id, payment_id, id, merchant_key_store, storage_scheme, ) .await .map(|payment_address| payment_address.address), ) .transpose() .to_not_found_response(errors::ApiErrorResponse::AddressNotFound)?, }, None => match req_address { Some(address) => { let address = get_domain_address(session_state, address, merchant_id, key, storage_scheme) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting address while insert")?; let payment_address = domain::PaymentAddress { address, payment_id: payment_id.clone(), customer_id: customer_id.cloned(), }; Some( db.insert_address_for_payments( key_manager_state, payment_id, payment_address, merchant_key_store, storage_scheme, ) .await .map(|payment_address| payment_address.address) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while inserting new address")?, ) } None => None, }, }) } #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn create_or_find_address_for_payment_by_request( state: &SessionState, req_address: Option<&api::Address>, address_id: Option<&str>, merchant_id: &id_type::MerchantId, customer_id: Option<&id_type::CustomerId>, merchant_key_store: &domain::MerchantKeyStore, payment_id: &id_type::PaymentId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> { let key = merchant_key_store.key.get_inner().peek(); let db = &state.store; let key_manager_state = &state.into(); Ok(match address_id { Some(id) => Some( db.find_address_by_merchant_id_payment_id_address_id( key_manager_state, merchant_id, payment_id, id, merchant_key_store, storage_scheme, ) .await .map(|payment_address| payment_address.address), ) .transpose() .to_not_found_response(errors::ApiErrorResponse::AddressNotFound)?, None => match req_address { Some(address) => { // generate a new address here let address = get_domain_address(state, address, merchant_id, key, storage_scheme) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting address while insert")?; let payment_address = domain::PaymentAddress { address, payment_id: payment_id.clone(), customer_id: customer_id.cloned(), }; Some( db.insert_address_for_payments( key_manager_state, payment_id, payment_address, merchant_key_store, storage_scheme, ) .await .map(|payment_address| payment_address.address) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while inserting new address")?, ) } None => None, }, }) } pub async fn get_domain_address( session_state: &SessionState, address: &api_models::payments::Address, merchant_id: &id_type::MerchantId, key: &[u8], storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<domain::Address, common_utils::errors::CryptoError> { async { let address_details = &address.address.as_ref(); let encrypted_data = types::crypto_operation( &session_state.into(), type_name!(domain::Address), types::CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address.address.as_ref().and_then(|a| a.line1.clone()), line2: address.address.as_ref().and_then(|a| a.line2.clone()), line3: address.address.as_ref().and_then(|a| a.line3.clone()), state: address.address.as_ref().and_then(|a| a.state.clone()), first_name: address.address.as_ref().and_then(|a| a.first_name.clone()), last_name: address.address.as_ref().and_then(|a| a.last_name.clone()), zip: address.address.as_ref().and_then(|a| a.zip.clone()), phone_number: address .phone .as_ref() .and_then(|phone| phone.number.clone()), email: address .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), origin_zip: address.address.as_ref().and_then(|a| a.origin_zip.clone()), }, ), ), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; Ok(domain::Address { phone_number: encryptable_address.phone_number, country_code: address.phone.as_ref().and_then(|a| a.country_code.clone()), merchant_id: merchant_id.to_owned(), address_id: generate_id(consts::ID_LENGTH, "add"), city: address_details.and_then(|address_details| address_details.city.clone()), country: address_details.and_then(|address_details| address_details.country), line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, state: encryptable_address.state, created_at: common_utils::date_time::now(), first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, modified_at: common_utils::date_time::now(), zip: encryptable_address.zip, updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), origin_zip: encryptable_address.origin_zip, }) } .await } pub async fn get_address_by_id( state: &SessionState, address_id: Option<String>, merchant_key_store: &domain::MerchantKeyStore, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> { match address_id { None => Ok(None), Some(address_id) => { let db = &*state.store; Ok(db .find_address_by_merchant_id_payment_id_address_id( &state.into(), merchant_id, payment_id, &address_id, merchant_key_store, storage_scheme, ) .await .map(|payment_address| payment_address.address) .ok()) } } } #[cfg(feature = "v1")] pub async fn get_token_pm_type_mandate_details( state: &SessionState, request: &api::PaymentsRequest, mandate_type: Option<api::MandateTransactionType>, merchant_context: &domain::MerchantContext, payment_method_id: Option<String>, payment_intent_customer_id: Option<&id_type::CustomerId>, ) -> RouterResult<MandateGenericData> { let mandate_data = request.mandate_data.clone().map(MandateData::foreign_from); let ( payment_token, payment_method, payment_method_type, mandate_data, recurring_payment_data, mandate_connector_details, payment_method_info, ) = match mandate_type { Some(api::MandateTransactionType::NewMandateTransaction) => ( request.payment_token.to_owned(), request.payment_method, request.payment_method_type, mandate_data.clone(), None, None, None, ), Some(api::MandateTransactionType::RecurringMandateTransaction) => { match &request.recurring_details { Some(recurring_details) => { match recurring_details { RecurringDetails::NetworkTransactionIdAndCardDetails(_) => { (None, request.payment_method, None, None, None, None, None) } RecurringDetails::ProcessorPaymentToken(processor_payment_token) => { if let Some(mca_id) = &processor_payment_token.merchant_connector_id { let db = &*state.store; let key_manager_state = &state.into(); #[cfg(feature = "v1")] let connector_name = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_context.get_merchant_account().get_id(), mca_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: mca_id.clone().get_string_repr().to_string(), })?.connector_name; #[cfg(feature = "v2")] let connector_name = db .find_merchant_connector_account_by_id(key_manager_state, mca_id, merchant_key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: mca_id.clone().get_string_repr().to_string(), })?.connector_name; ( None, request.payment_method, None, None, None, Some(payments::MandateConnectorDetails { connector: connector_name, merchant_connector_id: Some(mca_id.clone()), }), None, ) } else { (None, request.payment_method, None, None, None, None, None) } } RecurringDetails::MandateId(mandate_id) => { let mandate_generic_data = Box::pin(get_token_for_recurring_mandate( state, request, merchant_context, mandate_id.to_owned(), )) .await?; ( mandate_generic_data.token, mandate_generic_data.payment_method, mandate_generic_data .payment_method_type .or(request.payment_method_type), None, mandate_generic_data.recurring_mandate_payment_data, mandate_generic_data.mandate_connector, mandate_generic_data.payment_method_info, ) } RecurringDetails::PaymentMethodId(payment_method_id) => { let payment_method_info = state .store .find_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), payment_method_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response( errors::ApiErrorResponse::PaymentMethodNotFound, )?; let customer_id = request .get_customer_id() .get_required_value("customer_id")?; verify_mandate_details_for_recurring_payments( &payment_method_info.merchant_id, merchant_context.get_merchant_account().get_id(), &payment_method_info.customer_id, customer_id, )?; ( None, payment_method_info.get_payment_method_type(), payment_method_info.get_payment_method_subtype(), None, None, None, Some(payment_method_info), ) } } } None => { if let Some(mandate_id) = request.mandate_id.clone() { let mandate_generic_data = Box::pin(get_token_for_recurring_mandate( state, request, merchant_context, mandate_id, )) .await?; ( mandate_generic_data.token, mandate_generic_data.payment_method, mandate_generic_data .payment_method_type .or(request.payment_method_type), None, mandate_generic_data.recurring_mandate_payment_data, mandate_generic_data.mandate_connector, mandate_generic_data.payment_method_info, ) } else if request .payment_method_type .map(|payment_method_type_value| { payment_method_type_value .should_check_for_customer_saved_payment_method_type() }) .unwrap_or(false) { let payment_request_customer_id = request.get_customer_id(); if let Some(customer_id) = payment_request_customer_id.or(payment_intent_customer_id) { let customer_saved_pm_option = match state .store .find_payment_method_by_customer_id_merchant_id_list( &(state.into()), merchant_context.get_merchant_key_store(), customer_id, merchant_context.get_merchant_account().get_id(), None, ) .await { Ok(customer_payment_methods) => Ok(customer_payment_methods .iter() .find(|payment_method| { payment_method.get_payment_method_subtype() == request.payment_method_type }) .cloned()), Err(error) => { if error.current_context().is_db_not_found() { Ok(None) } else { Err(error) .change_context( errors::ApiErrorResponse::InternalServerError, ) .attach_printable( "failed to find payment methods for a customer", ) } } }?; ( None, request.payment_method, request.payment_method_type, None, None, None, customer_saved_pm_option, ) } else { ( None, request.payment_method, request.payment_method_type, None, None, None, None, ) } } else { let payment_method_info = payment_method_id .async_map(|payment_method_id| async move { state .store .find_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), &payment_method_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response( errors::ApiErrorResponse::PaymentMethodNotFound, ) }) .await .transpose()?; ( request.payment_token.to_owned(), request.payment_method, request.payment_method_type, None, None, None, payment_method_info, ) } } } } None => { let payment_method_info = payment_method_id .async_map(|payment_method_id| async move { state .store .find_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), &payment_method_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) }) .await .transpose()?; ( request.payment_token.to_owned(), request.payment_method, request.payment_method_type, mandate_data, None, None, payment_method_info, ) } }; Ok(MandateGenericData { token: payment_token, payment_method, payment_method_type, mandate_data, recurring_mandate_payment_data: recurring_payment_data, mandate_connector: mandate_connector_details, payment_method_info, }) } #[cfg(feature = "v1")] pub async fn get_token_for_recurring_mandate( state: &SessionState, req: &api::PaymentsRequest, merchant_context: &domain::MerchantContext, mandate_id: String, ) -> RouterResult<MandateGenericData> { let db = &*state.store; let mandate = db .find_mandate_by_merchant_id_mandate_id( merchant_context.get_merchant_account().get_id(), mandate_id.as_str(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; let key_manager_state: KeyManagerState = state.into(); let original_payment_intent = mandate .original_payment_id .as_ref() .async_map(|payment_id| async { db.find_payment_intent_by_payment_id_merchant_id( &key_manager_state, payment_id, &mandate.merchant_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .map_err(|err| logger::error!(mandate_original_payment_not_found=?err)) .ok() }) .await .flatten(); let original_payment_attempt = original_payment_intent .as_ref() .async_map(|payment_intent| async { db.find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, &mandate.merchant_id, payment_intent.active_attempt.get_id().as_str(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .map_err(|err| logger::error!(mandate_original_payment_attempt_not_found=?err)) .ok() }) .await .flatten(); let original_payment_authorized_amount = original_payment_attempt .clone() .map(|pa| pa.net_amount.get_total_amount().get_amount_as_i64()); let original_payment_authorized_currency = original_payment_intent.clone().and_then(|pi| pi.currency); let customer = req.get_customer_id().get_required_value("customer_id")?; let payment_method_id = { if &mandate.customer_id != customer { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "customer_id must match mandate customer_id".into() }))? } if mandate.mandate_status != storage_enums::MandateStatus::Active { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "mandate is not active".into() }))? }; mandate.payment_method_id.clone() }; verify_mandate_details( req.amount.get_required_value("amount")?.into(), req.currency.get_required_value("currency")?, mandate.clone(), )?; let payment_method = db .find_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), payment_method_id.as_str(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; let token = Uuid::new_v4().to_string(); let payment_method_type = payment_method.get_payment_method_subtype(); let mandate_connector_details = payments::MandateConnectorDetails { connector: mandate.connector, merchant_connector_id: mandate.merchant_connector_id, }; if let Some(enums::PaymentMethod::Card) = payment_method.get_payment_method_type() { if state.conf.locker.locker_enabled { let _ = cards::get_lookup_key_from_locker( state, &token, &payment_method, merchant_context.get_merchant_key_store(), ) .await?; } if let Some(payment_method_from_request) = req.payment_method { let pm: storage_enums::PaymentMethod = payment_method_from_request; if payment_method .get_payment_method_type() .is_some_and(|payment_method| payment_method != pm) { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "payment method in request does not match previously provided payment \ method information" .into() }))? } }; Ok(MandateGenericData { token: Some(token), payment_method: payment_method.get_payment_method_type(), recurring_mandate_payment_data: Some(RecurringMandatePaymentData { payment_method_type, original_payment_authorized_amount, original_payment_authorized_currency, mandate_metadata: None, }), payment_method_type: payment_method.get_payment_method_subtype(), mandate_connector: Some(mandate_connector_details), mandate_data: None, payment_method_info: Some(payment_method), }) } else { Ok(MandateGenericData { token: None, payment_method: payment_method.get_payment_method_type(), recurring_mandate_payment_data: Some(RecurringMandatePaymentData { payment_method_type, original_payment_authorized_amount, original_payment_authorized_currency, mandate_metadata: None, }), payment_method_type: payment_method.get_payment_method_subtype(), mandate_connector: Some(mandate_connector_details), mandate_data: None, payment_method_info: Some(payment_method), }) } } #[instrument(skip_all)] /// Check weather the merchant id in the request /// and merchant id in the merchant account are same. pub fn validate_merchant_id( merchant_id: &id_type::MerchantId, request_merchant_id: Option<&id_type::MerchantId>, ) -> CustomResult<(), errors::ApiErrorResponse> { // Get Merchant Id from the merchant // or get from merchant account let request_merchant_id = request_merchant_id.unwrap_or(merchant_id); utils::when(merchant_id.ne(request_merchant_id), || { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: format!( "Invalid `merchant_id`: {} not found in merchant account", request_merchant_id.get_string_repr() ) })) }) } #[instrument(skip_all)] pub fn validate_request_amount_and_amount_to_capture( op_amount: Option<api::Amount>, op_amount_to_capture: Option<MinorUnit>, surcharge_details: Option<RequestSurchargeDetails>, ) -> CustomResult<(), errors::ApiErrorResponse> { match (op_amount, op_amount_to_capture) { (None, _) => Ok(()), (Some(_amount), None) => Ok(()), (Some(amount), Some(amount_to_capture)) => { match amount { api::Amount::Value(amount_inner) => { // If both amount and amount to capture is present // then amount to be capture should be less than or equal to request amount let total_capturable_amount = MinorUnit::new(amount_inner.get()) + surcharge_details .map(|surcharge_details| surcharge_details.get_total_surcharge_amount()) .unwrap_or_default(); utils::when(!amount_to_capture.le(&total_capturable_amount), || { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: format!( "amount_to_capture is greater than amount capture_amount: {amount_to_capture:?} request_amount: {amount:?}" ) })) }) } api::Amount::Zero => { // If the amount is Null but still amount_to_capture is passed this is invalid and Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "amount_to_capture should not exist for when amount = 0" .to_string() })) } } } } } #[cfg(feature = "v1")] /// if capture method = automatic, amount_to_capture(if provided) must be equal to amount #[instrument(skip_all)] pub fn validate_amount_to_capture_and_capture_method( payment_attempt: Option<&PaymentAttempt>, request: &api_models::payments::PaymentsRequest, ) -> CustomResult<(), errors::ApiErrorResponse> { let option_net_amount = hyperswitch_domain_models::payments::payment_attempt::NetAmount::from_payments_request_and_payment_attempt( request, payment_attempt, ); let capture_method = request .capture_method .or(payment_attempt .map(|payment_attempt| payment_attempt.capture_method.unwrap_or_default())) .unwrap_or_default(); if matches!( capture_method, api_enums::CaptureMethod::Automatic | api_enums::CaptureMethod::SequentialAutomatic ) { let total_capturable_amount = option_net_amount.map(|net_amount| net_amount.get_total_amount()); let amount_to_capture = request .amount_to_capture .or(payment_attempt.and_then(|pa| pa.amount_to_capture)); if let Some((total_capturable_amount, amount_to_capture)) = total_capturable_amount.zip(amount_to_capture) { utils::when(amount_to_capture != total_capturable_amount, || { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "amount_to_capture must be equal to total_capturable_amount when capture_method = automatic".into() })) }) } else { Ok(()) } } else { Ok(()) } } #[instrument(skip_all)] pub fn validate_card_data( payment_method_data: Option<api::PaymentMethodData>, ) -> CustomResult<(), errors::ApiErrorResponse> { if let Some(api::PaymentMethodData::Card(card)) = payment_method_data { let cvc = card.card_cvc.peek().to_string(); if cvc.len() < 3 || cvc.len() > 4 { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "Invalid card_cvc length".to_string() }))? } let card_cvc = cvc.parse::<u16>() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "card_cvc", })?; ::cards::CardSecurityCode::try_from(card_cvc).change_context( errors::ApiErrorResponse::PreconditionFailed { message: "Invalid Card CVC".to_string(), }, )?; validate_card_expiry(&card.card_exp_month, &card.card_exp_year)?; } Ok(()) } #[instrument(skip_all)] pub fn validate_card_expiry( card_exp_month: &masking::Secret<String>, card_exp_year: &masking::Secret<String>, ) -> CustomResult<(), errors::ApiErrorResponse> { let exp_month = card_exp_month .peek() .to_string() .parse::<u8>() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "card_exp_month", })?; let month = ::cards::CardExpirationMonth::try_from(exp_month).change_context( errors::ApiErrorResponse::PreconditionFailed { message: "Invalid Expiry Month".to_string(), }, )?; let mut year_str = card_exp_year.peek().to_string(); if year_str.len() == 2 { year_str = format!("20{year_str}"); } let exp_year = year_str .parse::<u16>() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "card_exp_year", })?; let year = ::cards::CardExpirationYear::try_from(exp_year).change_context( errors::ApiErrorResponse::PreconditionFailed { message: "Invalid Expiry Year".to_string(), }, )?; let card_expiration = ::cards::CardExpiration { month, year }; let is_expired = card_expiration.is_expired().change_context( errors::ApiErrorResponse::PreconditionFailed { message: "Invalid card data".to_string(), }, )?; if is_expired { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "Card Expired".to_string() }))? } Ok(()) } pub fn infer_payment_type( amount: api::Amount, mandate_type: Option<&api::MandateTransactionType>, ) -> api_enums::PaymentType { match mandate_type { Some(api::MandateTransactionType::NewMandateTransaction) => { if let api::Amount::Value(_) = amount { api_enums::PaymentType::NewMandate } else { api_enums::PaymentType::SetupMandate } } Some(api::MandateTransactionType::RecurringMandateTransaction) => { api_enums::PaymentType::RecurringMandate } None => api_enums::PaymentType::Normal, } } pub fn validate_mandate( req: impl Into<api::MandateValidationFields>, is_confirm_operation: bool, ) -> CustomResult<Option<api::MandateTransactionType>, errors::ApiErrorResponse> { let req: api::MandateValidationFields = req.into(); match req.validate_and_get_mandate_type().change_context( errors::ApiErrorResponse::MandateValidationFailed { reason: "Expected one out of recurring_details and mandate_data but got both".into(), }, )? { Some(api::MandateTransactionType::NewMandateTransaction) => { validate_new_mandate_request(req, is_confirm_operation)?; Ok(Some(api::MandateTransactionType::NewMandateTransaction)) } Some(api::MandateTransactionType::RecurringMandateTransaction) => { validate_recurring_mandate(req)?; Ok(Some( api::MandateTransactionType::RecurringMandateTransaction, )) } None => Ok(None), } } pub fn validate_recurring_details_and_token( recurring_details: &Option<RecurringDetails>, payment_token: &Option<String>, mandate_id: &Option<String>, ) -> CustomResult<(), errors::ApiErrorResponse> { utils::when( recurring_details.is_some() && payment_token.is_some(), || { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "Expected one out of recurring_details and payment_token but got both" .into() })) }, )?; utils::when(recurring_details.is_some() && mandate_id.is_some(), || { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "Expected one out of recurring_details and mandate_id but got both".into() })) })?; Ok(()) } pub fn validate_overcapture_request( enable_overcapture: &Option<common_types::primitive_wrappers::EnableOvercaptureBool>, capture_method: &Option<common_enums::CaptureMethod>, ) -> CustomResult<(), errors::ApiErrorResponse> { if let Some(overcapture) = enable_overcapture { utils::when( *overcapture.deref() && !matches!(*capture_method, Some(common_enums::CaptureMethod::Manual)), || { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "Invalid overcapture request: supported only with manual capture" .into() })) }, )?; } Ok(()) } fn validate_new_mandate_request( req: api::MandateValidationFields, is_confirm_operation: bool, ) -> RouterResult<()> { // We need not check for customer_id in the confirm request if it is already passed // in create request fp_utils::when(!is_confirm_operation && req.customer_id.is_none(), || { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "`customer_id` is mandatory for mandates".into() })) })?; let mandate_data = req .mandate_data .clone() .get_required_value("mandate_data")?; // Only use this validation if the customer_acceptance is present if mandate_data .customer_acceptance .map(|inner| inner.acceptance_type == api::AcceptanceType::Online && inner.online.is_none()) .unwrap_or(false) { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "`mandate_data.customer_acceptance.online` is required when \ `mandate_data.customer_acceptance.acceptance_type` is `online`" .into() }))? } let mandate_details = match mandate_data.mandate_type { Some(api_models::payments::MandateType::SingleUse(details)) => Some(details), Some(api_models::payments::MandateType::MultiUse(details)) => details, _ => None, }; mandate_details.and_then(|md| md.start_date.zip(md.end_date)).map(|(start_date, end_date)| utils::when (start_date >= end_date, || { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "`mandate_data.mandate_type.{multi_use|single_use}.start_date` should be greater than \ `mandate_data.mandate_type.{multi_use|single_use}.end_date`" .into() })) })).transpose()?; Ok(()) } pub fn validate_customer_id_mandatory_cases( has_setup_future_usage: bool, customer_id: Option<&id_type::CustomerId>, ) -> RouterResult<()> { match (has_setup_future_usage, customer_id) { (true, None) => Err(errors::ApiErrorResponse::PreconditionFailed { message: "customer_id is mandatory when setup_future_usage is given".to_string(), } .into()), _ => Ok(()), } } #[cfg(feature = "v1")] pub fn create_startpay_url( base_url: &str, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, ) -> String { format!( "{}/payments/redirect/{}/{}/{}", base_url, payment_intent.get_id().get_string_repr(), payment_intent.merchant_id.get_string_repr(), payment_attempt.attempt_id ) } pub fn create_redirect_url( router_base_url: &String, payment_attempt: &PaymentAttempt, connector_name: impl std::fmt::Display, creds_identifier: Option<&str>, ) -> String { let creds_identifier_path = creds_identifier.map_or_else(String::new, |cd| format!("/{cd}")); format!( "{}/payments/{}/{}/redirect/response/{}", router_base_url, payment_attempt.payment_id.get_string_repr(), payment_attempt.merchant_id.get_string_repr(), connector_name, ) + creds_identifier_path.as_ref() } pub fn create_authentication_url( router_base_url: &str, payment_attempt: &PaymentAttempt, ) -> String { format!( "{router_base_url}/payments/{}/3ds/authentication", payment_attempt.payment_id.get_string_repr() ) } pub fn create_authorize_url( router_base_url: &str, payment_attempt: &PaymentAttempt, connector_name: impl std::fmt::Display, ) -> String { format!( "{}/payments/{}/{}/authorize/{}", router_base_url, payment_attempt.payment_id.get_string_repr(), payment_attempt.merchant_id.get_string_repr(), connector_name ) } pub fn create_webhook_url( router_base_url: &str, merchant_id: &id_type::MerchantId, merchant_connector_id_or_connector_name: &str, ) -> String { format!( "{}/webhooks/{}/{}", router_base_url, merchant_id.get_string_repr(), merchant_connector_id_or_connector_name, ) } pub fn create_complete_authorize_url( router_base_url: &String, payment_attempt: &PaymentAttempt, connector_name: impl std::fmt::Display, creds_identifier: Option<&str>, ) -> String { let creds_identifier = creds_identifier.map_or_else(String::new, |creds_identifier| { format!("/{creds_identifier}") }); format!( "{}/payments/{}/{}/redirect/complete/{}{}", router_base_url, payment_attempt.payment_id.get_string_repr(), payment_attempt.merchant_id.get_string_repr(), connector_name, creds_identifier ) } fn validate_recurring_mandate(req: api::MandateValidationFields) -> RouterResult<()> { let recurring_details = req .recurring_details .get_required_value("recurring_details")?; match recurring_details { RecurringDetails::ProcessorPaymentToken(_) | RecurringDetails::NetworkTransactionIdAndCardDetails(_) => Ok(()), _ => { req.customer_id.check_value_present("customer_id")?; let confirm = req.confirm.get_required_value("confirm")?; if !confirm { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "`confirm` must be `true` for mandates".into() }))? } let off_session = req.off_session.get_required_value("off_session")?; if !off_session { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "`off_session` should be `true` for mandates".into() }))? } Ok(()) } } } pub fn verify_mandate_details( request_amount: MinorUnit, request_currency: api_enums::Currency, mandate: storage::Mandate, ) -> RouterResult<()> { match mandate.mandate_type { storage_enums::MandateType::SingleUse => utils::when( mandate .mandate_amount .map(|mandate_amount| request_amount.get_amount_as_i64() > mandate_amount) .unwrap_or(true), || { Err(report!(errors::ApiErrorResponse::MandateValidationFailed { reason: "request amount is greater than mandate amount".into() })) }, ), storage::enums::MandateType::MultiUse => utils::when( mandate .mandate_amount .map(|mandate_amount| { (mandate.amount_captured.unwrap_or(0) + request_amount.get_amount_as_i64()) > mandate_amount }) .unwrap_or(false), || { Err(report!(errors::ApiErrorResponse::MandateValidationFailed { reason: "request amount is greater than mandate amount".into() })) }, ), }?; utils::when( mandate .mandate_currency .map(|mandate_currency| mandate_currency != request_currency) .unwrap_or(false), || { Err(report!(errors::ApiErrorResponse::MandateValidationFailed { reason: "cross currency mandates not supported".into() })) }, ) } pub fn verify_mandate_details_for_recurring_payments( mandate_merchant_id: &id_type::MerchantId, merchant_id: &id_type::MerchantId, mandate_customer_id: &id_type::CustomerId, customer_id: &id_type::CustomerId, ) -> RouterResult<()> { if mandate_merchant_id != merchant_id { Err(report!(errors::ApiErrorResponse::MandateNotFound))? } if mandate_customer_id != customer_id { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "customer_id must match mandate customer_id".into() }))? } Ok(()) } #[instrument(skip_all)] pub fn payment_attempt_status_fsm( payment_method_data: Option<&api::payments::PaymentMethodData>, confirm: Option<bool>, ) -> storage_enums::AttemptStatus { match payment_method_data { Some(_) => match confirm { Some(true) => storage_enums::AttemptStatus::PaymentMethodAwaited, _ => storage_enums::AttemptStatus::ConfirmationAwaited, }, None => storage_enums::AttemptStatus::PaymentMethodAwaited, } } pub fn payment_intent_status_fsm( payment_method_data: Option<&api::PaymentMethodData>, confirm: Option<bool>, ) -> storage_enums::IntentStatus { match payment_method_data { Some(_) => match confirm { Some(true) => storage_enums::IntentStatus::RequiresPaymentMethod, _ => storage_enums::IntentStatus::RequiresConfirmation, }, None => storage_enums::IntentStatus::RequiresPaymentMethod, } } #[cfg(feature = "v1")] pub async fn add_domain_task_to_pt<Op>( operation: &Op, state: &SessionState, payment_attempt: &PaymentAttempt, requeue: bool, schedule_time: Option<time::PrimitiveDateTime>, ) -> CustomResult<(), errors::ApiErrorResponse> where Op: std::fmt::Debug, { if check_if_operation_confirm(operation) { match schedule_time { Some(stime) => { if !requeue { // Here, increment the count of added tasks every time a payment has been confirmed or PSync has been called metrics::TASKS_ADDED_COUNT.add( 1, router_env::metric_attributes!(("flow", format!("{:#?}", operation))), ); super::add_process_sync_task(&*state.store, payment_attempt, stime) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while adding task to process tracker") } else { // When the requeue is true, we reset the tasks count as we reset the task every time it is requeued metrics::TASKS_RESET_COUNT.add( 1, router_env::metric_attributes!(("flow", format!("{:#?}", operation))), ); super::reset_process_sync_task(&*state.store, payment_attempt, stime) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while updating task in process tracker") } } None => Ok(()), } } else { Ok(()) } } pub fn response_operation<'a, F, R, D>() -> BoxedOperation<'a, F, R, D> where F: Send + Clone, PaymentResponse: Operation<F, R, Data = D>, { Box::new(PaymentResponse) } pub fn validate_max_amount( amount: api_models::payments::Amount, ) -> CustomResult<(), errors::ApiErrorResponse> { match amount { api_models::payments::Amount::Value(value) => { utils::when(value.get() > consts::MAX_ALLOWED_AMOUNT, || { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: format!( "amount should not be more than {}", consts::MAX_ALLOWED_AMOUNT ) })) }) } api_models::payments::Amount::Zero => Ok(()), } } #[cfg(feature = "v1")] /// Check whether the customer information that is sent in the root of payments request /// and in the customer object are same, if the values mismatch return an error pub fn validate_customer_information( request: &api_models::payments::PaymentsRequest, ) -> RouterResult<()> { if let Some(mismatched_fields) = request.validate_customer_details_in_request() { let mismatched_fields = mismatched_fields.join(", "); Err(errors::ApiErrorResponse::PreconditionFailed { message: format!( "The field names `{mismatched_fields}` sent in both places is ambiguous" ), })? } else { Ok(()) } } pub async fn validate_card_ip_blocking_for_business_profile( state: &SessionState, ip: IpAddr, fingerprnt: masking::Secret<String>, card_testing_guard_config: &diesel_models::business_profile::CardTestingGuardConfig, ) -> RouterResult<String> { let cache_key = format!( "{}_{}_{}", consts::CARD_IP_BLOCKING_CACHE_KEY_PREFIX, fingerprnt.peek(), ip ); let unsuccessful_payment_threshold = card_testing_guard_config.card_ip_blocking_threshold; validate_blocking_threshold(state, unsuccessful_payment_threshold, cache_key).await } pub async fn validate_guest_user_card_blocking_for_business_profile( state: &SessionState, fingerprnt: masking::Secret<String>, customer_id: Option<id_type::CustomerId>, card_testing_guard_config: &diesel_models::business_profile::CardTestingGuardConfig, ) -> RouterResult<String> { let cache_key = format!( "{}_{}", consts::GUEST_USER_CARD_BLOCKING_CACHE_KEY_PREFIX, fingerprnt.peek() ); let unsuccessful_payment_threshold = card_testing_guard_config.guest_user_card_blocking_threshold; if customer_id.is_none() { Ok(validate_blocking_threshold(state, unsuccessful_payment_threshold, cache_key).await?) } else { Ok(cache_key) } } pub async fn validate_customer_id_blocking_for_business_profile( state: &SessionState, customer_id: id_type::CustomerId, profile_id: &id_type::ProfileId, card_testing_guard_config: &diesel_models::business_profile::CardTestingGuardConfig, ) -> RouterResult<String> { let cache_key = format!( "{}_{}_{}", consts::CUSTOMER_ID_BLOCKING_PREFIX, profile_id.get_string_repr(), customer_id.get_string_repr(), ); let unsuccessful_payment_threshold = card_testing_guard_config.customer_id_blocking_threshold; validate_blocking_threshold(state, unsuccessful_payment_threshold, cache_key).await } pub async fn validate_blocking_threshold( state: &SessionState, unsuccessful_payment_threshold: i32, cache_key: String, ) -> RouterResult<String> { match services::card_testing_guard::get_blocked_count_from_cache(state, &cache_key).await { Ok(Some(unsuccessful_payment_count)) => { if unsuccessful_payment_count >= unsuccessful_payment_threshold { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Blocked due to suspicious activity".to_string(), })? } else { Ok(cache_key) } } Ok(None) => Ok(cache_key), Err(error) => Err(errors::ApiErrorResponse::InternalServerError).attach_printable(error)?, } } #[cfg(feature = "v1")] /// Get the customer details from customer field if present /// or from the individual fields in `PaymentsRequest` #[instrument(skip_all)] pub fn get_customer_details_from_request( request: &api_models::payments::PaymentsRequest, ) -> CustomerDetails { let customer_id = request.get_customer_id().map(ToOwned::to_owned); let customer_name = request .customer .as_ref() .and_then(|customer_details| customer_details.name.clone()) .or(request.name.clone()); let customer_email = request .customer .as_ref() .and_then(|customer_details| customer_details.email.clone()) .or(request.email.clone()); let customer_phone = request .customer .as_ref() .and_then(|customer_details| customer_details.phone.clone()) .or(request.phone.clone()); let customer_phone_code = request .customer .as_ref() .and_then(|customer_details| customer_details.phone_country_code.clone()) .or(request.phone_country_code.clone()); let tax_registration_id = request .customer .as_ref() .and_then(|customer_details| customer_details.tax_registration_id.clone()); CustomerDetails { customer_id, name: customer_name, email: customer_email, phone: customer_phone, phone_country_code: customer_phone_code, tax_registration_id, } } pub async fn get_connector_default( _state: &SessionState, request_connector: Option<serde_json::Value>, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { Ok(request_connector.map_or( api::ConnectorChoice::Decide, api::ConnectorChoice::StraightThrough, )) } #[cfg(feature = "v2")] pub async fn get_connector_data_from_request( state: &SessionState, req: Option<common_types::domain::MerchantConnectorAuthDetails>, ) -> CustomResult<api::ConnectorData, errors::ApiErrorResponse> { let connector = req .as_ref() .map(|connector_details| connector_details.connector_name.to_string()) .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "merchant_connector_details", })?; let connector_data: api::ConnectorData = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector, api::GetToken::Connector, None, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; Ok(connector_data) } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::type_complexity)] pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>( _state: &SessionState, _operation: BoxedOperation<'a, F, R, D>, _payment_data: &mut PaymentData<F>, _req: Option<CustomerDetails>, _merchant_id: &id_type::MerchantId, _key_store: &domain::MerchantKeyStore, _storage_scheme: common_enums::enums::MerchantStorageScheme, ) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError> { todo!() } #[cfg(feature = "v1")] #[instrument(skip_all)] #[allow(clippy::type_complexity)] pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>( state: &SessionState, operation: BoxedOperation<'a, F, R, D>, payment_data: &mut PaymentData<F>, req: Option<CustomerDetails>, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: common_enums::enums::MerchantStorageScheme, ) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError> { let request_customer_details = req .get_required_value("customer") .change_context(errors::StorageError::ValueNotFound("customer".to_owned()))?; let temp_customer_data = if request_customer_details.name.is_some() || request_customer_details.email.is_some() || request_customer_details.phone.is_some() || request_customer_details.phone_country_code.is_some() || request_customer_details.tax_registration_id.is_some() { Some(CustomerData { name: request_customer_details.name.clone(), email: request_customer_details.email.clone(), phone: request_customer_details.phone.clone(), phone_country_code: request_customer_details.phone_country_code.clone(), tax_registration_id: request_customer_details.tax_registration_id.clone(), }) } else { None }; // Updation of Customer Details for the cases where both customer_id and specific customer // details are provided in Payment Update Request let raw_customer_details = payment_data .payment_intent .customer_details .clone() .map(|customer_details_encrypted| { customer_details_encrypted .into_inner() .expose() .parse_value::<CustomerData>("CustomerData") }) .transpose() .change_context(errors::StorageError::DeserializationFailed) .attach_printable("Failed to parse customer data from payment intent")? .map(|parsed_customer_data| CustomerData { name: request_customer_details .name .clone() .or(parsed_customer_data.name.clone()), email: request_customer_details .email .clone() .or(parsed_customer_data.email.clone()), phone: request_customer_details .phone .clone() .or(parsed_customer_data.phone.clone()), phone_country_code: request_customer_details .phone_country_code .clone() .or(parsed_customer_data.phone_country_code.clone()), tax_registration_id: request_customer_details .tax_registration_id .clone() .or(parsed_customer_data.tax_registration_id.clone()), }) .or(temp_customer_data); let key_manager_state = state.into(); payment_data.payment_intent.customer_details = raw_customer_details .clone() .async_map(|customer_details| { create_encrypted_data(&key_manager_state, key_store, customer_details) }) .await .transpose() .change_context(errors::StorageError::EncryptionError) .attach_printable("Unable to encrypt customer details")?; let customer_id = request_customer_details .customer_id .or(payment_data.payment_intent.customer_id.clone()); let db = &*state.store; let key_manager_state = &state.into(); let optional_customer = match customer_id { Some(customer_id) => { let customer_data = db .find_customer_optional_by_customer_id_merchant_id( key_manager_state, &customer_id, merchant_id, key_store, storage_scheme, ) .await?; let key = key_store.key.get_inner().peek(); let encrypted_data = types::crypto_operation( key_manager_state, type_name!(domain::Customer), types::CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableCustomer::to_encryptable( domain::FromRequestEncryptableCustomer { name: request_customer_details.name.clone(), email: request_customer_details .email .as_ref() .map(|e| e.clone().expose().switch_strategy()), phone: request_customer_details.phone.clone(), tax_registration_id: None, }, ), ), Identifier::Merchant(key_store.merchant_id.clone()), key, ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::StorageError::SerializationFailed) .attach_printable("Failed while encrypting Customer while Update")?; let encryptable_customer = domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::StorageError::SerializationFailed) .attach_printable("Failed while encrypting Customer while Update")?; Some(match customer_data { Some(c) => { // Update the customer data if new data is passed in the request if request_customer_details.email.is_some() | request_customer_details.name.is_some() | request_customer_details.phone.is_some() | request_customer_details.phone_country_code.is_some() | request_customer_details.tax_registration_id.is_some() { let customer_update = Update { name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { let encryptable: Encryptable< masking::Secret<String, pii::EmailStrategy>, > = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), phone: Box::new(encryptable_customer.phone), phone_country_code: request_customer_details.phone_country_code, description: None, connector_customer: Box::new(None), metadata: Box::new(None), address_id: None, tax_registration_id: encryptable_customer.tax_registration_id, }; db.update_customer_by_customer_id_merchant_id( key_manager_state, customer_id, merchant_id.to_owned(), c, customer_update, key_store, storage_scheme, ) .await } else { Ok(c) } } None => { let new_customer = domain::Customer { customer_id, merchant_id: merchant_id.to_owned(), name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { let encryptable: Encryptable< masking::Secret<String, pii::EmailStrategy>, > = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), phone: encryptable_customer.phone, phone_country_code: request_customer_details.phone_country_code.clone(), description: None, created_at: common_utils::date_time::now(), metadata: None, modified_at: common_utils::date_time::now(), connector_customer: None, address_id: None, default_payment_method_id: None, updated_by: None, version: common_types::consts::API_VERSION, tax_registration_id: encryptable_customer.tax_registration_id, }; metrics::CUSTOMER_CREATED.add(1, &[]); db.insert_customer(new_customer, key_manager_state, key_store, storage_scheme) .await } }) } None => match &payment_data.payment_intent.customer_id { None => None, Some(customer_id) => db .find_customer_optional_by_customer_id_merchant_id( key_manager_state, customer_id, merchant_id, key_store, storage_scheme, ) .await? .map(Ok), }, }; Ok(( operation, match optional_customer { Some(customer) => { let customer = customer?; payment_data.payment_intent.customer_id = Some(customer.customer_id.clone()); payment_data.email = payment_data.email.clone().or_else(|| { customer .email .clone() .map(|encrypted_value| encrypted_value.into()) }); Some(customer) } None => None, }, )) } #[cfg(feature = "v1")] pub async fn retrieve_payment_method_with_temporary_token( state: &SessionState, token: &str, payment_intent: &PaymentIntent, payment_attempt: &PaymentAttempt, merchant_key_store: &domain::MerchantKeyStore, card_token_data: Option<&domain::CardToken>, ) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> { let (pm, supplementary_data) = vault::Vault::get_payment_method_data_from_locker(state, token, merchant_key_store) .await .attach_printable( "Payment method for given token not found or there was a problem fetching it", )?; utils::when( supplementary_data .customer_id .ne(&payment_intent.customer_id), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "customer associated with payment method and customer passed in payment are not same".into() }) }, )?; Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(match pm { Some(domain::PaymentMethodData::Card(card)) => { let mut updated_card = card.clone(); let mut is_card_updated = false; // The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked // from payment_method_data.card_token object let name_on_card = card_token_data.and_then(|token_data| token_data.card_holder_name.clone()); if let Some(name) = name_on_card.clone() { if !name.peek().is_empty() { is_card_updated = true; updated_card.nick_name = name_on_card; } } if let Some(token_data) = card_token_data { if let Some(cvc) = token_data.card_cvc.clone() { is_card_updated = true; updated_card.card_cvc = cvc; } } // populate additional card details from payment_attempt.payment_method_data (additional_payment_data) if not present in the locker if updated_card.card_issuer.is_none() || updated_card.card_network.is_none() || updated_card.card_type.is_none() || updated_card.card_issuing_country.is_none() { let additional_payment_method_data: Option< api_models::payments::AdditionalPaymentData, > = payment_attempt .payment_method_data .clone() .and_then(|data| match data { serde_json::Value::Null => None, // This is to handle the case when the payment_method_data is null _ => Some(data.parse_value("AdditionalPaymentData")), }) .transpose() .map_err(|err| logger::error!("Failed to parse AdditionalPaymentData {err:?}")) .ok() .flatten(); if let Some(api_models::payments::AdditionalPaymentData::Card(card)) = additional_payment_method_data { is_card_updated = true; updated_card.card_issuer = updated_card.card_issuer.or(card.card_issuer); updated_card.card_network = updated_card.card_network.or(card.card_network); updated_card.card_type = updated_card.card_type.or(card.card_type); updated_card.card_issuing_country = updated_card .card_issuing_country .or(card.card_issuing_country); }; }; if is_card_updated { let updated_pm = domain::PaymentMethodData::Card(updated_card); vault::Vault::store_payment_method_data_in_locker( state, Some(token.to_owned()), &updated_pm, payment_intent.customer_id.to_owned(), enums::PaymentMethod::Card, merchant_key_store, ) .await?; Some((updated_pm, enums::PaymentMethod::Card)) } else { Some(( domain::PaymentMethodData::Card(card), enums::PaymentMethod::Card, )) } } Some(the_pm @ domain::PaymentMethodData::Wallet(_)) => { Some((the_pm, enums::PaymentMethod::Wallet)) } Some(the_pm @ domain::PaymentMethodData::BankTransfer(_)) => { Some((the_pm, enums::PaymentMethod::BankTransfer)) } Some(the_pm @ domain::PaymentMethodData::BankRedirect(_)) => { Some((the_pm, enums::PaymentMethod::BankRedirect)) } Some(the_pm @ domain::PaymentMethodData::BankDebit(_)) => { Some((the_pm, enums::PaymentMethod::BankDebit)) } Some(_) => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Payment method received from locker is unsupported by locker")?, None => None, }) } #[cfg(feature = "v2")] pub async fn retrieve_card_with_permanent_token( state: &SessionState, locker_id: &str, _payment_method_id: &id_type::GlobalPaymentMethodId, payment_intent: &PaymentIntent, card_token_data: Option<&domain::CardToken>, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<domain::PaymentMethodData> { todo!() } pub enum VaultFetchAction { FetchCardDetailsFromLocker, FetchCardDetailsForNetworkTransactionIdFlowFromLocker, FetchNetworkTokenDataFromTokenizationService(String), FetchNetworkTokenDetailsFromLocker(api_models::payments::NetworkTokenWithNTIRef), NoFetchAction, } pub fn decide_payment_method_retrieval_action( is_network_tokenization_enabled: bool, mandate_id: Option<api_models::payments::MandateIds>, connector: Option<api_enums::Connector>, network_tokenization_supported_connectors: &HashSet<api_enums::Connector>, should_retry_with_pan: bool, network_token_requestor_ref_id: Option<String>, ) -> VaultFetchAction { let standard_flow = || { determine_standard_vault_action( is_network_tokenization_enabled, mandate_id, connector, network_tokenization_supported_connectors, network_token_requestor_ref_id, ) }; if should_retry_with_pan { VaultFetchAction::FetchCardDetailsFromLocker } else { standard_flow() } } pub async fn is_ucs_enabled(state: &SessionState, config_key: &str) -> bool { let db = state.store.as_ref(); db.find_config_by_key_unwrap_or(config_key, Some("false".to_string())) .await .inspect_err(|error| { logger::error!( ?error, "Failed to fetch `{config_key}` UCS enabled config from DB" ); }) .ok() .and_then(|config| { config .config .parse::<bool>() .inspect_err(|error| { logger::error!(?error, "Failed to parse `{config_key}` UCS enabled config"); }) .ok() }) .unwrap_or(false) } pub async fn should_execute_based_on_rollout( state: &SessionState, config_key: &str, ) -> RouterResult<bool> { let db = state.store.as_ref(); match db.find_config_by_key(config_key).await { Ok(rollout_config) => match rollout_config.config.parse::<f64>() { Ok(rollout_percent) => { if !(0.0..=1.0).contains(&rollout_percent) { logger::warn!( rollout_percent, "Rollout percent out of bounds. Must be between 0.0 and 1.0" ); return Ok(false); } let sampled_value: f64 = rand::thread_rng().gen_range(0.0..1.0); Ok(sampled_value < rollout_percent) } Err(err) => { logger::error!(error = ?err, "Failed to parse rollout percent"); Ok(false) } }, Err(err) => { logger::error!(error = ?err, "Failed to fetch rollout config from DB"); Ok(false) } } } pub fn determine_standard_vault_action( is_network_tokenization_enabled: bool, mandate_id: Option<api_models::payments::MandateIds>, connector: Option<api_enums::Connector>, network_tokenization_supported_connectors: &HashSet<api_enums::Connector>, network_token_requestor_ref_id: Option<String>, ) -> VaultFetchAction { let is_network_transaction_id_flow = mandate_id .as_ref() .map(|mandate_ids| mandate_ids.is_network_transaction_id_flow()) .unwrap_or(false); if !is_network_tokenization_enabled { if is_network_transaction_id_flow { VaultFetchAction::FetchCardDetailsForNetworkTransactionIdFlowFromLocker } else { VaultFetchAction::FetchCardDetailsFromLocker } } else { match mandate_id { Some(mandate_ids) => match mandate_ids.mandate_reference_id { Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(nt_data)) => { VaultFetchAction::FetchNetworkTokenDetailsFromLocker(nt_data) } Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) => { VaultFetchAction::FetchCardDetailsForNetworkTransactionIdFlowFromLocker } Some(api_models::payments::MandateReferenceId::ConnectorMandateId(_)) | None => { VaultFetchAction::NoFetchAction } }, None => { //saved card flow let is_network_token_supported_connector = connector .map(|conn| network_tokenization_supported_connectors.contains(&conn)) .unwrap_or(false); match ( is_network_token_supported_connector, network_token_requestor_ref_id, ) { (true, Some(ref_id)) => { VaultFetchAction::FetchNetworkTokenDataFromTokenizationService(ref_id) } (false, Some(_)) | (true, None) | (false, None) => { VaultFetchAction::FetchCardDetailsFromLocker } } } } } } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn retrieve_payment_method_data_with_permanent_token( state: &SessionState, locker_id: &str, _payment_method_id: &str, payment_intent: &PaymentIntent, card_token_data: Option<&domain::CardToken>, merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, mandate_id: Option<api_models::payments::MandateIds>, payment_method_info: domain::PaymentMethod, business_profile: &domain::Profile, connector: Option<String>, should_retry_with_pan: bool, vault_data: Option<&domain_payments::VaultData>, ) -> RouterResult<domain::PaymentMethodData> { let customer_id = payment_intent .customer_id .as_ref() .get_required_value("customer_id") .change_context(errors::ApiErrorResponse::UnprocessableEntity { message: "no customer id provided for the payment".to_string(), })?; let network_tokenization_supported_connectors = &state .conf .network_tokenization_supported_connectors .connector_list; let connector_variant = connector .as_ref() .map(|conn| { api_enums::Connector::from_str(conn.as_str()) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "connector", }) .attach_printable_lazy(|| format!("unable to parse connector name {connector:?}")) }) .transpose()?; let vault_fetch_action = decide_payment_method_retrieval_action( business_profile.is_network_tokenization_enabled, mandate_id, connector_variant, network_tokenization_supported_connectors, should_retry_with_pan, payment_method_info .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 .and_then(|vault_data| vault_data.get_card_vault_data()) .map(Ok) .async_unwrap_or_else(|| async { Box::pin(fetch_card_details_from_locker( state, customer_id, &payment_intent.merchant_id, locker_id, card_token_data, co_badged_card_data, payment_method_info, merchant_key_store, )) .await }) .await?; Ok(domain::PaymentMethodData::Card(card)) } VaultFetchAction::FetchCardDetailsForNetworkTransactionIdFlowFromLocker => { fetch_card_details_for_network_transaction_flow_from_locker( state, customer_id, &payment_intent.merchant_id, locker_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch card information from the permanent locker") } VaultFetchAction::FetchNetworkTokenDataFromTokenizationService( network_token_requestor_ref_id, ) => { logger::info!("Fetching network token data from tokenization service"); match network_tokenization::get_token_from_tokenization_service( state, network_token_requestor_ref_id, &payment_method_info, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch network token data from tokenization service") { Ok(network_token_data) => { Ok(domain::PaymentMethodData::NetworkToken(network_token_data)) } Err(err) => { logger::info!( "Failed to fetch network token data from tokenization service {err:?}" ); logger::info!("Falling back to fetch card details from locker"); Ok(domain::PaymentMethodData::Card( vault_data .and_then(|vault_data| vault_data.get_card_vault_data()) .map(Ok) .async_unwrap_or_else(|| async { Box::pin(fetch_card_details_from_locker( state, customer_id, &payment_intent.merchant_id, locker_id, card_token_data, co_badged_card_data, payment_method_info, merchant_key_store, )) .await }) .await?, )) } } } VaultFetchAction::FetchNetworkTokenDetailsFromLocker(nt_data) => { if let Some(network_token_locker_id) = payment_method_info.network_token_locker_id.as_ref() { let network_token_data = vault_data .and_then(|vault_data| vault_data.get_network_token_data()) .map(Ok) .async_unwrap_or_else(|| async { fetch_network_token_details_from_locker( state, customer_id, &payment_intent.merchant_id, network_token_locker_id, nt_data, ) .await }) .await?; Ok(domain::PaymentMethodData::NetworkToken(network_token_data)) } else { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Network token locker id is not present") } } VaultFetchAction::NoFetchAction => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Payment method data is not present"), } } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn retrieve_card_with_permanent_token_for_external_authentication( state: &SessionState, locker_id: &str, payment_intent: &PaymentIntent, card_token_data: Option<&domain::CardToken>, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<domain::PaymentMethodData> { let customer_id = payment_intent .customer_id .as_ref() .get_required_value("customer_id") .change_context(errors::ApiErrorResponse::UnprocessableEntity { message: "no customer id provided for the payment".to_string(), })?; Ok(domain::PaymentMethodData::Card( fetch_card_details_from_internal_locker( state, customer_id, &payment_intent.merchant_id, locker_id, card_token_data, None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch card information from the permanent locker")?, )) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn fetch_card_details_from_locker( state: &SessionState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, locker_id: &str, card_token_data: Option<&domain::CardToken>, co_badged_card_data: Option<api_models::payment_methods::CoBadgedCardData>, payment_method_info: domain::PaymentMethod, merchant_key_store: &domain::MerchantKeyStore, ) -> RouterResult<domain::Card> { match &payment_method_info.vault_source_details.clone() { domain::PaymentMethodVaultSourceDetails::ExternalVault { ref external_vault_source, } => { fetch_card_details_from_external_vault( state, merchant_id, card_token_data, co_badged_card_data, payment_method_info, merchant_key_store, external_vault_source, ) .await } domain::PaymentMethodVaultSourceDetails::InternalVault => { fetch_card_details_from_internal_locker( state, customer_id, merchant_id, locker_id, card_token_data, co_badged_card_data, ) .await } } } #[cfg(feature = "v1")] pub async fn fetch_card_details_from_internal_locker( state: &SessionState, customer_id: &id_type::CustomerId, 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) .attach_printable("failed to fetch card information from the permanent locker")?; // The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked // from payment_method_data.card_token object let name_on_card = if let Some(name) = card.name_on_card.clone() { if name.clone().expose().is_empty() { card_token_data .and_then(|token_data| token_data.card_holder_name.clone()) .or(Some(name)) } else { card.name_on_card } } else { card_token_data.and_then(|token_data| token_data.card_holder_name.clone()) }; let api_card = api::Card { card_number: card.card_number, card_holder_name: name_on_card, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_cvc: card_token_data .cloned() .unwrap_or_default() .card_cvc .unwrap_or_default(), card_issuer: None, nick_name: card.nick_name.map(masking::Secret::new), card_network: card .card_brand .map(|card_brand| enums::CardNetwork::from_str(&card_brand)) .transpose() .map_err(|e| { logger::error!("Failed to parse card network {e:?}"); }) .ok() .flatten(), card_type: None, card_issuing_country: None, bank_code: None, }; Ok(domain::Card::from((api_card, co_badged_card_data))) } #[cfg(feature = "v1")] pub async fn fetch_card_details_from_external_vault( state: &SessionState, merchant_id: &id_type::MerchantId, card_token_data: Option<&domain::CardToken>, co_badged_card_data: Option<api_models::payment_methods::CoBadgedCardData>, payment_method_info: domain::PaymentMethod, merchant_key_store: &domain::MerchantKeyStore, external_vault_mca_id: &id_type::MerchantConnectorAccountId, ) -> RouterResult<domain::Card> { let key_manager_state = &state.into(); let merchant_connector_account_details = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_id, external_vault_mca_id, merchant_key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: external_vault_mca_id.get_string_repr().to_string(), })?; let vault_resp = vault::retrieve_payment_method_from_vault_external_v1( state, merchant_id, &payment_method_info, merchant_connector_account_details, ) .await?; let payment_methods_data = payment_method_info.get_payment_methods_data(); match vault_resp { hyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(card) => Ok( domain::Card::from((card, card_token_data, co_badged_card_data)), ), hyperswitch_domain_models::vault::PaymentMethodVaultingData::CardNumber(card_number) => { let payment_methods_data = payment_methods_data .get_required_value("PaymentMethodsData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Payment methods data not present")?; let card = payment_methods_data .get_card_details() .get_required_value("CardDetails") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Card details not present")?; Ok( domain::Card::try_from((card_number, card_token_data, co_badged_card_data, card)) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to generate card data")?, ) } } } #[cfg(feature = "v1")] pub async fn fetch_network_token_details_from_locker( state: &SessionState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, network_token_locker_id: &str, network_transaction_data: api_models::payments::NetworkTokenWithNTIRef, ) -> RouterResult<domain::NetworkTokenData> { let mut token_data = cards::get_card_from_locker(state, customer_id, merchant_id, network_token_locker_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "failed to fetch network token information from the permanent locker", )?; let expiry = network_transaction_data .token_exp_month .zip(network_transaction_data.token_exp_year); if let Some((exp_month, exp_year)) = expiry { token_data.card_exp_month = exp_month; token_data.card_exp_year = exp_year; } let card_network = token_data .card_brand .map(|card_brand| enums::CardNetwork::from_str(&card_brand)) .transpose() .map_err(|e| { logger::error!("Failed to parse card network {e:?}"); }) .ok() .flatten(); let network_token_data = domain::NetworkTokenData { token_number: token_data.card_number, token_cryptogram: None, token_exp_month: token_data.card_exp_month, token_exp_year: token_data.card_exp_year, nick_name: token_data.nick_name.map(masking::Secret::new), card_issuer: None, card_network, card_type: None, card_issuing_country: None, bank_code: None, eci: None, }; Ok(network_token_data) } #[cfg(feature = "v1")] pub async fn fetch_card_details_for_network_transaction_flow_from_locker( state: &SessionState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, locker_id: &str, ) -> RouterResult<domain::PaymentMethodData> { let card_details_from_locker = cards::get_card_from_locker(state, customer_id, merchant_id, locker_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch card details from locker")?; let card_network = card_details_from_locker .card_brand .map(|card_brand| enums::CardNetwork::from_str(&card_brand)) .transpose() .map_err(|e| { logger::error!("Failed to parse card network {e:?}"); }) .ok() .flatten(); let card_details_for_network_transaction_id = hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId { card_number: card_details_from_locker.card_number, card_exp_month: card_details_from_locker.card_exp_month, card_exp_year: card_details_from_locker.card_exp_year, card_issuer: None, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name: card_details_from_locker.nick_name.map(masking::Secret::new), card_holder_name: card_details_from_locker.name_on_card.clone(), }; Ok( domain::PaymentMethodData::CardDetailsForNetworkTransactionId( card_details_for_network_transaction_id, ), ) } #[cfg(feature = "v2")] pub async fn retrieve_payment_method_from_db_with_token_data( state: &SessionState, merchant_key_store: &domain::MerchantKeyStore, token_data: &storage::PaymentTokenData, storage_scheme: storage::enums::MerchantStorageScheme, ) -> RouterResult<Option<domain::PaymentMethod>> { todo!() } #[cfg(feature = "v1")] pub async fn retrieve_payment_method_from_db_with_token_data( state: &SessionState, merchant_key_store: &domain::MerchantKeyStore, token_data: &storage::PaymentTokenData, storage_scheme: storage::enums::MerchantStorageScheme, ) -> RouterResult<Option<domain::PaymentMethod>> { match token_data { storage::PaymentTokenData::PermanentCard(data) => { if let Some(ref payment_method_id) = data.payment_method_id { state .store .find_payment_method( &(state.into()), merchant_key_store, payment_method_id, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) .attach_printable("error retrieving payment method from DB") .map(Some) } else { Ok(None) } } storage::PaymentTokenData::WalletToken(data) => state .store .find_payment_method( &(state.into()), merchant_key_store, &data.payment_method_id, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) .attach_printable("error retrieveing payment method from DB") .map(Some), storage::PaymentTokenData::Temporary(_) | storage::PaymentTokenData::TemporaryGeneric(_) | storage::PaymentTokenData::Permanent(_) | storage::PaymentTokenData::AuthBankDebit(_) => Ok(None), } } #[cfg(feature = "v1")] pub async fn retrieve_payment_token_data( state: &SessionState, token: String, payment_method: Option<storage_enums::PaymentMethod>, ) -> 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")? ); 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(), }, ))?; let token_data_result = token_data_string .clone() .parse_struct("PaymentTokenData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to deserialize hyperswitch token data"); let token_data = match token_data_result { Ok(data) => data, Err(e) => { // The purpose of this logic is backwards compatibility to support tokens // in redis that might be following the old format. if token_data_string.starts_with('{') { return Err(e); } else { storage::PaymentTokenData::temporary_generic(token_data_string) } } }; Ok(token_data) } #[cfg(feature = "v2")] pub async fn make_pm_data<'a, F: Clone, R, D>( _operation: BoxedOperation<'a, F, R, D>, _state: &'a SessionState, _payment_data: &mut PaymentData<F>, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _storage_scheme: common_enums::enums::MerchantStorageScheme, _business_profile: Option<&domain::Profile>, ) -> RouterResult<( BoxedOperation<'a, F, R, D>, Option<domain::PaymentMethodData>, Option<String>, )> { todo!() } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn make_pm_data<'a, F: Clone, R, D>( operation: BoxedOperation<'a, F, R, D>, state: &'a SessionState, payment_data: &mut PaymentData<F>, merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, storage_scheme: common_enums::enums::MerchantStorageScheme, business_profile: &domain::Profile, should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, R, D>, Option<domain::PaymentMethodData>, Option<String>, )> { use super::OperationSessionSetters; use crate::core::payments::OperationSessionGetters; let request = payment_data.payment_method_data.clone(); let mut card_token_data = payment_data .payment_method_data .clone() .and_then(|pmd| match pmd { domain::PaymentMethodData::CardToken(token_data) => Some(token_data), _ => None, }) .or(Some(domain::CardToken::default())); if let Some(cvc) = payment_data.card_cvc.clone() { if let Some(token_data) = card_token_data.as_mut() { token_data.card_cvc = Some(cvc); } } if payment_data.token_data.is_none() { if let Some(payment_method_info) = &payment_data.payment_method_info { if payment_method_info.get_payment_method_type() == Some(storage_enums::PaymentMethod::Card) { payment_data.token_data = Some(storage::PaymentTokenData::PermanentCard(CardTokenData { payment_method_id: Some(payment_method_info.get_id().clone()), locker_id: payment_method_info .locker_id .clone() .or(Some(payment_method_info.get_id().clone())), token: payment_method_info .locker_id .clone() .unwrap_or(payment_method_info.get_id().clone()), network_token_locker_id: payment_method_info .network_token_requestor_reference_id .clone() .or(Some(payment_method_info.get_id().clone())), })); } } } let mandate_id = payment_data.mandate_id.clone(); // TODO: Handle case where payment method and token both are present in request properly. let (payment_method, pm_id) = match (&request, payment_data.token_data.as_ref()) { (_, Some(hyperswitch_token)) => { let existing_vault_data = payment_data.get_vault_operation(); let vault_data = existing_vault_data.and_then(|data| match data { domain_payments::VaultOperation::ExistingVaultData(vault_data) => Some(vault_data), domain_payments::VaultOperation::SaveCardData(_) | domain_payments::VaultOperation::SaveCardAndNetworkTokenData(_) => None, }); let pm_data = Box::pin(payment_methods::retrieve_payment_method_with_token( state, merchant_key_store, hyperswitch_token, &payment_data.payment_intent, &payment_data.payment_attempt, card_token_data.as_ref(), customer, storage_scheme, mandate_id, payment_data.payment_method_info.clone(), business_profile, should_retry_with_pan, vault_data, )) .await; let payment_method_details = pm_data.attach_printable("in 'make_pm_data'")?; if let Some(ref payment_method_data) = payment_method_details.payment_method_data { let updated_vault_operation = domain_payments::VaultOperation::get_updated_vault_data( existing_vault_data, payment_method_data, ); if let Some(vault_operation) = updated_vault_operation { payment_data.set_vault_operation(vault_operation); } // Temporarily store payment method data along with the cvc in redis for saved card payments, if required by the connector based on its configs if payment_data.token.is_none() { let (_, payment_token) = payment_methods::retrieve_payment_method_core( &Some(payment_method_data.clone()), state, &payment_data.payment_intent, &payment_data.payment_attempt, merchant_key_store, Some(business_profile), ) .await?; payment_data.token = payment_token; } }; Ok::<_, error_stack::Report<errors::ApiErrorResponse>>( if let Some(payment_method_data) = payment_method_details.payment_method_data { payment_data.payment_attempt.payment_method = payment_method_details.payment_method; ( Some(payment_method_data), payment_method_details.payment_method_id, ) } else { (None, payment_method_details.payment_method_id) }, ) } (Some(_), _) => { let (payment_method_data, payment_token) = payment_methods::retrieve_payment_method_core( &request, state, &payment_data.payment_intent, &payment_data.payment_attempt, merchant_key_store, Some(business_profile), ) .await?; payment_data.token = payment_token; Ok((payment_method_data, None)) } _ => Ok((None, None)), }?; Ok((operation, payment_method, pm_id)) } #[cfg(feature = "v1")] pub async fn store_in_vault_and_generate_ppmt( state: &SessionState, payment_method_data: &domain::PaymentMethodData, payment_intent: &PaymentIntent, payment_attempt: &PaymentAttempt, payment_method: enums::PaymentMethod, merchant_key_store: &domain::MerchantKeyStore, business_profile: Option<&domain::Profile>, ) -> RouterResult<String> { let router_token = vault::Vault::store_payment_method_data_in_locker( state, None, payment_method_data, payment_intent.customer_id.to_owned(), payment_method, merchant_key_store, ) .await?; let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token"); let key_for_hyperswitch_token = payment_attempt.get_payment_method().map(|payment_method| { payment_methods_handler::ParentPaymentMethodToken::create_key_for_token(( &parent_payment_method_token, payment_method, )) }); let intent_fulfillment_time = business_profile .and_then(|b_profile| b_profile.get_order_fulfillment_time()) .unwrap_or(consts::DEFAULT_FULFILLMENT_TIME); if let Some(key_for_hyperswitch_token) = key_for_hyperswitch_token { key_for_hyperswitch_token .insert( intent_fulfillment_time, storage::PaymentTokenData::temporary_generic(router_token), state, ) .await?; }; Ok(parent_payment_method_token) } #[cfg(feature = "v2")] pub async fn store_payment_method_data_in_vault( state: &SessionState, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, payment_method: enums::PaymentMethod, payment_method_data: &domain::PaymentMethodData, merchant_key_store: &domain::MerchantKeyStore, business_profile: Option<&domain::Profile>, ) -> RouterResult<Option<String>> { todo!() } #[cfg(feature = "v1")] pub async fn store_payment_method_data_in_vault( state: &SessionState, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, payment_method: enums::PaymentMethod, payment_method_data: &domain::PaymentMethodData, merchant_key_store: &domain::MerchantKeyStore, business_profile: Option<&domain::Profile>, ) -> RouterResult<Option<String>> { if should_store_payment_method_data_in_vault( &state.conf.temp_locker_enable_config, payment_attempt.connector.clone(), payment_method, ) || payment_intent.request_external_three_ds_authentication == Some(true) { let parent_payment_method_token = store_in_vault_and_generate_ppmt( state, payment_method_data, payment_intent, payment_attempt, payment_method, merchant_key_store, business_profile, ) .await?; return Ok(Some(parent_payment_method_token)); } Ok(None) } pub fn should_store_payment_method_data_in_vault( temp_locker_enable_config: &TempLockerEnableConfig, option_connector: Option<String>, payment_method: enums::PaymentMethod, ) -> bool { option_connector .map(|connector| { temp_locker_enable_config .0 .get(&connector) .map(|config| config.payment_method.contains(&payment_method)) .unwrap_or(false) }) .unwrap_or(true) } #[instrument(skip_all)] pub(crate) fn validate_capture_method( capture_method: storage_enums::CaptureMethod, ) -> RouterResult<()> { utils::when( capture_method == storage_enums::CaptureMethod::Automatic, || { Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState { field_name: "capture_method".to_string(), current_flow: "captured".to_string(), current_value: capture_method.to_string(), states: "manual, manual_multiple, scheduled".to_string() })) }, ) } #[instrument(skip_all)] pub(crate) fn validate_status_with_capture_method( status: storage_enums::IntentStatus, capture_method: storage_enums::CaptureMethod, ) -> RouterResult<()> { if status == storage_enums::IntentStatus::Processing && !(capture_method == storage_enums::CaptureMethod::ManualMultiple) { return Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState { field_name: "capture_method".to_string(), current_flow: "captured".to_string(), current_value: capture_method.to_string(), states: "manual_multiple".to_string() })); } utils::when( status != storage_enums::IntentStatus::RequiresCapture && status != storage_enums::IntentStatus::PartiallyCapturedAndCapturable && status != storage_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture && status != storage_enums::IntentStatus::Processing, || { Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState { field_name: "payment.status".to_string(), current_flow: "captured".to_string(), current_value: status.to_string(), states: "requires_capture, partially_captured_and_capturable, processing" .to_string() })) }, ) } #[instrument(skip_all)] pub(crate) fn validate_amount_to_capture( amount: i64, amount_to_capture: Option<i64>, ) -> RouterResult<()> { utils::when(amount_to_capture.is_some_and(|value| value <= 0), || { Err(report!(errors::ApiErrorResponse::InvalidDataFormat { field_name: "amount".to_string(), expected_format: "positive integer".to_string(), })) })?; utils::when( amount_to_capture.is_some() && (Some(amount) < amount_to_capture), || { Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "amount_to_capture is greater than amount".to_string() })) }, ) } #[cfg(feature = "v1")] #[instrument(skip_all)] pub(crate) fn validate_payment_method_fields_present( req: &api_models::payments::PaymentsRequest, ) -> RouterResult<()> { let payment_method_data = req.payment_method_data .as_ref() .and_then(|request_payment_method_data| { request_payment_method_data.payment_method_data.as_ref() }); utils::when( req.payment_method.is_none() && payment_method_data.is_some(), || { Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "payment_method", }) }, )?; utils::when( !matches!( req.payment_method, Some(api_enums::PaymentMethod::Card) | None ) && (req.payment_method_type.is_none()), || { Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "payment_method_type", }) }, )?; utils::when( req.payment_method.is_some() && payment_method_data.is_none() && req.payment_token.is_none() && req.recurring_details.is_none() && req.ctp_service_details.is_none(), || { Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "payment_method_data", }) }, )?; utils::when( req.payment_method.is_some() && req.payment_method_type.is_some(), || { req.payment_method .map_or(Ok(()), |req_payment_method| { req.payment_method_type.map_or(Ok(()), |req_payment_method_type| { if !validate_payment_method_type_against_payment_method(req_payment_method, req_payment_method_type) { Err(errors::ApiErrorResponse::InvalidRequestData { message: ("payment_method_type doesn't correspond to the specified payment_method" .to_string()), }) } else { Ok(()) } }) }) }, )?; let validate_payment_method_and_payment_method_data = |req_payment_method_data, req_payment_method: api_enums::PaymentMethod| { api_enums::PaymentMethod::foreign_try_from(req_payment_method_data).and_then(|payment_method| if req_payment_method != payment_method { Err(errors::ApiErrorResponse::InvalidRequestData { message: ("payment_method_data doesn't correspond to the specified payment_method" .to_string()), }) } else { Ok(()) }) }; utils::when( req.payment_method.is_some() && payment_method_data.is_some(), || { payment_method_data .cloned() .map_or(Ok(()), |payment_method_data| { req.payment_method.map_or(Ok(()), |req_payment_method| { validate_payment_method_and_payment_method_data( payment_method_data, req_payment_method, ) }) }) }, )?; Ok(()) } pub fn check_force_psync_precondition(status: storage_enums::AttemptStatus) -> bool { !matches!( status, storage_enums::AttemptStatus::Charged | storage_enums::AttemptStatus::AutoRefunded | storage_enums::AttemptStatus::Voided | storage_enums::AttemptStatus::CodInitiated | storage_enums::AttemptStatus::Started | storage_enums::AttemptStatus::Failure ) } pub fn append_option<T, U, F, V>(func: F, option1: Option<T>, option2: Option<U>) -> Option<V> where F: FnOnce(T, U) -> V, { Some(func(option1?, option2?)) } #[cfg(all(feature = "olap", feature = "v1"))] pub(super) async fn filter_by_constraints( state: &SessionState, constraints: &PaymentIntentFetchConstraints, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Vec<PaymentIntent>, errors::StorageError> { let db = &*state.store; let result = db .filter_payment_intent_by_constraints( &(state).into(), merchant_id, constraints, key_store, storage_scheme, ) .await?; Ok(result) } #[cfg(feature = "olap")] pub(super) fn validate_payment_list_request( req: &api::PaymentListConstraints, ) -> CustomResult<(), errors::ApiErrorResponse> { use common_utils::consts::PAYMENTS_LIST_MAX_LIMIT_V1; utils::when( req.limit > PAYMENTS_LIST_MAX_LIMIT_V1 || req.limit < 1, || { Err(errors::ApiErrorResponse::InvalidRequestData { message: format!("limit should be in between 1 and {PAYMENTS_LIST_MAX_LIMIT_V1}"), }) }, )?; Ok(()) } #[cfg(feature = "olap")] pub(super) fn validate_payment_list_request_for_joins( limit: u32, ) -> CustomResult<(), errors::ApiErrorResponse> { use common_utils::consts::PAYMENTS_LIST_MAX_LIMIT_V2; utils::when(!(1..=PAYMENTS_LIST_MAX_LIMIT_V2).contains(&limit), || { Err(errors::ApiErrorResponse::InvalidRequestData { message: format!("limit should be in between 1 and {PAYMENTS_LIST_MAX_LIMIT_V2}"), }) })?; Ok(()) } #[cfg(feature = "v1")] pub fn get_handle_response_url( payment_id: id_type::PaymentId, business_profile: &domain::Profile, response: &api::PaymentsResponse, connector: String, ) -> RouterResult<api::RedirectionResponse> { let payments_return_url = response.return_url.as_ref(); let redirection_response = make_pg_redirect_response(payment_id, response, connector); let return_url = make_merchant_url_with_response( business_profile, redirection_response, payments_return_url, response.client_secret.as_ref(), response.manual_retry_allowed, ) .attach_printable("Failed to make merchant url with response")?; make_url_with_signature(&return_url, business_profile) } #[cfg(feature = "v1")] pub fn get_handle_response_url_for_modular_authentication( authentication_id: id_type::AuthenticationId, business_profile: &domain::Profile, response: &api_models::authentication::AuthenticationAuthenticateResponse, connector: String, return_url: Option<String>, client_secret: Option<&masking::Secret<String>>, amount: Option<MinorUnit>, ) -> RouterResult<api::RedirectionResponse> { let authentication_return_url = return_url; let trans_status = response .transaction_status .clone() .get_required_value("transaction_status")?; let redirection_response = make_pg_redirect_response_for_authentication( authentication_id, connector, amount, trans_status, ); let return_url = make_merchant_url_with_response_for_authentication( business_profile, redirection_response, authentication_return_url.as_ref(), client_secret, None, ) .attach_printable("Failed to make merchant url with response")?; make_url_with_signature(&return_url, business_profile) } #[cfg(feature = "v1")] pub fn make_merchant_url_with_response_for_authentication( business_profile: &domain::Profile, redirection_response: hyperswitch_domain_models::authentication::PgRedirectResponseForAuthentication, request_return_url: Option<&String>, client_secret: Option<&masking::Secret<String>>, manual_retry_allowed: Option<bool>, ) -> RouterResult<String> { // take return url if provided in the request else use merchant return url let url = request_return_url .or(business_profile.return_url.as_ref()) .get_required_value("return_url")?; let status_check = redirection_response.status; let authentication_client_secret = client_secret .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Expected client secret to be `Some`")?; let authentication_id = redirection_response .authentication_id .get_string_repr() .to_owned(); let merchant_url_with_response = if business_profile.redirect_to_merchant_with_http_post { url::Url::parse_with_params( url, &[ ("status", status_check.to_string()), ("authentication_id", authentication_id), ( "authentication_client_secret", authentication_client_secret.peek().to_string(), ), ( "manual_retry_allowed", manual_retry_allowed.unwrap_or(false).to_string(), ), ], ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse the url with param")? } else { let amount = redirection_response.amount.get_required_value("amount")?; url::Url::parse_with_params( url, &[ ("status", status_check.to_string()), ("authentication_id", authentication_id), ( "authentication_client_secret", authentication_client_secret.peek().to_string(), ), ("amount", amount.to_string()), ( "manual_retry_allowed", manual_retry_allowed.unwrap_or(false).to_string(), ), ], ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse the url with param")? }; Ok(merchant_url_with_response.to_string()) } #[cfg(feature = "v1")] pub fn make_merchant_url_with_response( business_profile: &domain::Profile, redirection_response: api::PgRedirectResponse, request_return_url: Option<&String>, client_secret: Option<&masking::Secret<String>>, manual_retry_allowed: Option<bool>, ) -> RouterResult<String> { // take return url if provided in the request else use merchant return url let url = request_return_url .or(business_profile.return_url.as_ref()) .get_required_value("return_url")?; let status_check = redirection_response.status; let payment_client_secret = client_secret .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Expected client secret to be `Some`")?; let payment_id = redirection_response.payment_id.get_string_repr().to_owned(); let merchant_url_with_response = if business_profile.redirect_to_merchant_with_http_post { url::Url::parse_with_params( url, &[ ("status", status_check.to_string()), ("payment_id", payment_id), ( "payment_intent_client_secret", payment_client_secret.peek().to_string(), ), ( "manual_retry_allowed", manual_retry_allowed.unwrap_or(false).to_string(), ), ], ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse the url with param")? } else { let amount = redirection_response.amount.get_required_value("amount")?; url::Url::parse_with_params( url, &[ ("status", status_check.to_string()), ("payment_id", payment_id), ( "payment_intent_client_secret", payment_client_secret.peek().to_string(), ), ("amount", amount.to_string()), ( "manual_retry_allowed", manual_retry_allowed.unwrap_or(false).to_string(), ), ], ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse the url with param")? }; Ok(merchant_url_with_response.to_string()) } #[cfg(feature = "v1")] pub async fn make_ephemeral_key( state: SessionState, customer_id: id_type::CustomerId, merchant_id: id_type::MerchantId, ) -> errors::RouterResponse<ephemeral_key::EphemeralKey> { let store = &state.store; let id = utils::generate_id(consts::ID_LENGTH, "eki"); let secret = format!("epk_{}", &Uuid::new_v4().simple().to_string()); let ek = ephemeral_key::EphemeralKeyNew { id, customer_id, merchant_id: merchant_id.to_owned(), secret, }; let ek = store .create_ephemeral_key(ek, state.conf.eph_key.validity) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to create ephemeral key")?; Ok(services::ApplicationResponse::Json(ek)) } #[cfg(feature = "v2")] pub async fn make_client_secret( state: SessionState, resource_id: api_models::ephemeral_key::ResourceId, merchant_context: domain::MerchantContext, headers: &actix_web::http::header::HeaderMap, ) -> errors::RouterResponse<ClientSecretResponse> { let db = &state.store; let key_manager_state = &((&state).into()); match &resource_id { api_models::ephemeral_key::ResourceId::Customer(global_customer_id) => { db.find_customer_by_global_id( key_manager_state, global_customer_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; } } let resource_id = match resource_id { api_models::ephemeral_key::ResourceId::Customer(global_customer_id) => { common_utils::types::authentication::ResourceId::Customer(global_customer_id) } }; let client_secret = create_client_secret( &state, merchant_context.get_merchant_account().get_id(), resource_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to create client secret")?; let response = ClientSecretResponse::foreign_try_from(client_secret) .attach_printable("Only customer is supported as resource_id in response")?; Ok(services::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] pub async fn create_client_secret( state: &SessionState, merchant_id: &id_type::MerchantId, resource_id: common_utils::types::authentication::ResourceId, ) -> RouterResult<ephemeral_key::ClientSecretType> { use common_utils::generate_time_ordered_id; let store = &state.store; let id = id_type::ClientSecretId::generate(); let secret = masking::Secret::new(generate_time_ordered_id("cs")); let client_secret = ephemeral_key::ClientSecretTypeNew { id, merchant_id: merchant_id.to_owned(), secret, resource_id, }; let client_secret = store .create_client_secret(client_secret, state.conf.eph_key.validity) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to create client secret")?; Ok(client_secret) } #[cfg(feature = "v1")] pub async fn delete_ephemeral_key( state: SessionState, ek_id: String, ) -> errors::RouterResponse<ephemeral_key::EphemeralKey> { let db = state.store.as_ref(); let ek = db .delete_ephemeral_key(&ek_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to delete ephemeral key")?; Ok(services::ApplicationResponse::Json(ek)) } #[cfg(feature = "v2")] pub async fn delete_client_secret( state: SessionState, ephemeral_key_id: String, ) -> errors::RouterResponse<ClientSecretResponse> { let db = state.store.as_ref(); let ephemeral_key = db .delete_client_secret(&ephemeral_key_id) .await .map_err(|err| match err.current_context() { errors::StorageError::ValueNotFound(_) => { err.change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "Ephemeral Key not found".to_string(), }) } _ => err.change_context(errors::ApiErrorResponse::InternalServerError), }) .attach_printable("Unable to delete ephemeral key")?; let response = ClientSecretResponse::foreign_try_from(ephemeral_key) .attach_printable("Only customer is supported as resource_id in response")?; Ok(services::ApplicationResponse::Json(response)) } #[cfg(feature = "v1")] pub fn make_pg_redirect_response( payment_id: id_type::PaymentId, response: &api::PaymentsResponse, connector: String, ) -> api::PgRedirectResponse { api::PgRedirectResponse { payment_id, status: response.status, gateway_id: connector, customer_id: response.customer_id.to_owned(), amount: Some(response.amount), } } #[cfg(feature = "v1")] pub fn make_pg_redirect_response_for_authentication( authentication_id: id_type::AuthenticationId, connector: String, amount: Option<MinorUnit>, trans_status: common_enums::TransactionStatus, ) -> hyperswitch_domain_models::authentication::PgRedirectResponseForAuthentication { hyperswitch_domain_models::authentication::PgRedirectResponseForAuthentication { authentication_id, status: trans_status, gateway_id: connector, customer_id: None, amount, } } #[cfg(feature = "v1")] pub fn make_url_with_signature( redirect_url: &str, business_profile: &domain::Profile, ) -> RouterResult<api::RedirectionResponse> { let mut url = url::Url::parse(redirect_url) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse the url")?; let mut base_url = url.clone(); base_url.query_pairs_mut().clear(); let url = if business_profile.enable_payment_response_hash { let key = business_profile .payment_response_hash_key .as_ref() .get_required_value("payment_response_hash_key")?; let signature = hmac_sha512_sorted_query_params( &mut url.query_pairs().collect::<Vec<_>>(), key.as_str(), )?; url.query_pairs_mut() .append_pair("signature", &signature) .append_pair("signature_algorithm", "HMAC-SHA512"); url.to_owned() } else { url.to_owned() }; let parameters = url .query_pairs() .collect::<Vec<_>>() .iter() .map(|(key, value)| (key.clone().into_owned(), value.clone().into_owned())) .collect::<Vec<_>>(); Ok(api::RedirectionResponse { return_url: base_url.to_string(), params: parameters, return_url_with_query_params: url.to_string(), http_method: if business_profile.redirect_to_merchant_with_http_post { services::Method::Post.to_string() } else { services::Method::Get.to_string() }, headers: Vec::new(), }) } pub fn hmac_sha512_sorted_query_params( params: &mut [(Cow<'_, str>, Cow<'_, str>)], key: &str, ) -> RouterResult<String> { params.sort(); let final_string = params .iter() .map(|(key, value)| format!("{key}={value}")) .collect::<Vec<_>>() .join("&"); let signature = crypto::HmacSha512::sign_message( &crypto::HmacSha512, key.as_bytes(), final_string.as_bytes(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to sign the message")?; Ok(hex::encode(signature)) } pub fn check_if_operation_confirm<Op: std::fmt::Debug>(operations: Op) -> bool { format!("{operations:?}") == "PaymentConfirm" } #[allow(clippy::too_many_arguments)] pub fn generate_mandate( merchant_id: id_type::MerchantId, payment_id: id_type::PaymentId, connector: String, setup_mandate_details: Option<MandateData>, customer_id: &Option<id_type::CustomerId>, payment_method_id: String, connector_mandate_id: Option<pii::SecretSerdeValue>, network_txn_id: Option<String>, payment_method_data_option: Option<domain::payments::PaymentMethodData>, mandate_reference: Option<MandateReference>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ) -> CustomResult<Option<storage::MandateNew>, errors::ApiErrorResponse> { match (setup_mandate_details, customer_id) { (Some(data), Some(cus_id)) => { let mandate_id = utils::generate_id(consts::ID_LENGTH, "man"); // The construction of the mandate new must be visible let mut new_mandate = storage::MandateNew::default(); let customer_acceptance = data .customer_acceptance .get_required_value("customer_acceptance")?; new_mandate .set_mandate_id(mandate_id) .set_customer_id(cus_id.clone()) .set_merchant_id(merchant_id) .set_original_payment_id(Some(payment_id)) .set_payment_method_id(payment_method_id) .set_connector(connector) .set_mandate_status(storage_enums::MandateStatus::Active) .set_connector_mandate_ids(connector_mandate_id) .set_network_transaction_id(network_txn_id) .set_customer_ip_address( customer_acceptance .get_ip_address() .map(masking::Secret::new), ) .set_customer_user_agent_extended(customer_acceptance.get_user_agent()) .set_customer_accepted_at(Some(customer_acceptance.get_accepted_at())) .set_metadata(payment_method_data_option.map(|payment_method_data| { pii::SecretSerdeValue::new( serde_json::to_value(payment_method_data).unwrap_or_default(), ) })) .set_connector_mandate_id( mandate_reference.and_then(|reference| reference.connector_mandate_id), ) .set_merchant_connector_id(merchant_connector_id); Ok(Some( match data.mandate_type.get_required_value("mandate_type")? { hyperswitch_domain_models::mandates::MandateDataType::SingleUse(data) => { new_mandate .set_mandate_amount(Some(data.amount.get_amount_as_i64())) .set_mandate_currency(Some(data.currency)) .set_mandate_type(storage_enums::MandateType::SingleUse) .to_owned() } hyperswitch_domain_models::mandates::MandateDataType::MultiUse(op_data) => { match op_data { Some(data) => new_mandate .set_mandate_amount(Some(data.amount.get_amount_as_i64())) .set_mandate_currency(Some(data.currency)) .set_start_date(data.start_date) .set_end_date(data.end_date), // .set_metadata(data.metadata), // we are storing PaymentMethodData in metadata of mandate None => &mut new_mandate, } .set_mandate_type(storage_enums::MandateType::MultiUse) .to_owned() } }, )) } (_, _) => Ok(None), } } #[cfg(feature = "v1")] // A function to manually authenticate the client secret with intent fulfillment time pub fn authenticate_client_secret( request_client_secret: Option<&String>, payment_intent: &PaymentIntent, ) -> Result<(), errors::ApiErrorResponse> { match (request_client_secret, &payment_intent.client_secret) { (Some(req_cs), Some(pi_cs)) => { if req_cs != pi_cs { Err(errors::ApiErrorResponse::ClientSecretInvalid) } else { let current_timestamp = common_utils::date_time::now(); let session_expiry = payment_intent.session_expiry.unwrap_or( payment_intent .created_at .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)), ); fp_utils::when(current_timestamp > session_expiry, || { Err(errors::ApiErrorResponse::ClientSecretExpired) }) } } // If there is no client in payment intent, then it has expired (Some(_), None) => Err(errors::ApiErrorResponse::ClientSecretExpired), _ => Ok(()), } } pub(crate) fn validate_payment_status_against_allowed_statuses( intent_status: storage_enums::IntentStatus, allowed_statuses: &[storage_enums::IntentStatus], action: &'static str, ) -> Result<(), errors::ApiErrorResponse> { fp_utils::when(!allowed_statuses.contains(&intent_status), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: format!( "You cannot {action} this payment because it has status {intent_status}", ), }) }) } pub(crate) fn validate_payment_status_against_not_allowed_statuses( intent_status: storage_enums::IntentStatus, not_allowed_statuses: &[storage_enums::IntentStatus], action: &'static str, ) -> Result<(), errors::ApiErrorResponse> { fp_utils::when(not_allowed_statuses.contains(&intent_status), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: format!( "You cannot {action} this payment because it has status {intent_status}", ), }) }) } #[instrument(skip_all)] pub(crate) fn validate_pm_or_token_given( payment_method: &Option<api_enums::PaymentMethod>, payment_method_data: &Option<api::PaymentMethodData>, payment_method_type: &Option<api_enums::PaymentMethodType>, mandate_type: &Option<api::MandateTransactionType>, token: &Option<String>, ctp_service_details: &Option<api_models::payments::CtpServiceDetails>, ) -> Result<(), errors::ApiErrorResponse> { utils::when( !matches!( payment_method_type, Some(api_enums::PaymentMethodType::Paypal) ) && !matches!( mandate_type, Some(api::MandateTransactionType::RecurringMandateTransaction) ) && token.is_none() && (payment_method_data.is_none() || payment_method.is_none()) && ctp_service_details.is_none(), || { Err(errors::ApiErrorResponse::InvalidRequestData { message: "A payment token or payment method data or ctp service details is required" .to_string(), }) }, ) } #[cfg(feature = "v2")] // A function to perform database lookup and then verify the client secret pub async fn verify_payment_intent_time_and_client_secret( state: &SessionState, merchant_context: &domain::MerchantContext, client_secret: Option<String>, ) -> error_stack::Result<Option<PaymentIntent>, errors::ApiErrorResponse> { todo!() } #[cfg(feature = "v1")] // A function to perform database lookup and then verify the client secret pub async fn verify_payment_intent_time_and_client_secret( state: &SessionState, merchant_context: &domain::MerchantContext, client_secret: Option<String>, ) -> error_stack::Result<Option<PaymentIntent>, errors::ApiErrorResponse> { let db = &*state.store; client_secret .async_map(|cs| async move { let payment_id = get_payment_id_from_client_secret(&cs)?; let payment_id = id_type::PaymentId::wrap(payment_id).change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "payment_id", }, )?; #[cfg(feature = "v1")] let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &state.into(), &payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; #[cfg(feature = "v2")] let payment_intent = db .find_payment_intent_by_id( &state.into(), &payment_id, key_store, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; authenticate_client_secret(Some(&cs), &payment_intent)?; Ok(payment_intent) }) .await .transpose() } #[cfg(feature = "v1")] /// Check whether the business details are configured in the merchant account pub fn validate_business_details( business_country: Option<api_enums::CountryAlpha2>, business_label: Option<&String>, merchant_context: &domain::MerchantContext, ) -> RouterResult<()> { let primary_business_details = merchant_context .get_merchant_account() .primary_business_details .clone() .parse_value::<Vec<api_models::admin::PrimaryBusinessDetails>>("PrimaryBusinessDetails") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to parse primary business details")?; business_country .zip(business_label) .map(|(business_country, business_label)| { primary_business_details .iter() .find(|business_details| { &business_details.business == business_label && business_details.country == business_country }) .ok_or(errors::ApiErrorResponse::PreconditionFailed { message: "business_details are not configured in the merchant account" .to_string(), }) }) .transpose()?; Ok(()) } #[inline] pub(crate) fn get_payment_id_from_client_secret(cs: &str) -> RouterResult<String> { let (payment_id, _) = cs .rsplit_once("_secret_") .ok_or(errors::ApiErrorResponse::ClientSecretInvalid)?; Ok(payment_id.to_string()) } #[cfg(feature = "v1")] #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_authenticate_client_secret_session_not_expired() { let payment_intent = PaymentIntent { payment_id: id_type::PaymentId::try_from(Cow::Borrowed("23")).unwrap(), merchant_id: id_type::MerchantId::default(), status: storage_enums::IntentStatus::RequiresCapture, amount: MinorUnit::new(200), currency: None, amount_captured: None, customer_id: None, description: None, return_url: None, metadata: None, connector_id: None, shipping_address_id: None, billing_address_id: None, mit_category: None, statement_descriptor_name: None, statement_descriptor_suffix: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), last_synced: None, setup_future_usage: None, fingerprint_id: None, off_session: None, client_secret: Some("1".to_string()), active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID( "nopes".to_string(), ), business_country: None, business_label: None, order_details: None, allowed_payment_method_types: None, connector_metadata: None, feature_metadata: None, attempt_count: 1, payment_link_id: None, profile_id: Some(common_utils::generate_profile_id_of_default_length()), merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, updated_by: storage_enums::MerchantStorageScheme::PostgresOnly.to_string(), request_incremental_authorization: Some( common_enums::RequestIncrementalAuthorization::default(), ), incremental_authorization_allowed: None, authorization_count: None, session_expiry: Some( common_utils::date_time::now() .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)), ), request_external_three_ds_authentication: None, split_payments: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, organization_id: id_type::OrganizationId::default(), shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, request_extended_authorization: None, psd2_sca_exemption_type: None, processor_merchant_id: id_type::MerchantId::default(), created_by: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, is_iframe_redirection_enabled: None, is_payment_id_from_merchant: None, payment_channel: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }; let req_cs = Some("1".to_string()); assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_ok()); // Check if the result is an Ok variant } #[test] fn test_authenticate_client_secret_session_expired() { let created_at = common_utils::date_time::now().saturating_sub(time::Duration::seconds(20 * 60)); let payment_intent = PaymentIntent { payment_id: id_type::PaymentId::try_from(Cow::Borrowed("23")).unwrap(), merchant_id: id_type::MerchantId::default(), status: storage_enums::IntentStatus::RequiresCapture, amount: MinorUnit::new(200), currency: None, amount_captured: None, customer_id: None, description: None, return_url: None, metadata: None, connector_id: None, shipping_address_id: None, mit_category: None, billing_address_id: None, statement_descriptor_name: None, statement_descriptor_suffix: None, created_at, modified_at: common_utils::date_time::now(), fingerprint_id: None, last_synced: None, setup_future_usage: None, off_session: None, client_secret: Some("1".to_string()), active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID( "nopes".to_string(), ), business_country: None, business_label: None, order_details: None, allowed_payment_method_types: None, connector_metadata: None, feature_metadata: None, attempt_count: 1, payment_link_id: None, profile_id: Some(common_utils::generate_profile_id_of_default_length()), merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, updated_by: storage_enums::MerchantStorageScheme::PostgresOnly.to_string(), request_incremental_authorization: Some( common_enums::RequestIncrementalAuthorization::default(), ), incremental_authorization_allowed: None, authorization_count: None, session_expiry: Some( created_at.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)), ), request_external_three_ds_authentication: None, split_payments: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, organization_id: id_type::OrganizationId::default(), shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, request_extended_authorization: None, psd2_sca_exemption_type: None, processor_merchant_id: id_type::MerchantId::default(), created_by: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, is_iframe_redirection_enabled: None, is_payment_id_from_merchant: None, payment_channel: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }; let req_cs = Some("1".to_string()); assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent,).is_err()) } #[test] fn test_authenticate_client_secret_expired() { let payment_intent = PaymentIntent { payment_id: id_type::PaymentId::try_from(Cow::Borrowed("23")).unwrap(), merchant_id: id_type::MerchantId::default(), status: storage_enums::IntentStatus::RequiresCapture, amount: MinorUnit::new(200), currency: None, amount_captured: None, customer_id: None, description: None, return_url: None, metadata: None, connector_id: None, mit_category: None, shipping_address_id: None, billing_address_id: None, statement_descriptor_name: None, statement_descriptor_suffix: None, created_at: common_utils::date_time::now().saturating_sub(time::Duration::seconds(20)), modified_at: common_utils::date_time::now(), last_synced: None, setup_future_usage: None, off_session: None, client_secret: None, fingerprint_id: None, active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID( "nopes".to_string(), ), business_country: None, business_label: None, order_details: None, allowed_payment_method_types: None, connector_metadata: None, feature_metadata: None, attempt_count: 1, payment_link_id: None, profile_id: Some(common_utils::generate_profile_id_of_default_length()), merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, updated_by: storage_enums::MerchantStorageScheme::PostgresOnly.to_string(), request_incremental_authorization: Some( common_enums::RequestIncrementalAuthorization::default(), ), incremental_authorization_allowed: None, authorization_count: None, session_expiry: Some( common_utils::date_time::now() .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)), ), request_external_three_ds_authentication: None, split_payments: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, organization_id: id_type::OrganizationId::default(), shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, request_extended_authorization: None, psd2_sca_exemption_type: None, processor_merchant_id: id_type::MerchantId::default(), created_by: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, is_iframe_redirection_enabled: None, is_payment_id_from_merchant: None, payment_channel: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }; let req_cs = Some("1".to_string()); assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_err()) } } // This function will be removed after moving this functionality to server_wrap and using cache instead of config #[instrument(skip_all)] pub async fn insert_merchant_connector_creds_to_config( db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, merchant_connector_details: admin::MerchantConnectorDetailsWrap, ) -> RouterResult<()> { if let Some(encoded_data) = merchant_connector_details.encoded_data { let redis = &db .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let key = merchant_id.get_creds_identifier_key(&merchant_connector_details.creds_identifier); redis .serialize_and_set_key_with_expiry( &key.as_str().into(), &encoded_data.peek(), consts::CONNECTOR_CREDS_TOKEN_TTL, ) .await .map_or_else( |e| { Err(e .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to insert connector_creds to config")) }, |_| Ok(()), ) } else { Ok(()) } } /// Query for merchant connector account either by business label or profile id /// If profile_id is passed use it, or use connector_label to query merchant connector account #[instrument(skip_all)] pub async fn get_merchant_connector_account( state: &SessionState, merchant_id: &id_type::MerchantId, creds_identifier: Option<&str>, key_store: &domain::MerchantKeyStore, profile_id: &id_type::ProfileId, connector_name: &str, merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>, ) -> RouterResult<MerchantConnectorAccountType> { let db = &*state.store; let key_manager_state: &KeyManagerState = &state.into(); match creds_identifier { Some(creds_identifier) => { let key = merchant_id.get_creds_identifier_key(creds_identifier); let cloned_key = key.clone(); let redis_fetch = || async { db.get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection") .async_and_then(|redis| async move { redis .get_and_deserialize_key(&key.as_str().into(), "String") .await .change_context( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: key.clone(), }, ) .attach_printable(key.clone() + ": Not found in Redis") }) .await }; let db_fetch = || async { db.find_config_by_key(cloned_key.as_str()) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: cloned_key.to_owned(), }, ) }; let mca_config: String = redis_fetch() .await .map_or_else( |_| { Either::Left(async { match db_fetch().await { Ok(config_entry) => Ok(config_entry.config), Err(e) => Err(e), } }) }, |result| Either::Right(async { Ok(result) }), ) .await?; let private_key = state .conf .jwekey .get_inner() .tunnel_private_key .peek() .as_bytes(); let decrypted_mca = services::decrypt_jwe(mca_config.as_str(), services::KeyIdCheck::SkipKeyIdCheck, private_key, jwe::RSA_OAEP_256) .await .change_context(errors::ApiErrorResponse::UnprocessableEntity{ message: "decoding merchant_connector_details failed due to invalid data format!".into()}) .attach_printable( "Failed to decrypt merchant_connector_details sent in request and then put in cache", )?; let res = String::into_bytes(decrypted_mca) .parse_struct("MerchantConnectorDetails") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to parse merchant_connector_details sent in request and then put in cache", )?; Ok(MerchantConnectorAccountType::CacheVal(res)) } None => { let mca: RouterResult<domain::MerchantConnectorAccount> = if let Some(merchant_connector_id) = merchant_connector_id { #[cfg(feature = "v1")] { db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_id, merchant_connector_id, key_store, ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, ) } #[cfg(feature = "v2")] { db.find_merchant_connector_account_by_id( &state.into(), merchant_connector_id, key_store, ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, ) } } else { #[cfg(feature = "v1")] { db.find_merchant_connector_account_by_profile_id_connector_name( key_manager_state, profile_id, connector_name, key_store, ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: format!( "profile id {} and connector name {connector_name}", profile_id.get_string_repr() ), }, ) } #[cfg(feature = "v2")] { todo!() } }; mca.map(Box::new).map(MerchantConnectorAccountType::DbVal) } } } /// This function replaces the request and response type of routerdata with the /// request and response type passed /// # Arguments /// /// * `router_data` - original router data /// * `request` - new request core/helper /// * `response` - new response pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>( router_data: RouterData<F1, Req1, Res1>, request: Req2, response: Result<Res2, ErrorResponse>, ) -> RouterData<F2, Req2, Res2> { RouterData { flow: std::marker::PhantomData, request, response, merchant_id: router_data.merchant_id, tenant_id: router_data.tenant_id, address: router_data.address, amount_captured: router_data.amount_captured, minor_amount_captured: router_data.minor_amount_captured, auth_type: router_data.auth_type, connector: router_data.connector, connector_auth_type: router_data.connector_auth_type, connector_meta_data: router_data.connector_meta_data, description: router_data.description, payment_id: router_data.payment_id, payment_method: router_data.payment_method, payment_method_type: router_data.payment_method_type, status: router_data.status, attempt_id: router_data.attempt_id, access_token: router_data.access_token, session_token: router_data.session_token, payment_method_status: router_data.payment_method_status, reference_id: router_data.reference_id, payment_method_token: router_data.payment_method_token, customer_id: router_data.customer_id, connector_customer: router_data.connector_customer, preprocessing_id: router_data.preprocessing_id, payment_method_balance: router_data.payment_method_balance, recurring_mandate_payment_data: router_data.recurring_mandate_payment_data, connector_request_reference_id: router_data.connector_request_reference_id, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode: router_data.test_mode, connector_api_version: router_data.connector_api_version, connector_http_status_code: router_data.connector_http_status_code, external_latency: router_data.external_latency, apple_pay_flow: router_data.apple_pay_flow, frm_metadata: router_data.frm_metadata, refund_id: router_data.refund_id, dispute_id: router_data.dispute_id, connector_response: router_data.connector_response, integrity_check: Ok(()), connector_wallets_details: router_data.connector_wallets_details, additional_merchant_data: router_data.additional_merchant_data, header_payload: router_data.header_payload, 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, raw_connector_response: router_data.raw_connector_response, is_payment_id_from_merchant: router_data.is_payment_id_from_merchant, l2_l3_data: router_data.l2_l3_data, minor_amount_capturable: router_data.minor_amount_capturable, authorized_amount: router_data.authorized_amount, } } #[cfg(feature = "v1")] #[instrument(skip_all)] pub fn get_attempt_type( payment_intent: &PaymentIntent, payment_attempt: &PaymentAttempt, is_manual_retry_enabled: Option<bool>, action: &str, ) -> RouterResult<AttemptType> { match payment_intent.status { enums::IntentStatus::Failed => { if matches!(is_manual_retry_enabled, Some(true)) { // if it is false, don't go ahead with manual retry fp_utils::when( !validate_manual_retry_cutoff( payment_intent.created_at, payment_intent.session_expiry, ), || { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: format!("You cannot {action} this payment using `manual_retry` because the allowed duration has expired") } )) }, )?; metrics::MANUAL_RETRY_REQUEST_COUNT.add( 1, router_env::metric_attributes!(( "merchant_id", payment_attempt.merchant_id.clone(), )), ); match payment_attempt.status { enums::AttemptStatus::Started | enums::AttemptStatus::AuthenticationPending | enums::AttemptStatus::AuthenticationSuccessful | enums::AttemptStatus::Authorized | enums::AttemptStatus::Charged | enums::AttemptStatus::Authorizing | enums::AttemptStatus::CodInitiated | enums::AttemptStatus::VoidInitiated | enums::AttemptStatus::CaptureInitiated | enums::AttemptStatus::Unresolved | enums::AttemptStatus::Pending | enums::AttemptStatus::ConfirmationAwaited | enums::AttemptStatus::PartialCharged | enums::AttemptStatus::PartialChargedAndChargeable | enums::AttemptStatus::Voided | enums::AttemptStatus::VoidedPostCharge | enums::AttemptStatus::AutoRefunded | enums::AttemptStatus::PaymentMethodAwaited | enums::AttemptStatus::DeviceDataCollectionPending | enums::AttemptStatus::IntegrityFailure | enums::AttemptStatus::Expired | enums::AttemptStatus::PartiallyAuthorized => { metrics::MANUAL_RETRY_VALIDATION_FAILED.add( 1, router_env::metric_attributes!(( "merchant_id", payment_attempt.merchant_id.clone(), )), ); Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Payment Attempt unexpected state") } storage_enums::AttemptStatus::VoidFailed | storage_enums::AttemptStatus::RouterDeclined | storage_enums::AttemptStatus::CaptureFailed => { metrics::MANUAL_RETRY_VALIDATION_FAILED.add( 1, router_env::metric_attributes!(( "merchant_id", payment_attempt.merchant_id.clone(), )), ); Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: format!("You cannot {action} this payment because it has status {}, and the previous attempt has the status {}", payment_intent.status, payment_attempt.status) } )) } storage_enums::AttemptStatus::AuthenticationFailed | storage_enums::AttemptStatus::AuthorizationFailed | storage_enums::AttemptStatus::Failure => { metrics::MANUAL_RETRY_COUNT.add( 1, router_env::metric_attributes!(( "merchant_id", payment_attempt.merchant_id.clone(), )), ); Ok(AttemptType::New) } } } else { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: format!("You cannot {action} this payment because it has status {}, you can enable `manual_retry` in profile to try this payment again", payment_intent.status) } )) } } enums::IntentStatus::Cancelled | enums::IntentStatus::CancelledPostCapture | enums::IntentStatus::RequiresCapture | enums::IntentStatus::PartiallyCaptured | enums::IntentStatus::PartiallyCapturedAndCapturable | enums::IntentStatus::Processing | enums::IntentStatus::Succeeded | enums::IntentStatus::Conflicted | enums::IntentStatus::Expired | enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: format!( "You cannot {action} this payment because it has status {}", payment_intent.status, ), })) } enums::IntentStatus::RequiresCustomerAction | enums::IntentStatus::RequiresMerchantAction | enums::IntentStatus::RequiresPaymentMethod | enums::IntentStatus::RequiresConfirmation => Ok(AttemptType::SameOld), } } fn validate_manual_retry_cutoff( created_at: time::PrimitiveDateTime, session_expiry: Option<time::PrimitiveDateTime>, ) -> bool { let utc_current_time = time::OffsetDateTime::now_utc(); let primitive_utc_current_time = time::PrimitiveDateTime::new(utc_current_time.date(), utc_current_time.time()); let time_difference_from_creation = primitive_utc_current_time - created_at; // cutoff time is 50% of session duration let cutoff_limit = match session_expiry { Some(session_expiry) => { let duration = session_expiry - created_at; duration.whole_seconds() / 2 } None => consts::DEFAULT_SESSION_EXPIRY / 2, }; time_difference_from_creation.whole_seconds() <= cutoff_limit } #[derive(Debug, Eq, PartialEq, Clone)] pub enum AttemptType { New, SameOld, } impl AttemptType { #[cfg(feature = "v1")] // The function creates a new payment_attempt from the previous payment attempt but doesn't populate fields like payment_method, error_code etc. // Logic to override the fields with data provided in the request should be done after this if required. // In case if fields are not overridden by the request then they contain the same data that was in the previous attempt provided it is populated in this function. #[inline(always)] fn make_new_payment_attempt( payment_method_data: Option<&api_models::payments::PaymentMethodData>, old_payment_attempt: PaymentAttempt, new_attempt_count: i16, storage_scheme: enums::MerchantStorageScheme, ) -> storage::PaymentAttemptNew { let created_at @ modified_at @ last_synced = Some(common_utils::date_time::now()); storage::PaymentAttemptNew { attempt_id: old_payment_attempt .payment_id .get_attempt_id(new_attempt_count), payment_id: old_payment_attempt.payment_id, merchant_id: old_payment_attempt.merchant_id, // A new payment attempt is getting created so, used the same function which is used to populate status in PaymentCreate Flow. status: payment_attempt_status_fsm(payment_method_data, Some(true)), currency: old_payment_attempt.currency, save_to_locker: old_payment_attempt.save_to_locker, connector: None, error_message: None, offer_amount: old_payment_attempt.offer_amount, payment_method_id: None, payment_method: None, capture_method: old_payment_attempt.capture_method, capture_on: old_payment_attempt.capture_on, confirm: old_payment_attempt.confirm, authentication_type: old_payment_attempt.authentication_type, created_at, modified_at, last_synced, cancellation_reason: None, amount_to_capture: old_payment_attempt.amount_to_capture, // Once the payment_attempt is authorised then mandate_id is created. If this payment attempt is authorised then mandate_id will be overridden. // Since mandate_id is a contract between merchant and customer to debit customers amount adding it to newly created attempt mandate_id: old_payment_attempt.mandate_id, // The payment could be done from a different browser or same browser, it would probably be overridden by request data. browser_info: None, error_code: None, payment_token: None, connector_metadata: None, payment_experience: None, payment_method_type: None, payment_method_data: None, // In case it is passed in create and not in confirm, business_sub_label: old_payment_attempt.business_sub_label, // If the algorithm is entered in Create call from server side, it needs to be populated here, however it could be overridden from the request. straight_through_algorithm: old_payment_attempt.straight_through_algorithm, mandate_details: old_payment_attempt.mandate_details, preprocessing_step_id: None, error_reason: None, multiple_capture_count: None, connector_response_reference_id: None, amount_capturable: old_payment_attempt.net_amount.get_total_amount(), updated_by: storage_scheme.to_string(), authentication_data: None, encoded_data: None, merchant_connector_id: None, unified_code: None, unified_message: None, net_amount: old_payment_attempt.net_amount, external_three_ds_authentication_attempted: old_payment_attempt .external_three_ds_authentication_attempted, authentication_connector: None, authentication_id: None, mandate_data: old_payment_attempt.mandate_data, // New payment method billing address can be passed for a retry payment_method_billing_address_id: None, fingerprint_id: None, client_source: old_payment_attempt.client_source, client_version: old_payment_attempt.client_version, customer_acceptance: old_payment_attempt.customer_acceptance, organization_id: old_payment_attempt.organization_id, profile_id: old_payment_attempt.profile_id, connector_mandate_detail: None, request_extended_authorization: None, extended_authorization_applied: None, capture_before: None, card_discovery: None, processor_merchant_id: old_payment_attempt.processor_merchant_id, created_by: old_payment_attempt.created_by, setup_future_usage_applied: None, routing_approach: old_payment_attempt.routing_approach, connector_request_reference_id: None, network_transaction_id: None, network_details: None, is_stored_credential: old_payment_attempt.is_stored_credential, authorized_amount: old_payment_attempt.authorized_amount, } } // #[cfg(feature = "v2")] // // The function creates a new payment_attempt from the previous payment attempt but doesn't populate fields like payment_method, error_code etc. // // Logic to override the fields with data provided in the request should be done after this if required. // // In case if fields are not overridden by the request then they contain the same data that was in the previous attempt provided it is populated in this function. // #[inline(always)] // fn make_new_payment_attempt( // _payment_method_data: Option<&api_models::payments::PaymentMethodData>, // _old_payment_attempt: PaymentAttempt, // _new_attempt_count: i16, // _storage_scheme: enums::MerchantStorageScheme, // ) -> PaymentAttempt { // todo!() // } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn modify_payment_intent_and_payment_attempt( &self, request: &api_models::payments::PaymentsRequest, fetched_payment_intent: PaymentIntent, fetched_payment_attempt: PaymentAttempt, state: &SessionState, key_store: &domain::MerchantKeyStore, storage_scheme: storage::enums::MerchantStorageScheme, ) -> RouterResult<(PaymentIntent, PaymentAttempt)> { match self { Self::SameOld => Ok((fetched_payment_intent, fetched_payment_attempt)), Self::New => { let db = &*state.store; let key_manager_state = &state.into(); let new_attempt_count = fetched_payment_intent.attempt_count + 1; let new_payment_attempt_to_insert = Self::make_new_payment_attempt( request .payment_method_data .as_ref() .and_then(|request_payment_method_data| { request_payment_method_data.payment_method_data.as_ref() }), fetched_payment_attempt, new_attempt_count, storage_scheme, ); #[cfg(feature = "v1")] let new_payment_attempt = db .insert_payment_attempt(new_payment_attempt_to_insert, storage_scheme) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment { payment_id: fetched_payment_intent.get_id().to_owned(), })?; #[cfg(feature = "v2")] let new_payment_attempt = db .insert_payment_attempt( key_manager_state, key_store, new_payment_attempt_to_insert, storage_scheme, ) .await .to_duplicate_response(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to insert payment attempt")?; let updated_payment_intent = db .update_payment_intent( key_manager_state, fetched_payment_intent, storage::PaymentIntentUpdate::StatusAndAttemptUpdate { status: payment_intent_status_fsm( request.payment_method_data.as_ref().and_then( |request_payment_method_data| { request_payment_method_data.payment_method_data.as_ref() }, ), Some(true), ), active_attempt_id: new_payment_attempt.get_id().to_owned(), attempt_count: new_attempt_count, updated_by: storage_scheme.to_string(), }, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; logger::info!( "manual_retry payment for {:?} with attempt_id {:?}", updated_payment_intent.get_id(), new_payment_attempt.get_id() ); Ok((updated_payment_intent, new_payment_attempt)) } } } } #[inline(always)] pub fn is_manual_retry_allowed( intent_status: &storage_enums::IntentStatus, attempt_status: &storage_enums::AttemptStatus, connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, merchant_id: &id_type::MerchantId, ) -> Option<bool> { let is_payment_status_eligible_for_retry = match intent_status { enums::IntentStatus::Failed => match attempt_status { enums::AttemptStatus::Started | enums::AttemptStatus::AuthenticationPending | enums::AttemptStatus::AuthenticationSuccessful | enums::AttemptStatus::Authorized | enums::AttemptStatus::Charged | enums::AttemptStatus::Authorizing | enums::AttemptStatus::CodInitiated | enums::AttemptStatus::VoidInitiated | enums::AttemptStatus::CaptureInitiated | enums::AttemptStatus::Unresolved | enums::AttemptStatus::Pending | enums::AttemptStatus::ConfirmationAwaited | enums::AttemptStatus::PartialCharged | enums::AttemptStatus::PartialChargedAndChargeable | enums::AttemptStatus::Voided | enums::AttemptStatus::VoidedPostCharge | enums::AttemptStatus::AutoRefunded | enums::AttemptStatus::PaymentMethodAwaited | enums::AttemptStatus::DeviceDataCollectionPending | enums::AttemptStatus::IntegrityFailure | enums::AttemptStatus::Expired | enums::AttemptStatus::PartiallyAuthorized => { logger::error!("Payment Attempt should not be in this state because Attempt to Intent status mapping doesn't allow it"); None } enums::AttemptStatus::VoidFailed | enums::AttemptStatus::RouterDeclined | enums::AttemptStatus::CaptureFailed => Some(false), enums::AttemptStatus::AuthenticationFailed | enums::AttemptStatus::AuthorizationFailed | enums::AttemptStatus::Failure => Some(true), }, enums::IntentStatus::Cancelled | enums::IntentStatus::CancelledPostCapture | enums::IntentStatus::RequiresCapture | enums::IntentStatus::PartiallyCaptured | enums::IntentStatus::PartiallyCapturedAndCapturable | enums::IntentStatus::Processing | enums::IntentStatus::Succeeded | enums::IntentStatus::Conflicted | enums::IntentStatus::Expired | enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => Some(false), enums::IntentStatus::RequiresCustomerAction | enums::IntentStatus::RequiresMerchantAction | enums::IntentStatus::RequiresPaymentMethod | enums::IntentStatus::RequiresConfirmation => None, }; let is_merchant_id_enabled_for_retries = !connector_request_reference_id_config .merchant_ids_send_payment_id_as_connector_request_id .contains(merchant_id); is_payment_status_eligible_for_retry .map(|payment_status_check| payment_status_check && is_merchant_id_enabled_for_retries) } #[cfg(test)] mod test { #![allow(clippy::unwrap_used)] #[test] fn test_client_secret_parse() { let client_secret1 = "pay_3TgelAms4RQec8xSStjF_secret_fc34taHLw1ekPgNh92qr"; let client_secret2 = "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_fc34taHLw1ekPgNh92qr"; let client_secret3 = "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret__secret_fc34taHLw1ekPgNh92qr"; assert_eq!( "pay_3TgelAms4RQec8xSStjF", super::get_payment_id_from_client_secret(client_secret1).unwrap() ); assert_eq!( "pay_3Tgel__Ams4RQ_secret_ec8xSStjF", super::get_payment_id_from_client_secret(client_secret2).unwrap() ); assert_eq!( "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_", super::get_payment_id_from_client_secret(client_secret3).unwrap() ); } } #[instrument(skip_all)] pub async fn get_additional_payment_data( pm_data: &domain::PaymentMethodData, db: &dyn StorageInterface, profile_id: &id_type::ProfileId, ) -> Result< Option<api_models::payments::AdditionalPaymentData>, error_stack::Report<errors::ApiErrorResponse>, > { match pm_data { domain::PaymentMethodData::Card(card_data) => { //todo! let card_isin = Some(card_data.card_number.get_card_isin()); let enable_extended_bin =db .find_config_by_key_unwrap_or( format!("{}_enable_extended_card_bin", profile_id.get_string_repr()).as_str(), Some("false".to_string())) .await.map_err(|err| services::logger::error!(message="Failed to fetch the config", extended_card_bin_error=?err)).ok(); let card_extended_bin = match enable_extended_bin { Some(config) if config.config == "true" => { Some(card_data.card_number.get_extended_card_bin()) } _ => None, }; // 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", )?; let (card_network, signature_network, is_regulated) = card_data .co_badged_card_data .as_ref() .map(|co_badged_data| { logger::debug!("Co-badged card data found"); ( card_data.card_network.clone(), co_badged_data .co_badged_card_networks_info .get_signature_network(), Some(co_badged_data.is_regulated), ) }) .or_else(|| { is_cobadged_based_on_regex.then(|| { logger::debug!("Card network is cobadged (regex-based detection)"); (card_data.card_network.clone(), None, None) }) }) .unwrap_or_else(|| { logger::debug!("Card network is not cobadged"); (None, None, None) }); let last4 = Some(card_data.card_number.get_last4()); if card_data.card_issuer.is_some() && card_network.is_some() && card_data.card_type.is_some() && card_data.card_issuing_country.is_some() && card_data.bank_code.is_some() { Ok(Some(api_models::payments::AdditionalPaymentData::Card( Box::new(api_models::payments::AdditionalCardInfo { card_issuer: card_data.card_issuer.to_owned(), card_network, card_type: card_data.card_type.to_owned(), card_issuing_country: card_data.card_issuing_country.to_owned(), bank_code: card_data.bank_code.to_owned(), card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), card_holder_name: card_data.card_holder_name.clone(), last4: last4.clone(), card_isin: card_isin.clone(), card_extended_bin: card_extended_bin.clone(), // These are filled after calling the processor / connector payment_checks: None, authentication_data: None, is_regulated, signature_network: signature_network.clone(), }), ))) } else { let card_info = card_isin .clone() .async_and_then(|card_isin| async move { db.get_card_info(&card_isin) .await .map_err(|error| services::logger::warn!(card_info_error=?error)) .ok() }) .await .flatten() .map(|card_info| { api_models::payments::AdditionalPaymentData::Card(Box::new( api_models::payments::AdditionalCardInfo { card_issuer: card_info.card_issuer, card_network: card_network.clone().or(card_info.card_network), bank_code: card_info.bank_code, card_type: card_info.card_type, card_issuing_country: card_info.card_issuing_country, last4: last4.clone(), card_isin: card_isin.clone(), card_extended_bin: card_extended_bin.clone(), card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), card_holder_name: card_data.card_holder_name.clone(), // These are filled after calling the processor / connector payment_checks: None, authentication_data: None, is_regulated, signature_network: signature_network.clone(), }, )) }); Ok(Some(card_info.unwrap_or_else(|| { api_models::payments::AdditionalPaymentData::Card(Box::new( api_models::payments::AdditionalCardInfo { card_issuer: None, card_network, bank_code: None, card_type: None, card_issuing_country: None, last4, card_isin, card_extended_bin, card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), card_holder_name: card_data.card_holder_name.clone(), // These are filled after calling the processor / connector payment_checks: None, authentication_data: None, is_regulated, signature_network: signature_network.clone(), }, )) }))) } } domain::PaymentMethodData::BankRedirect(bank_redirect_data) => match bank_redirect_data { domain::BankRedirectData::Eps { bank_name, .. } => Ok(Some( api_models::payments::AdditionalPaymentData::BankRedirect { bank_name: bank_name.to_owned(), details: None, }, )), domain::BankRedirectData::Eft { .. } => Ok(Some( api_models::payments::AdditionalPaymentData::BankRedirect { bank_name: None, details: None, }, )), domain::BankRedirectData::OnlineBankingFpx { issuer } => Ok(Some( api_models::payments::AdditionalPaymentData::BankRedirect { bank_name: Some(issuer.to_owned()), details: None, }, )), domain::BankRedirectData::Ideal { bank_name, .. } => Ok(Some( api_models::payments::AdditionalPaymentData::BankRedirect { bank_name: bank_name.to_owned(), details: None, }, )), domain::BankRedirectData::BancontactCard { card_number, card_exp_month, card_exp_year, card_holder_name, } => Ok(Some( api_models::payments::AdditionalPaymentData::BankRedirect { bank_name: None, details: Some( payment_additional_types::BankRedirectDetails::BancontactCard(Box::new( payment_additional_types::BancontactBankRedirectAdditionalData { last4: card_number.as_ref().map(|c| c.get_last4()), card_exp_month: card_exp_month.clone(), card_exp_year: card_exp_year.clone(), card_holder_name: card_holder_name.clone(), }, )), ), }, )), domain::BankRedirectData::Blik { blik_code } => Ok(Some( api_models::payments::AdditionalPaymentData::BankRedirect { bank_name: None, details: blik_code.as_ref().map(|blik_code| { payment_additional_types::BankRedirectDetails::Blik(Box::new( payment_additional_types::BlikBankRedirectAdditionalData { blik_code: Some(blik_code.to_owned()), }, )) }), }, )), domain::BankRedirectData::Giropay { bank_account_bic, bank_account_iban, country, } => Ok(Some( api_models::payments::AdditionalPaymentData::BankRedirect { bank_name: None, details: Some(payment_additional_types::BankRedirectDetails::Giropay( Box::new( payment_additional_types::GiropayBankRedirectAdditionalData { bic: bank_account_bic .as_ref() .map(|bic| MaskedSortCode::from(bic.to_owned())), iban: bank_account_iban .as_ref() .map(|iban| MaskedIban::from(iban.to_owned())), country: *country, }, ), )), }, )), _ => Ok(Some( api_models::payments::AdditionalPaymentData::BankRedirect { bank_name: None, details: None, }, )), }, domain::PaymentMethodData::Wallet(wallet) => match wallet { domain::WalletData::ApplePay(apple_pay_wallet_data) => { Ok(Some(api_models::payments::AdditionalPaymentData::Wallet { apple_pay: Some(api_models::payments::ApplepayPaymentMethod { display_name: apple_pay_wallet_data.payment_method.display_name.clone(), network: apple_pay_wallet_data.payment_method.network.clone(), pm_type: apple_pay_wallet_data.payment_method.pm_type.clone(), }), google_pay: None, samsung_pay: None, })) } domain::WalletData::GooglePay(google_pay_pm_data) => { Ok(Some(api_models::payments::AdditionalPaymentData::Wallet { apple_pay: None, google_pay: Some(payment_additional_types::WalletAdditionalDataForCard { last4: google_pay_pm_data.info.card_details.clone(), card_network: google_pay_pm_data.info.card_network.clone(), card_type: Some(google_pay_pm_data.pm_type.clone()), }), samsung_pay: None, })) } domain::WalletData::SamsungPay(samsung_pay_pm_data) => { Ok(Some(api_models::payments::AdditionalPaymentData::Wallet { apple_pay: None, google_pay: None, samsung_pay: Some(payment_additional_types::WalletAdditionalDataForCard { last4: samsung_pay_pm_data .payment_credential .card_last_four_digits .clone(), card_network: samsung_pay_pm_data .payment_credential .card_brand .to_string(), card_type: None, }), })) } _ => Ok(Some(api_models::payments::AdditionalPaymentData::Wallet { apple_pay: None, google_pay: None, samsung_pay: None, })), }, domain::PaymentMethodData::PayLater(_) => Ok(Some( api_models::payments::AdditionalPaymentData::PayLater { klarna_sdk: None }, )), domain::PaymentMethodData::BankTransfer(bank_transfer) => Ok(Some( api_models::payments::AdditionalPaymentData::BankTransfer { details: Some((*(bank_transfer.to_owned())).into()), }, )), domain::PaymentMethodData::Crypto(crypto) => { Ok(Some(api_models::payments::AdditionalPaymentData::Crypto { details: Some(crypto.to_owned().into()), })) } domain::PaymentMethodData::BankDebit(bank_debit) => Ok(Some( api_models::payments::AdditionalPaymentData::BankDebit { details: Some(bank_debit.to_owned().into()), }, )), domain::PaymentMethodData::MandatePayment => Ok(Some( api_models::payments::AdditionalPaymentData::MandatePayment {}, )), domain::PaymentMethodData::Reward => { Ok(Some(api_models::payments::AdditionalPaymentData::Reward {})) } domain::PaymentMethodData::RealTimePayment(realtime_payment) => Ok(Some( api_models::payments::AdditionalPaymentData::RealTimePayment { details: Some((*(realtime_payment.to_owned())).into()), }, )), domain::PaymentMethodData::Upi(upi) => { Ok(Some(api_models::payments::AdditionalPaymentData::Upi { details: Some(upi.to_owned().into()), })) } domain::PaymentMethodData::CardRedirect(card_redirect) => Ok(Some( api_models::payments::AdditionalPaymentData::CardRedirect { details: Some(card_redirect.to_owned().into()), }, )), domain::PaymentMethodData::Voucher(voucher) => { Ok(Some(api_models::payments::AdditionalPaymentData::Voucher { details: Some(voucher.to_owned().into()), })) } domain::PaymentMethodData::GiftCard(gift_card) => Ok(Some( api_models::payments::AdditionalPaymentData::GiftCard { details: Some((*(gift_card.to_owned())).into()), }, )), domain::PaymentMethodData::CardToken(card_token) => Ok(Some( api_models::payments::AdditionalPaymentData::CardToken { details: Some(card_token.to_owned().into()), }, )), domain::PaymentMethodData::OpenBanking(open_banking) => Ok(Some( api_models::payments::AdditionalPaymentData::OpenBanking { details: Some(open_banking.to_owned().into()), }, )), domain::PaymentMethodData::CardDetailsForNetworkTransactionId(card_data) => { let card_isin = Some(card_data.card_number.get_card_isin()); let enable_extended_bin =db .find_config_by_key_unwrap_or( format!("{}_enable_extended_card_bin", profile_id.get_string_repr()).as_str(), Some("false".to_string())) .await.map_err(|err| services::logger::error!(message="Failed to fetch the config", extended_card_bin_error=?err)).ok(); let card_extended_bin = match enable_extended_bin { Some(config) if config.config == "true" => { Some(card_data.card_number.get_extended_card_bin()) } _ => None, }; let card_network = match 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 last4 = Some(card_data.card_number.get_last4()); if card_data.card_issuer.is_some() && card_network.is_some() && card_data.card_type.is_some() && card_data.card_issuing_country.is_some() && card_data.bank_code.is_some() { Ok(Some(api_models::payments::AdditionalPaymentData::Card( Box::new(api_models::payments::AdditionalCardInfo { card_issuer: card_data.card_issuer.to_owned(), card_network, card_type: card_data.card_type.to_owned(), card_issuing_country: card_data.card_issuing_country.to_owned(), bank_code: card_data.bank_code.to_owned(), card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), card_holder_name: card_data.card_holder_name.clone(), last4: last4.clone(), card_isin: card_isin.clone(), card_extended_bin: card_extended_bin.clone(), // These are filled after calling the processor / connector payment_checks: None, authentication_data: None, is_regulated: None, signature_network: None, }), ))) } else { let card_info = card_isin .clone() .async_and_then(|card_isin| async move { db.get_card_info(&card_isin) .await .map_err(|error| services::logger::warn!(card_info_error=?error)) .ok() }) .await .flatten() .map(|card_info| { api_models::payments::AdditionalPaymentData::Card(Box::new( api_models::payments::AdditionalCardInfo { card_issuer: card_info.card_issuer, card_network: card_network.clone().or(card_info.card_network), bank_code: card_info.bank_code, card_type: card_info.card_type, card_issuing_country: card_info.card_issuing_country, last4: last4.clone(), card_isin: card_isin.clone(), card_extended_bin: card_extended_bin.clone(), card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), card_holder_name: card_data.card_holder_name.clone(), // These are filled after calling the processor / connector payment_checks: None, authentication_data: None, is_regulated: None, signature_network: None, }, )) }); Ok(Some(card_info.unwrap_or_else(|| { api_models::payments::AdditionalPaymentData::Card(Box::new( api_models::payments::AdditionalCardInfo { card_issuer: None, card_network, bank_code: None, card_type: None, card_issuing_country: None, last4, card_isin, card_extended_bin, card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), card_holder_name: card_data.card_holder_name.clone(), // These are filled after calling the processor / connector payment_checks: None, authentication_data: None, is_regulated: None, signature_network: None, }, )) }))) } } domain::PaymentMethodData::MobilePayment(mobile_payment) => Ok(Some( api_models::payments::AdditionalPaymentData::MobilePayment { details: Some(mobile_payment.to_owned().into()), }, )), domain::PaymentMethodData::NetworkToken(_) => Ok(None), } } #[cfg(feature = "v1")] pub fn validate_customer_access( payment_intent: &PaymentIntent, auth_flow: services::AuthFlow, request: &api::PaymentsRequest, ) -> Result<(), errors::ApiErrorResponse> { if auth_flow == services::AuthFlow::Client && request.get_customer_id().is_some() { let is_same_customer = request.get_customer_id() == payment_intent.customer_id.as_ref(); if !is_same_customer { Err(errors::ApiErrorResponse::GenericUnauthorized { message: "Unauthorised access to update customer".to_string(), })?; } } Ok(()) } pub fn is_apple_pay_simplified_flow( connector_metadata: Option<pii::SecretSerdeValue>, connector_name: Option<&String>, ) -> CustomResult<bool, errors::ApiErrorResponse> { let option_apple_pay_metadata = get_applepay_metadata(connector_metadata) .map_err(|error| { logger::info!( "Apple pay metadata parsing for {:?} in is_apple_pay_simplified_flow {:?}", connector_name, error ) }) .ok(); // return true only if the apple flow type is simplified Ok(matches!( option_apple_pay_metadata, Some( api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined( api_models::payments::ApplePayCombinedMetadata::Simplified { .. } ) ) )) } // This function will return the encrypted connector wallets details with Apple Pay certificates // Currently apple pay certifiactes are stored in the metadata which is not encrypted. // In future we want those certificates to be encrypted and stored in the connector_wallets_details. // As part of migration fallback this function checks apple pay details are present in connector_wallets_details // If yes, it will encrypt connector_wallets_details and store it in the database. // If no, it will check if apple pay details are present in metadata and merge it with connector_wallets_details, encrypt and store it. pub async fn get_connector_wallets_details_with_apple_pay_certificates( connector_metadata: &Option<masking::Secret<tera::Value>>, connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>, ) -> RouterResult<Option<masking::Secret<serde_json::Value>>> { let connector_wallet_details_with_apple_pay_metadata_optional = get_apple_pay_metadata_if_needed(connector_metadata, connector_wallets_details_optional) .await?; let connector_wallets_details = connector_wallet_details_with_apple_pay_metadata_optional .map(|details| { serde_json::to_value(details) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize Apple Pay metadata as JSON") }) .transpose()? .map(masking::Secret::new); Ok(connector_wallets_details) } async fn get_apple_pay_metadata_if_needed( connector_metadata: &Option<masking::Secret<tera::Value>>, connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>, ) -> RouterResult<Option<api_models::admin::ConnectorWalletDetails>> { if let Some(connector_wallets_details) = connector_wallets_details_optional { if connector_wallets_details.apple_pay_combined.is_some() || connector_wallets_details.apple_pay.is_some() { return Ok(Some(connector_wallets_details.clone())); } // Otherwise, merge Apple Pay metadata return get_and_merge_apple_pay_metadata( connector_metadata.clone(), Some(connector_wallets_details.clone()), ) .await; } // If connector_wallets_details_optional is None, attempt to get Apple Pay metadata get_and_merge_apple_pay_metadata(connector_metadata.clone(), None).await } async fn get_and_merge_apple_pay_metadata( connector_metadata: Option<masking::Secret<tera::Value>>, connector_wallets_details_optional: Option<api_models::admin::ConnectorWalletDetails>, ) -> RouterResult<Option<api_models::admin::ConnectorWalletDetails>> { let apple_pay_metadata_optional = get_applepay_metadata(connector_metadata) .map_err(|error| { logger::error!( "Apple Pay metadata parsing failed in get_encrypted_connector_wallets_details_with_apple_pay_certificates {:?}", error ); }) .ok(); if let Some(apple_pay_metadata) = apple_pay_metadata_optional { let updated_wallet_details = match apple_pay_metadata { api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined( apple_pay_combined_metadata, ) => { let combined_metadata_json = serde_json::to_value(apple_pay_combined_metadata) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize Apple Pay combined metadata as JSON")?; api_models::admin::ConnectorWalletDetails { apple_pay_combined: Some(masking::Secret::new(combined_metadata_json)), apple_pay: connector_wallets_details_optional .as_ref() .and_then(|d| d.apple_pay.clone()), amazon_pay: connector_wallets_details_optional .as_ref() .and_then(|d| d.amazon_pay.clone()), samsung_pay: connector_wallets_details_optional .as_ref() .and_then(|d| d.samsung_pay.clone()), paze: connector_wallets_details_optional .as_ref() .and_then(|d| d.paze.clone()), google_pay: connector_wallets_details_optional .as_ref() .and_then(|d| d.google_pay.clone()), } } api_models::payments::ApplepaySessionTokenMetadata::ApplePay(apple_pay_metadata) => { let metadata_json = serde_json::to_value(apple_pay_metadata) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize Apple Pay metadata as JSON")?; api_models::admin::ConnectorWalletDetails { apple_pay: Some(masking::Secret::new(metadata_json)), apple_pay_combined: connector_wallets_details_optional .as_ref() .and_then(|d| d.apple_pay_combined.clone()), amazon_pay: connector_wallets_details_optional .as_ref() .and_then(|d| d.amazon_pay.clone()), samsung_pay: connector_wallets_details_optional .as_ref() .and_then(|d| d.samsung_pay.clone()), paze: connector_wallets_details_optional .as_ref() .and_then(|d| d.paze.clone()), google_pay: connector_wallets_details_optional .as_ref() .and_then(|d| d.google_pay.clone()), } } }; return Ok(Some(updated_wallet_details)); } // Return connector_wallets_details if no Apple Pay metadata was found Ok(connector_wallets_details_optional) } pub fn get_applepay_metadata( connector_metadata: Option<pii::SecretSerdeValue>, ) -> RouterResult<api_models::payments::ApplepaySessionTokenMetadata> { connector_metadata .clone() .parse_value::<api_models::payments::ApplepayCombinedSessionTokenData>( "ApplepayCombinedSessionTokenData", ) .map(|combined_metadata| { api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined( combined_metadata.apple_pay_combined, ) }) .or_else(|_| { connector_metadata .parse_value::<api_models::payments::ApplepaySessionTokenData>( "ApplepaySessionTokenData", ) .map(|old_metadata| { api_models::payments::ApplepaySessionTokenMetadata::ApplePay( old_metadata.apple_pay, ) }) }) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_metadata".to_string(), expected_format: "applepay_metadata_format".to_string(), }) } pub fn calculate_debit_routing_savings(net_amount: i64, saving_percentage: f64) -> MinorUnit { logger::debug!( ?net_amount, ?saving_percentage, "Calculating debit routing saving amount" ); let net_decimal = Decimal::from_i64(net_amount).unwrap_or_else(|| { logger::warn!(?net_amount, "Invalid net_amount, using 0"); Decimal::ZERO }); let percentage_decimal = Decimal::from_f64(saving_percentage).unwrap_or_else(|| { logger::warn!(?saving_percentage, "Invalid saving_percentage, using 0"); Decimal::ZERO }); let savings_decimal = net_decimal * percentage_decimal / Decimal::from(100); let rounded_savings = savings_decimal.round(); let savings_int = rounded_savings.to_i64().unwrap_or_else(|| { logger::warn!( ?rounded_savings, "Debit routing savings calculation overflowed when converting to i64" ); 0 }); MinorUnit::new(savings_int) } pub fn get_debit_routing_savings_amount( payment_method_data: &domain::PaymentMethodData, payment_attempt: &PaymentAttempt, ) -> Option<MinorUnit> { let card_network = payment_attempt.extract_card_network()?; let saving_percentage = payment_method_data.extract_debit_routing_saving_percentage(&card_network)?; let net_amount = payment_attempt.get_total_amount().get_amount_as_i64(); Some(calculate_debit_routing_savings( net_amount, saving_percentage, )) } #[cfg(all(feature = "retry", feature = "v1"))] pub async fn get_apple_pay_retryable_connectors<F, D>( state: &SessionState, merchant_context: &domain::MerchantContext, payment_data: &D, pre_routing_connector_data_list: &[api::ConnectorRoutingData], merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>, business_profile: domain::Profile, ) -> CustomResult<Option<Vec<api::ConnectorRoutingData>>, errors::ApiErrorResponse> where F: Send + Clone, D: OperationSessionGetters<F> + Send, { let profile_id = business_profile.get_id(); let pre_decided_connector_data_first = pre_routing_connector_data_list .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?; let merchant_connector_account_type = get_merchant_connector_account( state, merchant_context.get_merchant_account().get_id(), payment_data.get_creds_identifier(), merchant_context.get_merchant_key_store(), profile_id, &pre_decided_connector_data_first .connector_data .connector_name .to_string(), merchant_connector_id, ) .await?; let connector_data_list = if is_apple_pay_simplified_flow( merchant_connector_account_type.get_metadata(), merchant_connector_account_type .get_connector_name() .as_ref(), )? { let merchant_connector_account_list = state .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( &state.into(), merchant_context.get_merchant_account().get_id(), false, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; let profile_specific_merchant_connector_account_list = merchant_connector_account_list .filter_based_on_profile_and_connector_type( profile_id, ConnectorType::PaymentProcessor, ); let mut connector_data_list = vec![pre_decided_connector_data_first.clone()]; for merchant_connector_account in profile_specific_merchant_connector_account_list { if is_apple_pay_simplified_flow( merchant_connector_account.metadata.clone(), Some(&merchant_connector_account.connector_name), )? { let routing_data: api::ConnectorRoutingData = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &merchant_connector_account.connector_name.to_string(), api::GetToken::Connector, Some(merchant_connector_account.get_id()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")? .into(); if !connector_data_list.iter().any(|connector_details| { connector_details.connector_data.merchant_connector_id == routing_data.connector_data.merchant_connector_id }) { connector_data_list.push(routing_data) } } } #[cfg(feature = "v1")] let fallback_connetors_list = crate::core::routing::helpers::get_merchant_default_config( &*state.clone().store, profile_id.get_string_repr(), &api_enums::TransactionType::Payment, ) .await .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| { routing_connector_data_list.push(pre_val.connector_data.merchant_connector_id.clone()) }); fallback_connetors_list.iter().for_each(|fallback_val| { routing_connector_data_list .iter() .all(|val| *val != fallback_val.merchant_connector_id) .then(|| { routing_connector_data_list.push(fallback_val.merchant_connector_id.clone()) }); }); // connector_data_list is the list of connectors for which Apple Pay simplified flow is configured. // This list is arranged in the same order as the merchant's connectors routingconfiguration. let mut ordered_connector_data_list = Vec::new(); routing_connector_data_list .iter() .for_each(|merchant_connector_id| { let connector_data = connector_data_list.iter().find(|connector_data| { *merchant_connector_id == connector_data.connector_data.merchant_connector_id }); if let Some(connector_data_details) = connector_data { ordered_connector_data_list.push(connector_data_details.clone()); } }); Some(ordered_connector_data_list) } else { None }; Ok(connector_data_list) } #[derive(Debug, Serialize, Deserialize)] pub struct ApplePayData { version: masking::Secret<String>, data: masking::Secret<String>, signature: masking::Secret<String>, header: ApplePayHeader, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayHeader { ephemeral_public_key: masking::Secret<String>, public_key_hash: masking::Secret<String>, transaction_id: masking::Secret<String>, } impl ApplePayData { pub fn token_json( wallet_data: domain::WalletData, ) -> CustomResult<Self, errors::ConnectorError> { let json_wallet_data: Self = connector::utils::WalletData::get_wallet_token_as_json( &wallet_data, "Apple Pay".to_string(), )?; Ok(json_wallet_data) } pub async fn decrypt( &self, payment_processing_certificate: &masking::Secret<String>, payment_processing_certificate_key: &masking::Secret<String>, ) -> CustomResult<serde_json::Value, errors::ApplePayDecryptionError> { let merchant_id = self.merchant_id(payment_processing_certificate)?; let shared_secret = self.shared_secret(payment_processing_certificate_key)?; let symmetric_key = self.symmetric_key(&merchant_id, &shared_secret)?; let decrypted = self.decrypt_ciphertext(&symmetric_key)?; let parsed_decrypted: serde_json::Value = serde_json::from_str(&decrypted) .change_context(errors::ApplePayDecryptionError::DecryptionFailed)?; Ok(parsed_decrypted) } pub fn merchant_id( &self, payment_processing_certificate: &masking::Secret<String>, ) -> CustomResult<String, errors::ApplePayDecryptionError> { let cert_data = payment_processing_certificate.clone().expose(); let base64_decode_cert_data = BASE64_ENGINE .decode(cert_data) .change_context(errors::ApplePayDecryptionError::Base64DecodingFailed)?; // Parsing the certificate using x509-parser let (_, certificate) = parse_x509_certificate(&base64_decode_cert_data) .change_context(errors::ApplePayDecryptionError::CertificateParsingFailed) .attach_printable("Error parsing apple pay PPC")?; // Finding the merchant ID extension let apple_pay_m_id = certificate .extensions() .iter() .find(|extension| { extension .oid .to_string() .eq(consts::MERCHANT_ID_FIELD_EXTENSION_ID) }) .map(|ext| { let merchant_id = String::from_utf8_lossy(ext.value) .trim() .trim_start_matches('@') .to_string(); merchant_id }) .ok_or(errors::ApplePayDecryptionError::MissingMerchantId) .attach_printable("Unable to find merchant ID extension in the certificate")?; Ok(apple_pay_m_id) } pub fn shared_secret( &self, payment_processing_certificate_key: &masking::Secret<String>, ) -> CustomResult<Vec<u8>, errors::ApplePayDecryptionError> { let public_ec_bytes = BASE64_ENGINE .decode(self.header.ephemeral_public_key.peek().as_bytes()) .change_context(errors::ApplePayDecryptionError::Base64DecodingFailed)?; let public_key = PKey::public_key_from_der(&public_ec_bytes) .change_context(errors::ApplePayDecryptionError::KeyDeserializationFailed) .attach_printable("Failed to deserialize the public key")?; let decrypted_apple_pay_ppc_key = payment_processing_certificate_key.clone().expose(); // Create PKey objects from EcKey let private_key = PKey::private_key_from_pem(decrypted_apple_pay_ppc_key.as_bytes()) .change_context(errors::ApplePayDecryptionError::KeyDeserializationFailed) .attach_printable("Failed to deserialize the private key")?; // Create the Deriver object and set the peer public key let mut deriver = Deriver::new(&private_key) .change_context(errors::ApplePayDecryptionError::DerivingSharedSecretKeyFailed) .attach_printable("Failed to create a deriver for the private key")?; deriver .set_peer(&public_key) .change_context(errors::ApplePayDecryptionError::DerivingSharedSecretKeyFailed) .attach_printable("Failed to set the peer key for the secret derivation")?; // Compute the shared secret let shared_secret = deriver .derive_to_vec() .change_context(errors::ApplePayDecryptionError::DerivingSharedSecretKeyFailed) .attach_printable("Final key derivation failed")?; Ok(shared_secret) } pub fn symmetric_key( &self, merchant_id: &str, shared_secret: &[u8], ) -> CustomResult<Vec<u8>, errors::ApplePayDecryptionError> { let kdf_algorithm = b"\x0did-aes256-GCM"; let kdf_party_v = hex::decode(merchant_id) .change_context(errors::ApplePayDecryptionError::Base64DecodingFailed)?; let kdf_party_u = b"Apple"; let kdf_info = [&kdf_algorithm[..], kdf_party_u, &kdf_party_v[..]].concat(); let mut hash = openssl::sha::Sha256::new(); hash.update(b"\x00\x00\x00"); hash.update(b"\x01"); hash.update(shared_secret); hash.update(&kdf_info[..]); let symmetric_key = hash.finish(); Ok(symmetric_key.to_vec()) } pub fn decrypt_ciphertext( &self, symmetric_key: &[u8], ) -> CustomResult<String, errors::ApplePayDecryptionError> { logger::info!("Decrypt apple pay token"); let data = BASE64_ENGINE .decode(self.data.peek().as_bytes()) .change_context(errors::ApplePayDecryptionError::Base64DecodingFailed)?; let iv = [0u8; 16]; //Initialization vector IV is typically used in AES-GCM (Galois/Counter Mode) encryption for randomizing the encryption process. let ciphertext = data .get(..data.len() - 16) .ok_or(errors::ApplePayDecryptionError::DecryptionFailed)?; let tag = data .get(data.len() - 16..) .ok_or(errors::ApplePayDecryptionError::DecryptionFailed)?; let cipher = Cipher::aes_256_gcm(); let decrypted_data = decrypt_aead(cipher, symmetric_key, Some(&iv), &[], ciphertext, tag) .change_context(errors::ApplePayDecryptionError::DecryptionFailed)?; let decrypted = String::from_utf8(decrypted_data) .change_context(errors::ApplePayDecryptionError::DecryptionFailed)?; Ok(decrypted) } } // Structs for keys and the main decryptor pub struct GooglePayTokenDecryptor { root_signing_keys: Vec<GooglePayRootSigningKey>, recipient_id: masking::Secret<String>, private_key: PKey<openssl::pkey::Private>, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct EncryptedData { signature: String, intermediate_signing_key: IntermediateSigningKey, protocol_version: GooglePayProtocolVersion, #[serde(with = "common_utils::custom_serde::json_string")] signed_message: GooglePaySignedMessage, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct GooglePaySignedMessage { #[serde(with = "common_utils::Base64Serializer")] encrypted_message: masking::Secret<Vec<u8>>, #[serde(with = "common_utils::Base64Serializer")] ephemeral_public_key: masking::Secret<Vec<u8>>, #[serde(with = "common_utils::Base64Serializer")] tag: masking::Secret<Vec<u8>>, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct IntermediateSigningKey { signed_key: masking::Secret<String>, signatures: Vec<masking::Secret<String>>, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct GooglePaySignedKey { key_value: masking::Secret<String>, key_expiration: String, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayRootSigningKey { key_value: masking::Secret<String>, key_expiration: String, protocol_version: GooglePayProtocolVersion, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)] pub enum GooglePayProtocolVersion { #[serde(rename = "ECv2")] EcProtocolVersion2, } // Check expiration date validity fn check_expiration_date_is_valid( expiration: &str, ) -> CustomResult<bool, errors::GooglePayDecryptionError> { let expiration_ms = expiration .parse::<i128>() .change_context(errors::GooglePayDecryptionError::InvalidExpirationTime)?; // convert milliseconds to nanoseconds (1 millisecond = 1_000_000 nanoseconds) to create OffsetDateTime let expiration_time = time::OffsetDateTime::from_unix_timestamp_nanos(expiration_ms * 1_000_000) .change_context(errors::GooglePayDecryptionError::InvalidExpirationTime)?; let now = time::OffsetDateTime::now_utc(); Ok(expiration_time > now) } // Construct little endian format of u32 fn get_little_endian_format(number: u32) -> Vec<u8> { number.to_le_bytes().to_vec() } // Filter and parse the root signing keys based on protocol version and expiration time fn filter_root_signing_keys( root_signing_keys: Vec<GooglePayRootSigningKey>, ) -> CustomResult<Vec<GooglePayRootSigningKey>, errors::GooglePayDecryptionError> { let filtered_root_signing_keys = root_signing_keys .iter() .filter(|key| { key.protocol_version == GooglePayProtocolVersion::EcProtocolVersion2 && matches!( check_expiration_date_is_valid(&key.key_expiration).inspect_err( |err| logger::warn!( "Failed to check expirattion due to invalid format: {:?}", err ) ), Ok(true) ) }) .cloned() .collect::<Vec<GooglePayRootSigningKey>>(); logger::info!( "Filtered {} out of {} root signing keys", filtered_root_signing_keys.len(), root_signing_keys.len() ); Ok(filtered_root_signing_keys) } impl GooglePayTokenDecryptor { pub fn new( root_keys: masking::Secret<String>, recipient_id: masking::Secret<String>, private_key: masking::Secret<String>, ) -> CustomResult<Self, errors::GooglePayDecryptionError> { // base64 decode the private key let decoded_key = BASE64_ENGINE .decode(private_key.expose()) .change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?; // base64 decode the root signing keys let decoded_root_signing_keys = BASE64_ENGINE .decode(root_keys.expose()) .change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?; // create a private key from the decoded key let private_key = PKey::private_key_from_pkcs8(&decoded_key) .change_context(errors::GooglePayDecryptionError::KeyDeserializationFailed) .attach_printable("cannot convert private key from decode_key")?; // parse the root signing keys let root_keys_vector: Vec<GooglePayRootSigningKey> = decoded_root_signing_keys .parse_struct("GooglePayRootSigningKey") .change_context(errors::GooglePayDecryptionError::DeserializationFailed)?; // parse and filter the root signing keys by protocol version let filtered_root_signing_keys = filter_root_signing_keys(root_keys_vector)?; Ok(Self { root_signing_keys: filtered_root_signing_keys, recipient_id, private_key, }) } // Decrypt the Google pay token pub fn decrypt_token( &self, data: String, should_verify_signature: bool, ) -> CustomResult< hyperswitch_domain_models::router_data::GooglePayPredecryptDataInternal, errors::GooglePayDecryptionError, > { // parse the encrypted data let encrypted_data: EncryptedData = data .parse_struct("EncryptedData") .change_context(errors::GooglePayDecryptionError::DeserializationFailed)?; // verify the signature if required if should_verify_signature { self.verify_signature(&encrypted_data)?; } let ephemeral_public_key = encrypted_data.signed_message.ephemeral_public_key.peek(); let tag = encrypted_data.signed_message.tag.peek(); let encrypted_message = encrypted_data.signed_message.encrypted_message.peek(); // derive the shared key let shared_key = self.get_shared_key(ephemeral_public_key)?; // derive the symmetric encryption key and MAC key let derived_key = self.derive_key(ephemeral_public_key, &shared_key)?; // First 32 bytes for AES-256 and Remaining bytes for HMAC let (symmetric_encryption_key, mac_key) = derived_key .split_at_checked(32) .ok_or(errors::GooglePayDecryptionError::ParsingFailed)?; // verify the HMAC of the message self.verify_hmac(mac_key, tag, encrypted_message)?; // decrypt the message let decrypted = self.decrypt_message(symmetric_encryption_key, encrypted_message)?; // parse the decrypted data let decrypted_data: hyperswitch_domain_models::router_data::GooglePayPredecryptDataInternal = decrypted .parse_struct("GooglePayPredecryptDataInternal") .change_context(errors::GooglePayDecryptionError::DeserializationFailed)?; // check the expiration date of the decrypted data if matches!( check_expiration_date_is_valid(&decrypted_data.message_expiration), Ok(true) ) { Ok(decrypted_data) } else { Err(errors::GooglePayDecryptionError::DecryptedTokenExpired.into()) } } // Verify the signature of the token fn verify_signature( &self, encrypted_data: &EncryptedData, ) -> CustomResult<(), errors::GooglePayDecryptionError> { // check the protocol version if encrypted_data.protocol_version != GooglePayProtocolVersion::EcProtocolVersion2 { return Err(errors::GooglePayDecryptionError::InvalidProtocolVersion.into()); } // verify the intermediate signing key self.verify_intermediate_signing_key(encrypted_data)?; // validate and fetch the signed key let signed_key = self.validate_signed_key(&encrypted_data.intermediate_signing_key)?; // verify the signature of the token self.verify_message_signature(encrypted_data, &signed_key) } // Verify the intermediate signing key fn verify_intermediate_signing_key( &self, encrypted_data: &EncryptedData, ) -> CustomResult<(), errors::GooglePayDecryptionError> { let mut signatrues: Vec<openssl::ecdsa::EcdsaSig> = Vec::new(); // decode and parse the signatures for signature in encrypted_data.intermediate_signing_key.signatures.iter() { let signature = BASE64_ENGINE .decode(signature.peek()) .change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?; let ecdsa_signature = openssl::ecdsa::EcdsaSig::from_der(&signature) .change_context(errors::GooglePayDecryptionError::EcdsaSignatureParsingFailed)?; signatrues.push(ecdsa_signature); } // get the sender id i.e. Google let sender_id = String::from_utf8(consts::SENDER_ID.to_vec()) .change_context(errors::GooglePayDecryptionError::DeserializationFailed)?; // construct the signed data let signed_data = self.construct_signed_data_for_intermediate_signing_key_verification( &sender_id, consts::PROTOCOL, encrypted_data.intermediate_signing_key.signed_key.peek(), )?; // check if any of the signatures are valid for any of the root signing keys for key in self.root_signing_keys.iter() { // decode and create public key let public_key = self .load_public_key(key.key_value.peek()) .change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?; // fetch the ec key from public key let ec_key = public_key .ec_key() .change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?; // hash the signed data let message_hash = openssl::sha::sha256(&signed_data); // verify if any of the signatures is valid against the given key for signature in signatrues.iter() { let result = signature.verify(&message_hash, &ec_key).change_context( errors::GooglePayDecryptionError::SignatureVerificationFailed, )?; if result { return Ok(()); } } } Err(errors::GooglePayDecryptionError::InvalidIntermediateSignature.into()) } // Construct signed data for intermediate signing key verification fn construct_signed_data_for_intermediate_signing_key_verification( &self, sender_id: &str, protocol_version: &str, signed_key: &str, ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> { let length_of_sender_id = u32::try_from(sender_id.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let length_of_protocol_version = u32::try_from(protocol_version.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let length_of_signed_key = u32::try_from(signed_key.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let mut signed_data: Vec<u8> = Vec::new(); signed_data.append(&mut get_little_endian_format(length_of_sender_id)); signed_data.append(&mut sender_id.as_bytes().to_vec()); signed_data.append(&mut get_little_endian_format(length_of_protocol_version)); signed_data.append(&mut protocol_version.as_bytes().to_vec()); signed_data.append(&mut get_little_endian_format(length_of_signed_key)); signed_data.append(&mut signed_key.as_bytes().to_vec()); Ok(signed_data) } // Validate and parse signed key fn validate_signed_key( &self, intermediate_signing_key: &IntermediateSigningKey, ) -> CustomResult<GooglePaySignedKey, errors::GooglePayDecryptionError> { let signed_key: GooglePaySignedKey = intermediate_signing_key .signed_key .clone() .expose() .parse_struct("GooglePaySignedKey") .change_context(errors::GooglePayDecryptionError::SignedKeyParsingFailure)?; if !matches!( check_expiration_date_is_valid(&signed_key.key_expiration), Ok(true) ) { return Err(errors::GooglePayDecryptionError::SignedKeyExpired)?; } Ok(signed_key) } // Verify the signed message fn verify_message_signature( &self, encrypted_data: &EncryptedData, signed_key: &GooglePaySignedKey, ) -> CustomResult<(), errors::GooglePayDecryptionError> { // create a public key from the intermediate signing key let public_key = self.load_public_key(signed_key.key_value.peek())?; // base64 decode the signature let signature = BASE64_ENGINE .decode(&encrypted_data.signature) .change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?; // parse the signature using ECDSA let ecdsa_signature = openssl::ecdsa::EcdsaSig::from_der(&signature) .change_context(errors::GooglePayDecryptionError::EcdsaSignatureFailed)?; // get the EC key from the public key let ec_key = public_key .ec_key() .change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?; // get the sender id i.e. Google let sender_id = String::from_utf8(consts::SENDER_ID.to_vec()) .change_context(errors::GooglePayDecryptionError::DeserializationFailed)?; // serialize the signed message to string let signed_message = serde_json::to_string(&encrypted_data.signed_message) .change_context(errors::GooglePayDecryptionError::SignedKeyParsingFailure)?; // construct the signed data let signed_data = self.construct_signed_data_for_signature_verification( &sender_id, consts::PROTOCOL, &signed_message, )?; // hash the signed data let message_hash = openssl::sha::sha256(&signed_data); // verify the signature let result = ecdsa_signature .verify(&message_hash, &ec_key) .change_context(errors::GooglePayDecryptionError::SignatureVerificationFailed)?; if result { Ok(()) } else { Err(errors::GooglePayDecryptionError::InvalidSignature)? } } // Fetch the public key fn load_public_key( &self, key: &str, ) -> CustomResult<PKey<openssl::pkey::Public>, errors::GooglePayDecryptionError> { // decode the base64 string let der_data = BASE64_ENGINE .decode(key) .change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?; // parse the DER-encoded data as an EC public key let ec_key = openssl::ec::EcKey::public_key_from_der(&der_data) .change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?; // wrap the EC key in a PKey (a more general-purpose public key type in OpenSSL) let public_key = PKey::from_ec_key(ec_key) .change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?; Ok(public_key) } // Construct signed data for signature verification fn construct_signed_data_for_signature_verification( &self, sender_id: &str, protocol_version: &str, signed_key: &str, ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> { let recipient_id = self.recipient_id.clone().expose(); let length_of_sender_id = u32::try_from(sender_id.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let length_of_recipient_id = u32::try_from(recipient_id.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let length_of_protocol_version = u32::try_from(protocol_version.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let length_of_signed_key = u32::try_from(signed_key.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let mut signed_data: Vec<u8> = Vec::new(); signed_data.append(&mut get_little_endian_format(length_of_sender_id)); signed_data.append(&mut sender_id.as_bytes().to_vec()); signed_data.append(&mut get_little_endian_format(length_of_recipient_id)); signed_data.append(&mut recipient_id.as_bytes().to_vec()); signed_data.append(&mut get_little_endian_format(length_of_protocol_version)); signed_data.append(&mut protocol_version.as_bytes().to_vec()); signed_data.append(&mut get_little_endian_format(length_of_signed_key)); signed_data.append(&mut signed_key.as_bytes().to_vec()); Ok(signed_data) } // Derive a shared key using ECDH fn get_shared_key( &self, ephemeral_public_key_bytes: &[u8], ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> { let group = openssl::ec::EcGroup::from_curve_name(openssl::nid::Nid::X9_62_PRIME256V1) .change_context(errors::GooglePayDecryptionError::DerivingEcGroupFailed)?; let mut big_num_context = openssl::bn::BigNumContext::new() .change_context(errors::GooglePayDecryptionError::BigNumAllocationFailed)?; let ec_key = openssl::ec::EcPoint::from_bytes( &group, ephemeral_public_key_bytes, &mut big_num_context, ) .change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?; // create an ephemeral public key from the given bytes let ephemeral_public_key = openssl::ec::EcKey::from_public_key(&group, &ec_key) .change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?; // wrap the public key in a PKey let ephemeral_pkey = PKey::from_ec_key(ephemeral_public_key) .change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?; // perform ECDH to derive the shared key let mut deriver = Deriver::new(&self.private_key) .change_context(errors::GooglePayDecryptionError::DerivingSharedSecretKeyFailed)?; deriver .set_peer(&ephemeral_pkey) .change_context(errors::GooglePayDecryptionError::DerivingSharedSecretKeyFailed)?; let shared_key = deriver .derive_to_vec() .change_context(errors::GooglePayDecryptionError::DerivingSharedSecretKeyFailed)?; Ok(shared_key) } // Derive symmetric key and MAC key using HKDF fn derive_key( &self, ephemeral_public_key_bytes: &[u8], shared_key: &[u8], ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> { // concatenate ephemeral public key and shared key let input_key_material = [ephemeral_public_key_bytes, shared_key].concat(); // initialize HKDF with SHA-256 as the hash function // Salt is not provided as per the Google Pay documentation // https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#encrypt-spec let hkdf: ::hkdf::Hkdf<sha2::Sha256> = ::hkdf::Hkdf::new(None, &input_key_material); // derive 64 bytes for the output key (symmetric encryption + MAC key) let mut output_key = vec![0u8; 64]; hkdf.expand(consts::SENDER_ID, &mut output_key) .map_err(|err| { logger::error!( "Failed to derive the shared ephemeral key for Google Pay decryption flow: {:?}", err ); report!(errors::GooglePayDecryptionError::DerivingSharedEphemeralKeyFailed) })?; Ok(output_key) } // Verify the Hmac key // https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#encrypt-spec fn verify_hmac( &self, mac_key: &[u8], tag: &[u8], encrypted_message: &[u8], ) -> CustomResult<(), errors::GooglePayDecryptionError> { let hmac_key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, mac_key); ring::hmac::verify(&hmac_key, encrypted_message, tag) .change_context(errors::GooglePayDecryptionError::HmacVerificationFailed) } // Method to decrypt the AES-GCM encrypted message fn decrypt_message( &self, symmetric_key: &[u8], encrypted_message: &[u8], ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> { //initialization vector IV is typically used in AES-GCM (Galois/Counter Mode) encryption for randomizing the encryption process. // zero iv is being passed as specified in Google Pay documentation // https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#decrypt-token let iv = [0u8; 16]; // extract the tag from the end of the encrypted message let tag = encrypted_message .get(encrypted_message.len() - 16..) .ok_or(errors::GooglePayDecryptionError::ParsingTagError)?; // decrypt the message using AES-256-CTR let cipher = Cipher::aes_256_ctr(); let decrypted_data = decrypt_aead( cipher, symmetric_key, Some(&iv), &[], encrypted_message, tag, ) .change_context(errors::GooglePayDecryptionError::DecryptionFailed)?; Ok(decrypted_data) } } pub fn decrypt_paze_token( paze_wallet_data: PazeWalletData, paze_private_key: masking::Secret<String>, paze_private_key_passphrase: masking::Secret<String>, ) -> CustomResult<serde_json::Value, errors::PazeDecryptionError> { let decoded_paze_private_key = BASE64_ENGINE .decode(paze_private_key.expose().as_bytes()) .change_context(errors::PazeDecryptionError::Base64DecodingFailed)?; let decrypted_private_key = openssl::rsa::Rsa::private_key_from_pem_passphrase( decoded_paze_private_key.as_slice(), paze_private_key_passphrase.expose().as_bytes(), ) .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?; let decrypted_private_key_pem = String::from_utf8( decrypted_private_key .private_key_to_pem() .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?, ) .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?; let decrypter = jwe::RSA_OAEP_256 .decrypter_from_pem(decrypted_private_key_pem) .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?; let paze_complete_response: Vec<&str> = paze_wallet_data .complete_response .peek() .split('.') .collect(); let encrypted_jwe_key = paze_complete_response .get(1) .ok_or(errors::PazeDecryptionError::DecryptionFailed)? .to_string(); let decoded_jwe_key = base64::engine::general_purpose::URL_SAFE_NO_PAD .decode(encrypted_jwe_key) .change_context(errors::PazeDecryptionError::Base64DecodingFailed)?; let jws_body: JwsBody = serde_json::from_slice(&decoded_jwe_key) .change_context(errors::PazeDecryptionError::DecryptionFailed)?; let (deserialized_payload, _deserialized_header) = jwe::deserialize_compact(jws_body.secured_payload.peek(), &decrypter) .change_context(errors::PazeDecryptionError::DecryptionFailed)?; let encoded_secured_payload_element = String::from_utf8(deserialized_payload) .change_context(errors::PazeDecryptionError::DecryptionFailed)? .split('.') .collect::<Vec<&str>>() .get(1) .ok_or(errors::PazeDecryptionError::DecryptionFailed)? .to_string(); let decoded_secured_payload_element = base64::engine::general_purpose::URL_SAFE_NO_PAD .decode(encoded_secured_payload_element) .change_context(errors::PazeDecryptionError::Base64DecodingFailed)?; let parsed_decrypted: serde_json::Value = serde_json::from_slice(&decoded_secured_payload_element) .change_context(errors::PazeDecryptionError::DecryptionFailed)?; Ok(parsed_decrypted) } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct JwsBody { pub payload_id: String, pub session_id: String, pub secured_payload: masking::Secret<String>, } pub fn get_key_params_for_surcharge_details( payment_method_data: &domain::PaymentMethodData, ) -> Option<( common_enums::PaymentMethod, common_enums::PaymentMethodType, Option<common_enums::CardNetwork>, )> { match payment_method_data { domain::PaymentMethodData::Card(card) => { // surcharge generated will always be same for credit as well as debit // since surcharge conditions cannot be defined on card_type Some(( common_enums::PaymentMethod::Card, common_enums::PaymentMethodType::Credit, card.card_network.clone(), )) } domain::PaymentMethodData::CardRedirect(card_redirect_data) => Some(( common_enums::PaymentMethod::CardRedirect, card_redirect_data.get_payment_method_type(), None, )), domain::PaymentMethodData::Wallet(wallet) => Some(( common_enums::PaymentMethod::Wallet, wallet.get_payment_method_type(), None, )), domain::PaymentMethodData::PayLater(pay_later) => Some(( common_enums::PaymentMethod::PayLater, pay_later.get_payment_method_type(), None, )), domain::PaymentMethodData::BankRedirect(bank_redirect) => Some(( common_enums::PaymentMethod::BankRedirect, bank_redirect.get_payment_method_type(), None, )), domain::PaymentMethodData::BankDebit(bank_debit) => Some(( common_enums::PaymentMethod::BankDebit, bank_debit.get_payment_method_type(), None, )), domain::PaymentMethodData::BankTransfer(bank_transfer) => Some(( common_enums::PaymentMethod::BankTransfer, bank_transfer.get_payment_method_type(), None, )), domain::PaymentMethodData::Crypto(crypto) => Some(( common_enums::PaymentMethod::Crypto, crypto.get_payment_method_type(), None, )), domain::PaymentMethodData::MandatePayment => None, domain::PaymentMethodData::Reward => None, domain::PaymentMethodData::RealTimePayment(real_time_payment) => Some(( common_enums::PaymentMethod::RealTimePayment, real_time_payment.get_payment_method_type(), None, )), domain::PaymentMethodData::Upi(upi_data) => Some(( common_enums::PaymentMethod::Upi, upi_data.get_payment_method_type(), None, )), domain::PaymentMethodData::Voucher(voucher) => Some(( common_enums::PaymentMethod::Voucher, voucher.get_payment_method_type(), None, )), domain::PaymentMethodData::GiftCard(gift_card) => Some(( common_enums::PaymentMethod::GiftCard, gift_card.get_payment_method_type(), None, )), domain::PaymentMethodData::OpenBanking(ob_data) => Some(( common_enums::PaymentMethod::OpenBanking, ob_data.get_payment_method_type(), None, )), domain::PaymentMethodData::MobilePayment(mobile_payment) => Some(( common_enums::PaymentMethod::MobilePayment, mobile_payment.get_payment_method_type(), None, )), domain::PaymentMethodData::CardToken(_) | domain::PaymentMethodData::NetworkToken(_) | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => None, } } pub fn validate_payment_link_request( request: &api::PaymentsRequest, ) -> Result<(), errors::ApiErrorResponse> { #[cfg(feature = "v1")] if request.confirm == Some(true) { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "cannot confirm a payment while creating a payment link".to_string(), }); } if request.return_url.is_none() { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "return_url must be sent while creating a payment link".to_string(), }); } Ok(()) } pub async fn get_gsm_record( state: &SessionState, error_code: Option<String>, error_message: Option<String>, connector_name: String, flow: String, ) -> Option<hyperswitch_domain_models::gsm::GatewayStatusMap> { let get_gsm = || async { state.store.find_gsm_rule( connector_name.clone(), flow.clone(), "sub_flow".to_string(), error_code.clone().unwrap_or_default(), // TODO: make changes in connector to get a mandatory code in case of success or error response error_message.clone().unwrap_or_default(), ) .await .map_err(|err| { if err.current_context().is_db_not_found() { logger::warn!( "GSM miss for connector - {}, flow - {}, error_code - {:?}, error_message - {:?}", connector_name, flow, error_code, error_message ); metrics::AUTO_RETRY_GSM_MISS_COUNT.add( 1, &[]); } else { metrics::AUTO_RETRY_GSM_FETCH_FAILURE_COUNT.add( 1, &[]); }; err.change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch decision from gsm") }) }; get_gsm() .await .inspect_err(|err| { // warn log should suffice here because we are not propagating this error logger::warn!(get_gsm_decision_fetch_error=?err, "error fetching gsm decision"); }) .ok() } pub async fn get_unified_translation( state: &SessionState, unified_code: String, unified_message: String, locale: String, ) -> Option<String> { let get_unified_translation = || async { state.store.find_translation( unified_code.clone(), unified_message.clone(), locale.clone(), ) .await .map_err(|err| { if err.current_context().is_db_not_found() { logger::warn!( "Translation missing for unified_code - {:?}, unified_message - {:?}, locale - {:?}", unified_code, unified_message, locale ); } err.change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch translation from unified_translations") }) }; get_unified_translation() .await .inspect_err(|err| { // warn log should suffice here because we are not propagating this error logger::warn!(get_translation_error=?err, "error fetching unified translations"); }) .ok() } pub fn validate_order_details_amount( order_details: Vec<api_models::payments::OrderDetailsWithAmount>, amount: MinorUnit, should_validate: bool, ) -> Result<(), errors::ApiErrorResponse> { if should_validate { let total_order_details_amount: MinorUnit = order_details .iter() .map(|order| order.amount * order.quantity) .sum(); if total_order_details_amount != amount { Err(errors::ApiErrorResponse::InvalidRequestData { message: "Total sum of order details doesn't match amount in payment request" .to_string(), }) } else { Ok(()) } } else { Ok(()) } } // This function validates the client secret expiry set by the merchant in the request pub fn validate_session_expiry(session_expiry: u32) -> Result<(), errors::ApiErrorResponse> { if !(consts::MIN_SESSION_EXPIRY..=consts::MAX_SESSION_EXPIRY).contains(&session_expiry) { Err(errors::ApiErrorResponse::InvalidRequestData { message: "session_expiry should be between 60(1 min) to 7890000(3 months).".to_string(), }) } else { Ok(()) } } pub fn get_recipient_id_for_open_banking( merchant_data: &AdditionalMerchantData, ) -> Result<Option<String>, errors::ApiErrorResponse> { match merchant_data { AdditionalMerchantData::OpenBankingRecipientData(data) => match data { MerchantRecipientData::ConnectorRecipientId(id) => Ok(Some(id.peek().clone())), MerchantRecipientData::AccountData(acc_data) => { let connector_recipient_id = match acc_data { MerchantAccountData::Bacs { connector_recipient_id, .. } | MerchantAccountData::Iban { connector_recipient_id, .. } | MerchantAccountData::FasterPayments { connector_recipient_id, .. } | MerchantAccountData::Sepa { connector_recipient_id, .. } | MerchantAccountData::SepaInstant { connector_recipient_id, .. } | MerchantAccountData::Elixir { connector_recipient_id, .. } | MerchantAccountData::Bankgiro { connector_recipient_id, .. } | MerchantAccountData::Plusgiro { connector_recipient_id, .. } => connector_recipient_id, }; match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Ok(Some(id.peek().clone())), Some(RecipientIdType::LockerId(id)) => Ok(Some(id.peek().clone())), _ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration { config: "recipient_id".to_string(), }), } } _ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration { config: "recipient_id".to_string(), }), }, } } pub fn get_connector_data_with_token( state: &SessionState, connector_name: String, merchant_connector_account_id: Option<id_type::MerchantConnectorAccountId>, payment_method_type: api_models::enums::PaymentMethodType, ) -> RouterResult<api::ConnectorData> { let connector_data_result = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_name.to_string(), // Default value, will be replaced by the result of decide_session_token_flow api::GetToken::Connector, merchant_connector_account_id.clone(), ); let connector_type = decide_session_token_flow( &connector_data_result?.connector, payment_method_type, connector_name.clone(), ); logger::debug!(session_token_flow=?connector_type, "Session token flow decided for payment method type: {:?}", payment_method_type); api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_name.to_string(), connector_type, merchant_connector_account_id, ) .inspect_err(|err| { logger::error!(session_token_error=?err); }) } /// Decides the session token flow based on payment method type pub fn decide_session_token_flow( connector: &hyperswitch_interfaces::connector_integration_interface::ConnectorEnum, payment_method_type: api_models::enums::PaymentMethodType, connector_name: String, ) -> api::GetToken { if connector.validate_sdk_session_token_for_payment_method(&payment_method_type) { logger::debug!( "SDK session token validation succeeded for payment_method_type {:?} in connector {} , proceeding with Connector token flow", payment_method_type, connector_name ); return api::GetToken::Connector; } match payment_method_type { api_models::enums::PaymentMethodType::ApplePay => api::GetToken::ApplePayMetadata, api_models::enums::PaymentMethodType::GooglePay => api::GetToken::GpayMetadata, api_models::enums::PaymentMethodType::Paypal => api::GetToken::PaypalSdkMetadata, api_models::enums::PaymentMethodType::SamsungPay => api::GetToken::SamsungPayMetadata, api_models::enums::PaymentMethodType::Paze => api::GetToken::PazeMetadata, _ => api::GetToken::Connector, } } // This function validates the intent fulfillment time expiry set by the merchant in the request pub fn validate_intent_fulfillment_expiry( intent_fulfillment_time: u32, ) -> Result<(), errors::ApiErrorResponse> { if !(consts::MIN_INTENT_FULFILLMENT_EXPIRY..=consts::MAX_INTENT_FULFILLMENT_EXPIRY) .contains(&intent_fulfillment_time) { Err(errors::ApiErrorResponse::InvalidRequestData { message: "intent_fulfillment_time should be between 60(1 min) to 1800(30 mins)." .to_string(), }) } else { Ok(()) } } pub fn add_connector_response_to_additional_payment_data( additional_payment_data: api_models::payments::AdditionalPaymentData, connector_response_payment_method_data: AdditionalPaymentMethodConnectorResponse, ) -> api_models::payments::AdditionalPaymentData { match ( &additional_payment_data, connector_response_payment_method_data, ) { ( api_models::payments::AdditionalPaymentData::Card(additional_card_data), AdditionalPaymentMethodConnectorResponse::Card { authentication_data, payment_checks, .. }, ) => api_models::payments::AdditionalPaymentData::Card(Box::new( api_models::payments::AdditionalCardInfo { payment_checks, authentication_data, ..*additional_card_data.clone() }, )), ( api_models::payments::AdditionalPaymentData::PayLater { .. }, AdditionalPaymentMethodConnectorResponse::PayLater { klarna_sdk: Some(KlarnaSdkResponse { payment_type }), }, ) => api_models::payments::AdditionalPaymentData::PayLater { klarna_sdk: Some(api_models::payments::KlarnaSdkPaymentMethod { payment_type }), }, _ => additional_payment_data, } } pub fn update_additional_payment_data_with_connector_response_pm_data( additional_payment_data: Option<serde_json::Value>, connector_response_pm_data: Option<AdditionalPaymentMethodConnectorResponse>, ) -> RouterResult<Option<serde_json::Value>> { let parsed_additional_payment_method_data = additional_payment_data .as_ref() .map(|payment_method_data| { payment_method_data .clone() .parse_value::<api_models::payments::AdditionalPaymentData>( "additional_payment_method_data", ) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to parse value into additional_payment_method_data")?; let additional_payment_method_data = parsed_additional_payment_method_data .zip(connector_response_pm_data) .map(|(additional_pm_data, connector_response_pm_data)| { add_connector_response_to_additional_payment_data( additional_pm_data, connector_response_pm_data, ) }); additional_payment_method_data .as_ref() .map(Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode additional pm data") } #[cfg(feature = "v2")] pub async fn get_payment_method_details_from_payment_token( state: &SessionState, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> { todo!() } #[cfg(feature = "v1")] pub async fn get_payment_method_details_from_payment_token( state: &SessionState, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> { let hyperswitch_token = if let Some(token) = payment_attempt.payment_token.clone() { 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_attempt .payment_method .to_owned() .get_required_value("payment_method")?, ); 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(), }, ))?; let token_data_result = token_data_string .clone() .parse_struct("PaymentTokenData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to deserialize hyperswitch token data"); let token_data = match token_data_result { Ok(data) => data, Err(e) => { // The purpose of this logic is backwards compatibility to support tokens // in redis that might be following the old format. if token_data_string.starts_with('{') { return Err(e); } else { storage::PaymentTokenData::temporary_generic(token_data_string) } } }; Some(token_data) } else { None }; let token = hyperswitch_token .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing hyperswitch_token")?; match token { storage::PaymentTokenData::TemporaryGeneric(generic_token) => { retrieve_payment_method_with_temporary_token( state, &generic_token.token, payment_intent, payment_attempt, key_store, None, ) .await } storage::PaymentTokenData::Temporary(generic_token) => { retrieve_payment_method_with_temporary_token( state, &generic_token.token, payment_intent, payment_attempt, key_store, None, ) .await } storage::PaymentTokenData::Permanent(card_token) => { retrieve_card_with_permanent_token_for_external_authentication( state, &card_token.token, payment_intent, None, key_store, storage_scheme, ) .await .map(|card| Some((card, enums::PaymentMethod::Card))) } storage::PaymentTokenData::PermanentCard(card_token) => { retrieve_card_with_permanent_token_for_external_authentication( state, &card_token.token, payment_intent, None, key_store, storage_scheme, ) .await .map(|card| Some((card, enums::PaymentMethod::Card))) } storage::PaymentTokenData::AuthBankDebit(auth_token) => { retrieve_payment_method_from_auth_service( state, key_store, &auth_token, payment_intent, &None, ) .await } storage::PaymentTokenData::WalletToken(_) => Ok(None), } } // This function validates the mandate_data with its setup_future_usage pub fn validate_mandate_data_and_future_usage( setup_future_usages: Option<api_enums::FutureUsage>, mandate_details_present: bool, ) -> Result<(), errors::ApiErrorResponse> { if mandate_details_present && (Some(api_enums::FutureUsage::OnSession) == setup_future_usages || setup_future_usages.is_none()) { Err(errors::ApiErrorResponse::PreconditionFailed { message: "`setup_future_usage` must be `off_session` for mandates".into(), }) } else { Ok(()) } } #[derive(Debug, Clone)] pub enum UnifiedAuthenticationServiceFlow { ClickToPayInitiate, ExternalAuthenticationInitiate { acquirer_details: Option<authentication::types::AcquirerDetails>, card: Box<hyperswitch_domain_models::payment_method_data::Card>, token: String, }, ExternalAuthenticationPostAuthenticate { authentication_id: id_type::AuthenticationId, }, } #[cfg(feature = "v1")] pub async fn decide_action_for_unified_authentication_service<F: Clone>( state: &SessionState, key_store: &domain::MerchantKeyStore, business_profile: &domain::Profile, payment_data: &mut PaymentData<F>, connector_call_type: &api::ConnectorCallType, mandate_type: Option<api_models::payments::MandateTransactionType>, ) -> RouterResult<Option<UnifiedAuthenticationServiceFlow>> { let external_authentication_flow = get_payment_external_authentication_flow_during_confirm( state, key_store, business_profile, payment_data, connector_call_type, mandate_type, ) .await?; Ok(match external_authentication_flow { Some(PaymentExternalAuthenticationFlow::PreAuthenticationFlow { acquirer_details, card, token, }) => Some( UnifiedAuthenticationServiceFlow::ExternalAuthenticationInitiate { acquirer_details, card, token, }, ), Some(PaymentExternalAuthenticationFlow::PostAuthenticationFlow { authentication_id }) => { Some( UnifiedAuthenticationServiceFlow::ExternalAuthenticationPostAuthenticate { authentication_id, }, ) } None => { if let Some(payment_method) = payment_data.payment_attempt.payment_method { if payment_method == storage_enums::PaymentMethod::Card && business_profile.is_click_to_pay_enabled && payment_data.service_details.is_some() { Some(UnifiedAuthenticationServiceFlow::ClickToPayInitiate) } else { None } } else { logger::info!( payment_method=?payment_data.payment_attempt.payment_method, click_to_pay_enabled=?business_profile.is_click_to_pay_enabled, "skipping unified authentication service call since payment conditions are not satisfied" ); None } } }) } pub enum PaymentExternalAuthenticationFlow { PreAuthenticationFlow { acquirer_details: Option<authentication::types::AcquirerDetails>, card: Box<hyperswitch_domain_models::payment_method_data::Card>, token: String, }, PostAuthenticationFlow { authentication_id: id_type::AuthenticationId, }, } #[cfg(feature = "v1")] pub async fn get_payment_external_authentication_flow_during_confirm<F: Clone>( state: &SessionState, key_store: &domain::MerchantKeyStore, business_profile: &domain::Profile, payment_data: &mut PaymentData<F>, connector_call_type: &api::ConnectorCallType, mandate_type: Option<api_models::payments::MandateTransactionType>, ) -> RouterResult<Option<PaymentExternalAuthenticationFlow>> { let authentication_id = payment_data.payment_attempt.authentication_id.clone(); let is_authentication_type_3ds = payment_data.payment_attempt.authentication_type == Some(common_enums::AuthenticationType::ThreeDs); let separate_authentication_requested = payment_data .payment_intent .request_external_three_ds_authentication .unwrap_or(false); let separate_three_ds_authentication_attempted = payment_data .payment_attempt .external_three_ds_authentication_attempted .unwrap_or(false); let connector_supports_separate_authn = authentication::utils::get_connector_data_if_separate_authn_supported(connector_call_type); logger::info!("is_pre_authn_call {:?}", authentication_id.is_none()); logger::info!( "separate_authentication_requested {:?}", separate_authentication_requested ); logger::info!( "payment connector supports external authentication: {:?}", connector_supports_separate_authn.is_some() ); let card = payment_data.payment_method_data.as_ref().and_then(|pmd| { if let domain::PaymentMethodData::Card(card) = pmd { Some(card.clone()) } else { None } }); Ok(if separate_three_ds_authentication_attempted { authentication_id.map(|authentication_id| { PaymentExternalAuthenticationFlow::PostAuthenticationFlow { authentication_id } }) } else if separate_authentication_requested && is_authentication_type_3ds && mandate_type != Some(api_models::payments::MandateTransactionType::RecurringMandateTransaction) { if let Some((connector_data, card)) = connector_supports_separate_authn.zip(card) { let token = payment_data .token .clone() .get_required_value("token") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "payment_data.token should not be None while making pre authentication call", )?; let payment_connector_mca = get_merchant_connector_account( state, &business_profile.merchant_id, None, key_store, business_profile.get_id(), connector_data.connector_name.to_string().as_str(), connector_data.merchant_connector_id.as_ref(), ) .await?; let acquirer_details = payment_connector_mca .get_metadata() .clone() .and_then(|metadata| { metadata .peek() .clone() .parse_value::<authentication::types::AcquirerDetails>("AcquirerDetails") .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "acquirer_bin and acquirer_merchant_id not found in Payment Connector's Metadata" .to_string(), }) .inspect_err(|err| { logger::error!( "Failed to parse acquirer details from Payment Connector's Metadata: {:?}", err ); }) .ok() }); Some(PaymentExternalAuthenticationFlow::PreAuthenticationFlow { card: Box::new(card), token, acquirer_details, }) } else { None } } else { None }) } pub fn get_redis_key_for_extended_card_info( merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, ) -> String { format!( "{}_{}_extended_card_info", merchant_id.get_string_repr(), payment_id.get_string_repr() ) } pub fn check_integrity_based_on_flow<T, Request>( request: &Request, payment_response_data: &Result<PaymentsResponseData, ErrorResponse>, ) -> Result<(), common_utils::errors::IntegrityCheckError> where T: FlowIntegrity, Request: GetIntegrityObject<T> + CheckIntegrity<Request, T>, { let connector_transaction_id = match payment_response_data { Ok(resp_data) => match resp_data { PaymentsResponseData::TransactionResponse { connector_response_reference_id, .. } => connector_response_reference_id, PaymentsResponseData::TransactionUnresolvedResponse { connector_response_reference_id, .. } => connector_response_reference_id, PaymentsResponseData::PreProcessingResponse { connector_response_reference_id, .. } => connector_response_reference_id, _ => &None, }, Err(_) => &None, }; request.check_integrity(request, connector_transaction_id.to_owned()) } pub async fn config_skip_saving_wallet_at_connector( db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, ) -> CustomResult<Option<Vec<storage_enums::PaymentMethodType>>, errors::ApiErrorResponse> { let config = db .find_config_by_key_unwrap_or( &merchant_id.get_skip_saving_wallet_at_connector_key(), Some("[]".to_string()), ) .await; Ok(match config { Ok(conf) => Some( serde_json::from_str::<Vec<storage_enums::PaymentMethodType>>(&conf.config) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("skip_save_wallet_at_connector config parsing failed")?, ), Err(error) => { logger::error!(?error); None } }) } #[cfg(feature = "v1")] pub async fn override_setup_future_usage_to_on_session<F, D>( db: &dyn StorageInterface, payment_data: &mut D, ) -> CustomResult<(), errors::ApiErrorResponse> where F: Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send, { if payment_data.get_payment_intent().setup_future_usage == Some(enums::FutureUsage::OffSession) { let skip_saving_wallet_at_connector_optional = config_skip_saving_wallet_at_connector( db, &payment_data.get_payment_intent().merchant_id, ) .await?; if let Some(skip_saving_wallet_at_connector) = skip_saving_wallet_at_connector_optional { if let Some(payment_method_type) = payment_data.get_payment_attempt().get_payment_method_type() { if skip_saving_wallet_at_connector.contains(&payment_method_type) { logger::debug!("Override setup_future_usage from off_session to on_session based on the merchant's skip_saving_wallet_at_connector configuration to avoid creating a connector mandate."); payment_data .set_setup_future_usage_in_payment_intent(enums::FutureUsage::OnSession); } } }; }; 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, key_store: &domain::MerchantKeyStore, connector_mandate_details: &api_models::payment_methods::CommonMandateReference, merchant_id: &id_type::MerchantId, card_network: Option<api_enums::CardNetwork>, ) -> CustomResult<(), errors::ApiErrorResponse> { let db = &*state.store; let merchant_connector_account_list = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( &state.into(), merchant_id, true, key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; let merchant_connector_account_details_hash_map: std::collections::HashMap< id_type::MerchantConnectorAccountId, domain::MerchantConnectorAccount, > = merchant_connector_account_list .iter() .map(|merchant_connector_account| { ( merchant_connector_account.get_id(), merchant_connector_account.clone(), ) }) .collect(); if let Some(payment_mandate_reference) = &connector_mandate_details.payments { let payments_map = payment_mandate_reference.0.clone(); for (migrating_merchant_connector_id, migrating_connector_mandate_details) in payments_map { match ( card_network.clone(), merchant_connector_account_details_hash_map.get(&migrating_merchant_connector_id), ) { (Some(enums::CardNetwork::Discover), Some(merchant_connector_account_details)) => { if let ("cybersource", None) = ( merchant_connector_account_details.connector_name.as_str(), migrating_connector_mandate_details .original_payment_authorized_amount .zip( migrating_connector_mandate_details .original_payment_authorized_currency, ), ) { Err(errors::ApiErrorResponse::MissingRequiredFields { field_names: vec![ "original_payment_authorized_currency", "original_payment_authorized_amount", ], }) .attach_printable(format!( "Invalid connector_mandate_details provided for connector {migrating_merchant_connector_id:?}", ))? } } (_, Some(_)) => (), (_, None) => Err(errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_connector_id", }) .attach_printable_lazy(|| { format!( "{migrating_merchant_connector_id:?} invalid merchant connector id in connector_mandate_details", ) })?, } } } else { router_env::logger::error!("payment mandate reference not found"); } Ok(()) } pub fn validate_platform_request_for_marketplace( amount: api::Amount, split_payments: Option<common_types::payments::SplitPaymentsRequest>, ) -> Result<(), errors::ApiErrorResponse> { match split_payments { Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment( stripe_split_payment, )) => match amount { api::Amount::Zero => { if stripe_split_payment .application_fees .as_ref() .map_or(MinorUnit::zero(), |amount| *amount) != MinorUnit::zero() { return Err(errors::ApiErrorResponse::InvalidDataValue { field_name: "split_payments.stripe_split_payment.application_fees", }); } } api::Amount::Value(amount) => { if stripe_split_payment .application_fees .as_ref() .map_or(MinorUnit::zero(), |amount| *amount) > amount.into() { return Err(errors::ApiErrorResponse::InvalidDataValue { field_name: "split_payments.stripe_split_payment.application_fees", }); } } }, Some(common_types::payments::SplitPaymentsRequest::AdyenSplitPayment( adyen_split_payment, )) => { let total_split_amount: i64 = adyen_split_payment .split_items .iter() .map(|split_item| { split_item .amount .unwrap_or(MinorUnit::new(0)) .get_amount_as_i64() }) .sum(); match amount { api::Amount::Zero => { if total_split_amount != 0 { return Err(errors::ApiErrorResponse::InvalidDataValue { field_name: "Sum of split amounts should be equal to the total amount", }); } } api::Amount::Value(amount) => { let i64_amount: i64 = amount.into(); if !adyen_split_payment.split_items.is_empty() && i64_amount != total_split_amount { return Err(errors::ApiErrorResponse::PreconditionFailed { message: "Sum of split amounts should be equal to the total amount" .to_string(), }); } } }; adyen_split_payment .split_items .iter() .try_for_each(|split_item| { match split_item.split_type { common_enums::AdyenSplitType::BalanceAccount => { if split_item.account.is_none() { return Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "split_payments.adyen_split_payment.split_items.account", }); } } common_enums::AdyenSplitType::Commission | enums::AdyenSplitType::Vat | enums::AdyenSplitType::TopUp => { if split_item.amount.is_none() { return Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "split_payments.adyen_split_payment.split_items.amount", }); } if let enums::AdyenSplitType::TopUp = split_item.split_type { if split_item.account.is_none() { return Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "split_payments.adyen_split_payment.split_items.account", }); } if adyen_split_payment.store.is_some() { return Err(errors::ApiErrorResponse::PreconditionFailed { message: "Topup split payment is not available via Adyen Platform" .to_string(), }); } } } enums::AdyenSplitType::AcquiringFees | enums::AdyenSplitType::PaymentFee | enums::AdyenSplitType::AdyenFees | enums::AdyenSplitType::AdyenCommission | enums::AdyenSplitType::AdyenMarkup | enums::AdyenSplitType::Interchange | enums::AdyenSplitType::SchemeFee => {} }; Ok(()) })?; } Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment( xendit_split_payment, )) => match xendit_split_payment { common_types::payments::XenditSplitRequest::MultipleSplits( xendit_multiple_split_payment, ) => { match amount { api::Amount::Zero => { let total_split_amount: i64 = xendit_multiple_split_payment .routes .iter() .map(|route| { route .flat_amount .unwrap_or(MinorUnit::new(0)) .get_amount_as_i64() }) .sum(); if total_split_amount != 0 { return Err(errors::ApiErrorResponse::InvalidDataValue { field_name: "Sum of split amounts should be equal to the total amount", }); } } api::Amount::Value(amount) => { let total_payment_amount: i64 = amount.into(); let total_split_amount: i64 = xendit_multiple_split_payment .routes .into_iter() .map(|route| { if route.flat_amount.is_none() && route.percent_amount.is_none() { Err(errors::ApiErrorResponse::InvalidRequestData { message: "Expected either split_payments.xendit_split_payment.routes.flat_amount or split_payments.xendit_split_payment.routes.percent_amount to be provided".to_string(), }) } else if route.flat_amount.is_some() && route.percent_amount.is_some(){ Err(errors::ApiErrorResponse::InvalidRequestData { message: "Expected either split_payments.xendit_split_payment.routes.flat_amount or split_payments.xendit_split_payment.routes.percent_amount, but not both".to_string(), }) } else { Ok(route .flat_amount .map(|amount| amount.get_amount_as_i64()) .or(route.percent_amount.map(|percentage| (percentage * total_payment_amount) / 100)) .unwrap_or(0)) } }) .collect::<Result<Vec<i64>, _>>()? .into_iter() .sum(); if total_payment_amount < total_split_amount { return Err(errors::ApiErrorResponse::PreconditionFailed { message: "The sum of split amounts should not exceed the total amount" .to_string(), }); } } }; } common_types::payments::XenditSplitRequest::SingleSplit(_) => (), }, None => (), } Ok(()) } pub async fn is_merchant_eligible_authentication_service( merchant_id: &id_type::MerchantId, state: &SessionState, ) -> RouterResult<bool> { let merchants_eligible_for_authentication_service = state .store .as_ref() .find_config_by_key_unwrap_or( consts::AUTHENTICATION_SERVICE_ELIGIBLE_CONFIG, Some("[]".to_string()), ) .await; let auth_eligible_array: Vec<String> = match merchants_eligible_for_authentication_service { Ok(config) => serde_json::from_str(&config.config) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to parse authentication service config")?, Err(err) => { logger::error!( "Error fetching authentication service enabled merchant config {:?}", err ); Vec::new() } }; Ok(auth_eligible_array.contains(&merchant_id.get_string_repr().to_owned())) } #[cfg(feature = "v1")] pub async fn validate_allowed_payment_method_types_request( state: &SessionState, profile_id: &id_type::ProfileId, merchant_context: &domain::MerchantContext, allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, ) -> CustomResult<(), errors::ApiErrorResponse> { if let Some(allowed_payment_method_types) = allowed_payment_method_types { let db = &*state.store; let all_connector_accounts = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( &state.into(), merchant_context.get_merchant_account().get_id(), false, merchant_context.get_merchant_key_store(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch merchant connector account for given merchant id")?; let filtered_connector_accounts = all_connector_accounts .filter_based_on_profile_and_connector_type( profile_id, ConnectorType::PaymentProcessor, ); let supporting_payment_method_types: HashSet<_> = filtered_connector_accounts .iter() .flat_map(|connector_account| { connector_account .payment_methods_enabled .clone() .unwrap_or_default() .into_iter() .map(|payment_methods_enabled| { payment_methods_enabled .parse_value::<api_models::admin::PaymentMethodsEnabled>( "payment_methods_enabled", ) }) .filter_map(|parsed_payment_method_result| { parsed_payment_method_result .inspect_err(|err| { logger::error!( "Unable to deserialize payment methods enabled: {:?}", err ); }) .ok() }) .flat_map(|parsed_payment_methods_enabled| { parsed_payment_methods_enabled .payment_method_types .unwrap_or_default() .into_iter() .map(|payment_method_type| payment_method_type.payment_method_type) }) }) .collect(); let unsupported_payment_methods: Vec<_> = allowed_payment_method_types .iter() .filter(|allowed_pmt| !supporting_payment_method_types.contains(allowed_pmt)) .collect(); if !unsupported_payment_methods.is_empty() { metrics::PAYMENT_METHOD_TYPES_MISCONFIGURATION_METRIC.add( 1, router_env::metric_attributes!(( "merchant_id", merchant_context.get_merchant_account().get_id().clone() )), ); } fp_utils::when( unsupported_payment_methods.len() == allowed_payment_method_types.len(), || { Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable(format!( "None of the allowed payment method types {allowed_payment_method_types:?} are configured for this merchant connector account.", )) }, )?; } Ok(()) } async fn get_payment_update_enabled_for_client_auth( merchant_id: &id_type::MerchantId, state: &SessionState, ) -> bool { let key = merchant_id.get_payment_update_enabled_for_client_auth_key(); let db = &*state.store; let update_enabled = db.find_config_by_key(key.as_str()).await; match update_enabled { Ok(conf) => conf.config.to_lowercase() == "true", Err(error) => { logger::error!(?error); false } } } pub async fn allow_payment_update_enabled_for_client_auth( merchant_id: &id_type::MerchantId, state: &SessionState, auth_flow: services::AuthFlow, ) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> { match auth_flow { services::AuthFlow::Client => { if get_payment_update_enabled_for_client_auth(merchant_id, state).await { Ok(()) } else { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Client auth for payment update is not enabled.") } } services::AuthFlow::Merchant => Ok(()), } } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn get_merchant_connector_account_v2( state: &SessionState, key_store: &domain::MerchantKeyStore, merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>, ) -> RouterResult<domain::MerchantConnectorAccount> { let db = &*state.store; match merchant_connector_id { Some(merchant_connector_id) => db .find_merchant_connector_account_by_id(&state.into(), merchant_connector_id, key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }), None => Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "merchant_connector_id", }) .attach_printable("merchant_connector_id is not provided"), } } pub fn is_stored_credential( recurring_details: &Option<RecurringDetails>, payment_token: &Option<String>, is_mandate: bool, is_stored_credential_prev: Option<bool>, ) -> Option<bool> { if is_stored_credential_prev == Some(true) || recurring_details.is_some() || payment_token.is_some() || is_mandate { Some(true) } else { is_stored_credential_prev } } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] // Helper function to process through UCS gateway pub async fn process_through_ucs<'a, F, RouterDReq, ApiRequest, D>( state: &'a SessionState, req_state: routes::app::ReqState, merchant_context: &'a domain::MerchantContext, operation: &'a BoxedOperation<'a, F, ApiRequest, D>, payment_data: &'a mut D, customer: &Option<domain::Customer>, validate_result: &'a OperationsValidateResult, schedule_time: Option<time::PrimitiveDateTime>, header_payload: domain_payments::HeaderPayload, frm_suggestion: Option<enums::FrmSuggestion>, business_profile: &'a domain::Profile, merchant_connector_account: MerchantConnectorAccountType, mut router_data: RouterData<F, RouterDReq, PaymentsResponseData>, ) -> RouterResult<( RouterData<F, RouterDReq, PaymentsResponseData>, MerchantConnectorAccountType, )> where F: Send + Clone + Sync + 'static, RouterDReq: Send + Sync + Clone + 'static + Serialize, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, PaymentsResponseData>, RouterData<F, RouterDReq, PaymentsResponseData>: Feature<F, RouterDReq> + Send + Clone + Serialize, dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, PaymentsResponseData>, { router_env::logger::info!( "Processing payment through UCS gateway system - payment_id={}, attempt_id={}", payment_data .get_payment_intent() .payment_id .get_string_repr(), payment_data.get_payment_attempt().attempt_id ); // Add task to process tracker if needed if should_add_task_to_process_tracker(payment_data) { operation .to_domain()? .add_task_to_process_tracker( state, payment_data.get_payment_attempt(), validate_result.requeue, schedule_time, ) .await .map_err(|error| router_env::logger::error!(process_tracker_error=?error)) .ok(); } // Update feature metadata to track UCS usage for stickiness update_gateway_system_in_feature_metadata( payment_data, GatewaySystem::UnifiedConnectorService, )?; // Update trackers (_, *payment_data) = operation .to_update_tracker()? .update_trackers( state, req_state, payment_data.clone(), customer.clone(), merchant_context.get_merchant_account().storage_scheme, None, merchant_context.get_merchant_key_store(), frm_suggestion, header_payload.clone(), ) .await?; // Call UCS let lineage_ids = grpc_client::LineageIds::new( business_profile.merchant_id.clone(), business_profile.get_id().clone(), ); router_data .call_unified_connector_service( state, &header_payload, lineage_ids, merchant_connector_account.clone(), merchant_context, ExecutionMode::Primary, // UCS is called in primary mode ) .await?; Ok((router_data, merchant_connector_account)) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] // Helper function to process through Direct gateway pub async fn process_through_direct<'a, F, RouterDReq, ApiRequest, D>( state: &'a SessionState, req_state: routes::app::ReqState, merchant_context: &'a domain::MerchantContext, connector: api::ConnectorData, operation: &'a BoxedOperation<'a, F, ApiRequest, D>, payment_data: &'a mut D, customer: &Option<domain::Customer>, call_connector_action: CallConnectorAction, validate_result: &'a OperationsValidateResult, schedule_time: Option<time::PrimitiveDateTime>, header_payload: domain_payments::HeaderPayload, frm_suggestion: Option<enums::FrmSuggestion>, business_profile: &'a domain::Profile, is_retry_payment: bool, all_keys_required: Option<bool>, merchant_connector_account: MerchantConnectorAccountType, router_data: RouterData<F, RouterDReq, PaymentsResponseData>, tokenization_action: TokenizationAction, ) -> RouterResult<( RouterData<F, RouterDReq, PaymentsResponseData>, MerchantConnectorAccountType, )> where F: Send + Clone + Sync + 'static, RouterDReq: Send + Sync + Clone + 'static + Serialize, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, PaymentsResponseData>, RouterData<F, RouterDReq, PaymentsResponseData>: Feature<F, RouterDReq> + Send + Clone + Serialize, dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, PaymentsResponseData>, { router_env::logger::info!( "Processing payment through Direct gateway system - payment_id={}, attempt_id={}", payment_data .get_payment_intent() .payment_id .get_string_repr(), payment_data.get_payment_attempt().attempt_id ); // Update feature metadata to track Direct routing usage for stickiness update_gateway_system_in_feature_metadata(payment_data, GatewaySystem::Direct)?; call_connector_service( state, req_state, merchant_context, connector, operation, payment_data, customer, call_connector_action, validate_result, schedule_time, header_payload, frm_suggestion, business_profile, is_retry_payment, all_keys_required, merchant_connector_account, router_data, tokenization_action, ) .await } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] // Helper function to process through Direct with Shadow UCS pub async fn process_through_direct_with_shadow_unified_connector_service< 'a, F, RouterDReq, ApiRequest, D, >( state: &'a SessionState, req_state: routes::app::ReqState, merchant_context: &'a domain::MerchantContext, connector: api::ConnectorData, operation: &'a BoxedOperation<'a, F, ApiRequest, D>, payment_data: &'a mut D, customer: &Option<domain::Customer>, call_connector_action: CallConnectorAction, validate_result: &'a OperationsValidateResult, schedule_time: Option<time::PrimitiveDateTime>, header_payload: domain_payments::HeaderPayload, frm_suggestion: Option<enums::FrmSuggestion>, business_profile: &'a domain::Profile, is_retry_payment: bool, all_keys_required: Option<bool>, merchant_connector_account: MerchantConnectorAccountType, router_data: RouterData<F, RouterDReq, PaymentsResponseData>, tokenization_action: TokenizationAction, ) -> RouterResult<( RouterData<F, RouterDReq, PaymentsResponseData>, MerchantConnectorAccountType, )> where F: Send + Clone + Sync + 'static, RouterDReq: Send + Sync + Clone + 'static + Serialize, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, PaymentsResponseData>, RouterData<F, RouterDReq, PaymentsResponseData>: Feature<F, RouterDReq> + Send + Clone + Serialize, dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, PaymentsResponseData>, { router_env::logger::info!( "Processing payment through Direct gateway system with UCS in shadow mode - payment_id={}, attempt_id={}", payment_data.get_payment_intent().payment_id.get_string_repr(), payment_data.get_payment_attempt().attempt_id ); // Clone data needed for shadow UCS call let unified_connector_service_router_data = router_data.clone(); let unified_connector_service_merchant_connector_account = merchant_connector_account.clone(); let unified_connector_service_merchant_context = merchant_context.clone(); let unified_connector_service_header_payload = header_payload.clone(); let unified_connector_service_state = state.clone(); let lineage_ids = grpc_client::LineageIds::new( business_profile.merchant_id.clone(), business_profile.get_id().clone(), ); // Update feature metadata to track Direct routing usage for stickiness update_gateway_system_in_feature_metadata(payment_data, GatewaySystem::Direct)?; // Call Direct connector service let result = call_connector_service( state, req_state, merchant_context, connector, operation, payment_data, customer, call_connector_action, validate_result, schedule_time, header_payload, frm_suggestion, business_profile, is_retry_payment, all_keys_required, merchant_connector_account, router_data, tokenization_action, ) .await?; // Spawn shadow UCS call in background let direct_router_data = result.0.clone(); tokio::spawn(async move { execute_shadow_unified_connector_service_call( unified_connector_service_state, unified_connector_service_router_data, direct_router_data, unified_connector_service_header_payload, lineage_ids, unified_connector_service_merchant_connector_account, unified_connector_service_merchant_context, ) .await }); Ok(result) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] // Helper function to execute shadow UCS call pub async fn execute_shadow_unified_connector_service_call<F, RouterDReq>( state: SessionState, mut unified_connector_service_router_data: RouterData<F, RouterDReq, PaymentsResponseData>, direct_router_data: RouterData<F, RouterDReq, PaymentsResponseData>, header_payload: domain_payments::HeaderPayload, lineage_ids: grpc_client::LineageIds, merchant_connector_account: MerchantConnectorAccountType, merchant_context: domain::MerchantContext, ) where F: Send + Clone + Sync + 'static, RouterDReq: Send + Sync + Clone + 'static + Serialize, RouterData<F, RouterDReq, PaymentsResponseData>: Feature<F, RouterDReq> + Send + Clone + Serialize, dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, PaymentsResponseData>, { // Call UCS in shadow mode let _unified_connector_service_result = unified_connector_service_router_data .call_unified_connector_service( &state, &header_payload, lineage_ids, merchant_connector_account, &merchant_context, ExecutionMode::Shadow, // Shadow mode for UCS ) .await .map_err(|e| router_env::logger::debug!("Shadow UCS call failed: {:?}", e)); // Compare results match serialize_router_data_and_send_to_comparison_service( &state, direct_router_data, unified_connector_service_router_data, ) .await { Ok(_) => router_env::logger::debug!("Shadow UCS comparison completed successfully"), Err(e) => router_env::logger::debug!("Shadow UCS comparison failed: {:?}", e), } } #[cfg(feature = "v1")] pub async fn serialize_router_data_and_send_to_comparison_service<F, RouterDReq>( state: &SessionState, hyperswitch_router_data: RouterData<F, RouterDReq, PaymentsResponseData>, unified_connector_service_router_data: RouterData<F, RouterDReq, PaymentsResponseData>, ) -> RouterResult<()> where F: Send + Clone + Sync + 'static, RouterDReq: Send + Sync + Clone + 'static + Serialize, { router_env::logger::info!("Simulating UCS call for shadow mode comparison"); let hyperswitch_data = match serde_json::to_value(hyperswitch_router_data) { Ok(data) => masking::Secret::new(data), Err(_) => { router_env::logger::debug!("Failed to serialize HS router data"); return Ok(()); } }; let unified_connector_service_data = match serde_json::to_value(unified_connector_service_router_data) { Ok(data) => masking::Secret::new(data), Err(_) => { router_env::logger::debug!("Failed to serialize UCS router data"); return Ok(()); } }; let comparison_data = ComparisonData { hyperswitch_data, unified_connector_service_data, }; let _ = send_comparison_data(state, comparison_data) .await .map_err(|e| { router_env::logger::debug!("Failed to send comparison data: {:?}", e); }); Ok(()) }
{ "crate": "router", "file": "crates/router/src/core/payments/helpers.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 3, "num_structs": 8, "num_tables": null, "score": null, "total_crates": null }
file_router_-7809956782993231231
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations.rs // Contains: 2 structs, 0 enums #[cfg(feature = "v1")] pub mod payment_approve; #[cfg(feature = "v1")] pub mod payment_cancel; #[cfg(feature = "v1")] pub mod payment_cancel_post_capture; #[cfg(feature = "v1")] pub mod payment_capture; #[cfg(feature = "v1")] pub mod payment_complete_authorize; #[cfg(feature = "v1")] pub mod payment_confirm; #[cfg(feature = "v1")] pub mod payment_create; #[cfg(feature = "v1")] pub mod payment_post_session_tokens; #[cfg(feature = "v1")] pub mod payment_reject; pub mod payment_response; #[cfg(feature = "v1")] pub mod payment_session; #[cfg(feature = "v2")] pub mod payment_session_intent; #[cfg(feature = "v1")] pub mod payment_start; #[cfg(feature = "v1")] pub mod payment_status; #[cfg(feature = "v1")] pub mod payment_update; #[cfg(feature = "v1")] pub mod payment_update_metadata; #[cfg(feature = "v1")] pub mod payments_extend_authorization; #[cfg(feature = "v1")] 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 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 external_vault_proxy_payment_intent; #[cfg(feature = "v2")] pub mod payment_get; #[cfg(feature = "v2")] pub mod payment_capture_v2; #[cfg(feature = "v2")] pub mod payment_cancel_v2; use api_models::enums::FrmSuggestion; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use api_models::routing::RoutableConnectorChoice; 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")] pub use self::payment_get_intent::PaymentGetIntent; pub use self::payment_response::PaymentResponse; #[cfg(feature = "v2")] pub use self::payment_update_intent::PaymentUpdateIntent; #[cfg(feature = "v1")] pub use self::{ payment_approve::PaymentApprove, payment_cancel::PaymentCancel, payment_cancel_post_capture::PaymentCancelPostCapture, payment_capture::PaymentCapture, payment_confirm::PaymentConfirm, payment_create::PaymentCreate, payment_post_session_tokens::PaymentPostSessionTokens, payment_reject::PaymentReject, payment_session::PaymentSession, payment_start::PaymentStart, payment_status::PaymentStatus, payment_update::PaymentUpdate, payment_update_metadata::PaymentUpdateMetadata, payments_extend_authorization::PaymentExtendAuthorization, payments_incremental_authorization::PaymentIncrementalAuthorization, tax_calculation::PaymentSessionUpdate, }; #[cfg(feature = "v2")] pub use self::{ payment_confirm_intent::PaymentIntentConfirm, payment_create_intent::PaymentIntentCreate, payment_session_intent::PaymentSessionIntent, }; use super::{helpers, CustomerDetails, OperationSessionGetters, OperationSessionSetters}; #[cfg(feature = "v2")] use crate::core::payments; use crate::{ core::errors::{self, CustomResult, RouterResult}, routes::{app::ReqState, SessionState}, services, types::{ self, api::{self, ConnectorCallType}, domain, storage::{self, enums}, PaymentsResponseData, }, }; pub type BoxedOperation<'a, F, T, D> = Box<dyn Operation<F, T, Data = D> + Send + Sync + 'a>; pub trait Operation<F: Clone, T>: Send + std::fmt::Debug { type Data; fn to_validate_request( &self, ) -> RouterResult<&(dyn ValidateRequest<F, T, Self::Data> + Send + Sync)> { Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| format!("validate request interface not found for {self:?}")) } fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F, Self::Data, T> + Send + Sync)> { Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| format!("get tracker interface not found for {self:?}")) } fn to_domain(&self) -> RouterResult<&dyn Domain<F, T, Self::Data>> { Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| format!("domain interface not found for {self:?}")) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, T> + Send + Sync)> { Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| format!("update tracker interface not found for {self:?}")) } fn to_post_update_tracker( &self, ) -> RouterResult<&(dyn PostUpdateTracker<F, Self::Data, T> + Send + Sync)> { Err(report!(errors::ApiErrorResponse::InternalServerError)).attach_printable_lazy(|| { format!("post connector update tracker not found for {self:?}") }) } } #[cfg(feature = "v1")] #[derive(Clone)] pub struct ValidateResult { pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: api::PaymentIdType, pub storage_scheme: enums::MerchantStorageScheme, pub requeue: bool, } #[cfg(feature = "v2")] #[derive(Clone)] pub struct ValidateResult { pub merchant_id: common_utils::id_type::MerchantId, pub storage_scheme: enums::MerchantStorageScheme, pub requeue: bool, } #[cfg(feature = "v1")] #[allow(clippy::type_complexity)] pub trait ValidateRequest<F, R, D> { fn validate_request<'b>( &'b self, request: &R, merchant_context: &domain::MerchantContext, ) -> RouterResult<(BoxedOperation<'b, F, R, D>, ValidateResult)>; } #[cfg(feature = "v2")] pub trait ValidateRequest<F, R, D> { fn validate_request( &self, request: &R, merchant_context: &domain::MerchantContext, ) -> RouterResult<ValidateResult>; } #[cfg(feature = "v2")] pub struct GetTrackerResponse<D> { pub payment_data: D, } #[cfg(feature = "v1")] pub struct GetTrackerResponse<'a, F: Clone, R, D> { pub operation: BoxedOperation<'a, F, R, D>, pub customer_details: Option<CustomerDetails>, pub payment_data: D, pub business_profile: domain::Profile, pub mandate_type: Option<api::MandateTransactionType>, } /// This trait is used to fetch / create all the tracker related information for a payment /// This functions returns the session data that is used by subsequent functions #[async_trait] pub trait GetTracker<F: Clone, D, R>: Send { #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &R, merchant_context: &domain::MerchantContext, auth_flow: services::AuthFlow, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<GetTrackerResponse<'a, F, R, D>>; #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &common_utils::id_type::GlobalPaymentId, request: &R, merchant_context: &domain::MerchantContext, profile: &domain::Profile, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<GetTrackerResponse<D>>; async fn validate_request_with_state( &self, _state: &SessionState, _request: &R, _payment_data: &mut D, _business_profile: &domain::Profile, ) -> RouterResult<()> { Ok(()) } } #[async_trait] pub trait Domain<F: Clone, R, D>: Send + Sync { #[cfg(feature = "v1")] /// This will fetch customer details, (this operation is flow specific) async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut D, request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError>; #[cfg(feature = "v2")] /// This will fetch customer details, (this operation is flow specific) async fn get_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut D, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError>; #[cfg(feature = "v2")] /// This will run the decision manager for the payment async fn run_decision_manager<'a>( &'a self, state: &SessionState, payment_data: &mut D, business_profile: &domain::Profile, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } #[allow(clippy::too_many_arguments)] async fn make_pm_data<'a>( &'a self, state: &'a SessionState, payment_data: &mut D, storage_scheme: enums::MerchantStorageScheme, merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, R, D>, Option<domain::PaymentMethodData>, Option<String>, )>; async fn add_task_to_process_tracker<'a>( &'a self, _db: &'a SessionState, _payment_attempt: &storage::PaymentAttempt, _requeue: bool, _schedule_time: Option<time::PrimitiveDateTime>, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } #[cfg(feature = "v1")] async fn get_connector<'a>( &'a self, merchant_context: &domain::MerchantContext, state: &SessionState, request: &R, payment_intent: &storage::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse>; #[cfg(feature = "v2")] async fn get_connector_from_request<'a>( &'a self, state: &SessionState, request: &R, payment_data: &mut D, ) -> CustomResult<api::ConnectorData, errors::ApiErrorResponse> { Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| "get connector for tunnel not implemented".to_string()) } #[cfg(feature = "v2")] async fn perform_routing<'a>( &'a self, merchant_context: &domain::MerchantContext, business_profile: &domain::Profile, state: &SessionState, // TODO: do not take the whole payment data here payment_data: &mut D, ) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse>; async fn populate_payment_data<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _merchant_context: &domain::MerchantContext, _business_profile: &domain::Profile, _connector_data: &api::ConnectorData, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } #[allow(clippy::too_many_arguments)] async fn call_external_three_ds_authentication_if_eligible<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _should_continue_confirm_transaction: &mut bool, _connector_call_type: &ConnectorCallType, _business_profile: &domain::Profile, _key_store: &domain::MerchantKeyStore, _mandate_type: Option<api_models::payments::MandateTransactionType>, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } #[allow(clippy::too_many_arguments)] async fn call_unified_authentication_service_if_eligible<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _should_continue_confirm_transaction: &mut bool, _connector_call_type: &ConnectorCallType, _business_profile: &domain::Profile, _key_store: &domain::MerchantKeyStore, _mandate_type: Option<api_models::payments::MandateTransactionType>, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } #[allow(clippy::too_many_arguments)] async fn payments_dynamic_tax_calculation<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _connector_call_type: &ConnectorCallType, _business_profile: &domain::Profile, _merchant_context: &domain::MerchantContext, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut D, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } async fn store_extended_card_info_temporarily<'a>( &'a self, _state: &SessionState, _payment_id: &common_utils::id_type::PaymentId, _business_profile: &domain::Profile, _payment_method_data: Option<&domain::PaymentMethodData>, ) -> CustomResult<(), errors::ApiErrorResponse> { 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(()) } // does not propagate error to not affect the payment flow // must add debugger in case of internal error #[cfg(feature = "v2")] async fn update_payment_method<'a>( &'a self, state: &SessionState, merchant_context: &domain::MerchantContext, payment_data: &mut D, ) { } /// This function is used to apply the 3DS authentication strategy async fn apply_three_ds_authentication_strategy<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _business_profile: &domain::Profile, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } /// Get connector tokenization action #[cfg(feature = "v2")] async fn get_connector_tokenization_action<'a>( &'a self, _state: &SessionState, _payment_data: &D, ) -> RouterResult<(payments::TokenizationAction)> { Ok(payments::TokenizationAction::SkipConnectorTokenization) } // #[cfg(feature = "v2")] // async fn call_connector<'a, RouterDataReq>( // &'a self, // _state: &SessionState, // _req_state: ReqState, // _merchant_context: &domain::MerchantContext, // _business_profile: &domain::Profile, // _payment_method_data: Option<&domain::PaymentMethodData>, // _connector: api::ConnectorData, // _customer: &Option<domain::Customer>, // _payment_data: &mut D, // _call_connector_action: common_enums::CallConnectorAction, // ) -> CustomResult< // hyperswitch_domain_models::router_data::RouterData<F, RouterDataReq, PaymentsResponseData>, // errors::ApiErrorResponse, // > { // // TODO: raise an error here // todo!(); // } } #[async_trait] #[allow(clippy::too_many_arguments)] pub trait UpdateTracker<F, D, Req>: Send { /// Update the tracker information with the new data from request or calculated by the operations performed after get trackers /// This will persist the SessionData ( PaymentData ) in the database /// /// In case we are calling a processor / connector, we persist all the data in the database and then call the connector async fn update_trackers<'b>( &'b self, db: &'b SessionState, req_state: ReqState, payment_data: D, customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, updated_customer: Option<storage::CustomerUpdate>, mechant_key_store: &domain::MerchantKeyStore, frm_suggestion: Option<FrmSuggestion>, header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(BoxedOperation<'b, F, Req, D>, D)> where F: 'b + Send; } #[cfg(feature = "v2")] #[async_trait] #[allow(clippy::too_many_arguments)] pub trait CallConnector<F, D, RouterDReq: Send>: Send { async fn call_connector<'b>( &'b self, db: &'b SessionState, req_state: ReqState, payment_data: D, key_store: &domain::MerchantKeyStore, call_connector_action: common_enums::CallConnectorAction, connector_data: api::ConnectorData, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<types::RouterData<F, RouterDReq, PaymentsResponseData>> where F: 'b + Send + Sync, D: super::flows::ConstructFlowSpecificData<F, RouterDReq, PaymentsResponseData>, types::RouterData<F, RouterDReq, PaymentsResponseData>: super::flows::Feature<F, RouterDReq> + Send; } #[async_trait] #[allow(clippy::too_many_arguments)] pub trait PostUpdateTracker<F, D, R: Send>: Send { /// Update the tracker information with the response from the connector /// The response from routerdata is used to update paymentdata and also persist this in the database #[cfg(feature = "v1")] async fn update_tracker<'b>( &'b self, db: &'b SessionState, payment_data: D, response: types::RouterData<F, R, PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, locale: &Option<String>, #[cfg(feature = "dynamic_routing")] routable_connector: Vec<RoutableConnectorChoice>, #[cfg(feature = "dynamic_routing")] business_profile: &domain::Profile, ) -> RouterResult<D> where F: 'b + Send + Sync; #[cfg(feature = "v2")] async fn update_tracker<'b>( &'b self, db: &'b SessionState, payment_data: D, response: types::RouterData<F, R, PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<D> where F: 'b + Send + Sync, types::RouterData<F, R, PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, R, D>; async fn save_pm_and_mandate<'b>( &self, _state: &SessionState, _resp: &types::RouterData<F, R, PaymentsResponseData>, _merchant_context: &domain::MerchantContext, _payment_data: &mut D, _business_profile: &domain::Profile, ) -> CustomResult<(), errors::ApiErrorResponse> where F: 'b + Clone + Send + Sync, { Ok(()) } } #[cfg(feature = "v1")] #[async_trait] impl< D, F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsRetrieveRequest, Data = D>, > Domain<F, api::PaymentsRetrieveRequest, D> for Op where for<'a> &'a Op: Operation<F, api::PaymentsRetrieveRequest, Data = D>, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send, { #[instrument(skip_all)] #[cfg(feature = "v1")] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut D, _request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsRetrieveRequest, D>, Option<domain::Customer>, ), errors::StorageError, > { let db = &*state.store; let customer = match payment_data.get_payment_intent().customer_id.as_ref() { None => None, Some(customer_id) => { // This function is to retrieve customer details. If the customer is deleted, it returns // customer details that contains the fields as Redacted db.find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &state.into(), customer_id, &merchant_key_store.merchant_id, merchant_key_store, storage_scheme, ) .await? } }; if let Some(email) = customer.as_ref().and_then(|inner| inner.email.clone()) { payment_data.set_email_if_not_present(email.into()); } Ok((Box::new(self), customer)) } async fn get_connector<'a>( &'a self, _merchant_context: &domain::MerchantContext, state: &SessionState, _request: &api::PaymentsRetrieveRequest, _payment_intent: &storage::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut D, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRetrieveRequest, D>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut D, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[cfg(feature = "v1")] #[async_trait] impl<D, F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsCaptureRequest, Data = D>> Domain<F, api::PaymentsCaptureRequest, D> for Op where for<'a> &'a Op: Operation<F, api::PaymentsCaptureRequest, Data = D>, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send, { #[instrument(skip_all)] #[cfg(feature = "v1")] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut D, _request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsCaptureRequest, D>, Option<domain::Customer>, ), errors::StorageError, > { let db = &*state.store; let customer = match payment_data.get_payment_intent().customer_id.as_ref() { None => None, Some(customer_id) => { db.find_customer_optional_by_customer_id_merchant_id( &state.into(), customer_id, &merchant_key_store.merchant_id, merchant_key_store, storage_scheme, ) .await? } }; if let Some(email) = customer.as_ref().and_then(|inner| inner.email.clone()) { payment_data.set_email_if_not_present(email.into()); } Ok((Box::new(self), customer)) } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn get_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsCaptureRequest, D>, Option<domain::Customer>, ), errors::StorageError, > { todo!() } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut D, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsCaptureRequest, D>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } async fn get_connector<'a>( &'a self, _merchant_context: &domain::MerchantContext, state: &SessionState, _request: &api::PaymentsCaptureRequest, _payment_intent: &storage::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut D, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[cfg(feature = "v1")] #[async_trait] impl<D, F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsCancelRequest, Data = D>> Domain<F, api::PaymentsCancelRequest, D> for Op where for<'a> &'a Op: Operation<F, api::PaymentsCancelRequest, Data = D>, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send, { #[instrument(skip_all)] #[cfg(feature = "v1")] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut D, _request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsCancelRequest, D>, Option<domain::Customer>, ), errors::StorageError, > { let db = &*state.store; let customer = match payment_data.get_payment_intent().customer_id.as_ref() { None => None, Some(customer_id) => { db.find_customer_optional_by_customer_id_merchant_id( &state.into(), customer_id, &merchant_key_store.merchant_id, merchant_key_store, storage_scheme, ) .await? } }; if let Some(email) = customer.as_ref().and_then(|inner| inner.email.clone()) { payment_data.set_email_if_not_present(email.into()); } Ok((Box::new(self), customer)) } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn get_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsCancelRequest, D>, Option<domain::Customer>, ), errors::StorageError, > { todo!() } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut D, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsCancelRequest, D>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } async fn get_connector<'a>( &'a self, _merchant_context: &domain::MerchantContext, state: &SessionState, _request: &api::PaymentsCancelRequest, _payment_intent: &storage::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut D, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[cfg(feature = "v1")] #[async_trait] impl<D, F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsRejectRequest, Data = D>> Domain<F, api::PaymentsRejectRequest, D> for Op where for<'a> &'a Op: Operation<F, api::PaymentsRejectRequest, Data = D>, { #[cfg(feature = "v1")] #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _request: Option<CustomerDetails>, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsRejectRequest, D>, Option<domain::Customer>, ), errors::StorageError, > { Ok((Box::new(self), None)) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn get_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsRejectRequest, D>, 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 D, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRejectRequest, D>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } async fn get_connector<'a>( &'a self, _merchant_context: &domain::MerchantContext, state: &SessionState, _request: &api::PaymentsRejectRequest, _payment_intent: &storage::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut D, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } /// Validate if a particular operation can be performed for the given intent status pub trait ValidateStatusForOperation { fn validate_status_for_operation( &self, intent_status: common_enums::IntentStatus, ) -> Result<(), errors::ApiErrorResponse>; } /// Should the connector be called for this operation pub trait ShouldCallConnector { fn should_call_connector( &self, intent_status: common_enums::IntentStatus, force_sync: Option<bool>, ) -> bool; }
{ "crate": "router", "file": "crates/router/src/core/payments/operations.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_router_1457827023212678738
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_status.rs // Contains: 1 structs, 0 enums use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; use error_stack::ResultExt; use router_derive::PaymentOperation; use router_env::{instrument, logger, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, payments::{ helpers, operations, types as payment_types, CustomerDetails, PaymentAddress, PaymentData, }, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ api, domain, storage::{self, enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, PaymentOperation)] #[operation(operations = "all", flow = "sync")] pub struct PaymentStatus; type PaymentStatusOperation<'b, F, R> = BoxedOperation<'b, F, R, PaymentData<F>>; impl<F: Send + Clone + Sync> Operation<F, api::PaymentsRequest> for PaymentStatus { type Data = PaymentData<F>; fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, PaymentData<F>>> { Ok(self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> + Send + Sync)> { Ok(self) } } impl<F: Send + Clone + Sync> Operation<F, api::PaymentsRequest> for &PaymentStatus { type Data = PaymentData<F>; fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, PaymentData<F>>> { Ok(*self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> + Send + Sync)> { Ok(*self) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for PaymentStatus { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( PaymentStatusOperation<'a, F, api::PaymentsRequest>, Option<domain::Customer>, ), errors::StorageError, > { helpers::create_customer_if_not_exist( state, Box::new(self), payment_data, request, &key_store.merchant_id, key_store, storage_scheme, ) .await } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentStatusOperation<'a, F, api::PaymentsRequest>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } #[instrument(skip_all)] async fn add_task_to_process_tracker<'a>( &'a self, state: &'a SessionState, payment_attempt: &storage::PaymentAttempt, requeue: bool, schedule_time: Option<time::PrimitiveDateTime>, ) -> CustomResult<(), errors::ApiErrorResponse> { helpers::add_domain_task_to_pt(self, state, payment_attempt, requeue, schedule_time).await } async fn get_connector<'a>( &'a self, _merchant_context: &domain::MerchantContext, state: &SessionState, request: &api::PaymentsRequest, _payment_intent: &storage::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, request.routing.clone()).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut PaymentData<F>, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentStatus { async fn update_trackers<'b>( &'b self, _state: &'b SessionState, req_state: ReqState, payment_data: PaymentData<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<( PaymentStatusOperation<'b, F, api::PaymentsRequest>, PaymentData<F>, )> where F: 'b + Send, { req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentStatus)) .with(payment_data.to_event()) .emit(); Ok((Box::new(self), payment_data)) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> for PaymentStatus { async fn update_trackers<'b>( &'b self, _state: &'b SessionState, req_state: ReqState, payment_data: PaymentData<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<( PaymentStatusOperation<'b, F, api::PaymentsRetrieveRequest>, PaymentData<F>, )> where F: 'b + Send, { req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentStatus)) .with(payment_data.to_event()) .emit(); Ok((Box::new(self), payment_data)) } } #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> for PaymentStatus { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &api::PaymentsRetrieveRequest, merchant_context: &domain::MerchantContext, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>, > { Box::pin(get_tracker_for_sync( payment_id, &merchant_context.clone(), state, request, self, merchant_context.get_merchant_account().storage_scheme, )) .await } } #[cfg(feature = "v2")] async fn get_tracker_for_sync< 'a, F: Send + Clone, Op: Operation<F, api::PaymentsRetrieveRequest, Data = PaymentData<F>> + 'a + Send + Sync, >( _payment_id: &api::PaymentIdType, _merchant_context: &domain::MerchantContext, _state: &SessionState, _request: &api::PaymentsRetrieveRequest, _operation: Op, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>> { todo!() } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn get_tracker_for_sync< 'a, F: Send + Clone, Op: Operation<F, api::PaymentsRetrieveRequest, Data = PaymentData<F>> + 'a + Send + Sync, >( payment_id: &api::PaymentIdType, merchant_context: &domain::MerchantContext, state: &SessionState, request: &api::PaymentsRetrieveRequest, operation: Op, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>> { let (payment_intent, mut payment_attempt, currency, amount); (payment_intent, payment_attempt) = get_payment_intent_payment_attempt( state, payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), storage_scheme, ) .await?; helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?; let payment_id = payment_attempt.payment_id.clone(); currency = payment_attempt.currency.get_required_value("currency")?; amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( state, payment_intent.shipping_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id.clone(), merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await?; let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id.clone(), merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await?; let payment_method_billing = helpers::get_address_by_id( state, payment_attempt.payment_method_billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id.clone(), merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await?; payment_attempt.encoded_data.clone_from(&request.param); let db = &*state.store; let key_manager_state = &state.into(); let attempts = match request.expand_attempts { Some(true) => { Some(db .find_attempts_by_merchant_id_payment_id(merchant_context.get_merchant_account().get_id(), &payment_id, storage_scheme) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving attempt list for, merchant_id: {:?}, payment_id: {payment_id:?}",merchant_context.get_merchant_account().get_id()) })?) }, _ => None, }; let multiple_capture_data = if payment_attempt.multiple_capture_count > Some(0) { let captures = db .find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &payment_attempt.merchant_id, &payment_attempt.payment_id, &payment_attempt.attempt_id, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving capture list for, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_context.get_merchant_account().get_id()) })?; Some(payment_types::MultipleCaptureData::new_for_sync( captures, request.expand_captures, )?) } else { None }; let refunds = db .find_refund_by_payment_id_merchant_id( &payment_id, merchant_context.get_merchant_account().get_id(), storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!( "Failed while getting refund list for, payment_id: {:?}, merchant_id: {:?}", &payment_id, merchant_context.get_merchant_account().get_id() ) })?; let authorizations = db .find_all_authorizations_by_merchant_id_payment_id( merchant_context.get_merchant_account().get_id(), &payment_id, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!( "Failed while getting authorizations list for, payment_id: {:?}, merchant_id: {:?}", &payment_id, merchant_context.get_merchant_account().get_id() ) })?; let disputes = db .find_disputes_by_merchant_id_payment_id(merchant_context.get_merchant_account().get_id(), &payment_id) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving dispute list for, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_context.get_merchant_account().get_id()) })?; let frm_response = if cfg!(feature = "frm") { db.find_fraud_check_by_payment_id(payment_id.to_owned(), merchant_context.get_merchant_account().get_id().clone()) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_context.get_merchant_account().get_id()) }) .ok() } else { None }; let contains_encoded_data = payment_attempt.encoded_data.is_some(); let creds_identifier = request .merchant_connector_details .as_ref() .map(|mcd| mcd.creds_identifier.to_owned()); request .merchant_connector_details .to_owned() .async_map(|mcd| async { helpers::insert_merchant_connector_creds_to_config( db, merchant_context.get_merchant_account().get_id(), mcd, ) .await }) .await .transpose()?; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = db .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 payment_method_info = if let Some(ref payment_method_id) = payment_attempt.payment_method_id.clone() { match db .find_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), payment_method_id, storage_scheme, ) .await { Ok(payment_method) => Some(payment_method), Err(error) => { if error.current_context().is_db_not_found() { logger::info!("Payment Method not found in db {:?}", error); None } else { Err(error) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error retrieving payment method from db")? } } } } else { None }; let merchant_id = payment_intent.merchant_id.clone(); let authentication_store = if let Some(ref authentication_id) = payment_attempt.authentication_id { let authentication = db .find_authentication_by_merchant_id_authentication_id(&merchant_id, authentication_id) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Error while fetching authentication record with authentication_id {}", authentication_id.get_string_repr() ) })?; Some( hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore { authentication, cavv: None, // marking this as None since we don't need authentication value in payment status flow }, ) } else { None }; let payment_link_data = payment_intent .payment_link_id .as_ref() .async_map(|id| crate::core::payments::get_payment_link_response_from_id(state, id)) .await .transpose()?; let payment_data = PaymentData { flow: PhantomData, payment_intent, currency, amount, email: None, mandate_id: payment_attempt .mandate_id .clone() .map(|id| api_models::payments::MandateIds { mandate_id: Some(id), mandate_reference_id: None, }), mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, address: PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ), token_data: None, confirm: Some(request.force_sync), payment_method_data: None, payment_method_token: None, payment_method_info, force_sync: Some( request.force_sync && (helpers::check_force_psync_precondition(payment_attempt.status) || contains_encoded_data), ), all_keys_required: request.all_keys_required, payment_attempt, refunds, disputes, attempts, sessions_token: vec![], card_cvc: None, creds_identifier, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data, redirect_response: None, payment_link_data, surcharge_details: None, frm_message: frm_response, incremental_authorization_details: None, authorizations, authentication: authentication_store, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, whole_connector_response: None, is_manual_retry_enabled: business_profile.is_manual_retry_enabled, is_l2_l3_enabled: business_profile.is_l2_l3_enabled, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(operation), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRetrieveRequest, PaymentData<F>> for PaymentStatus { fn validate_request<'b>( &'b self, request: &api::PaymentsRetrieveRequest, merchant_context: &domain::MerchantContext, ) -> RouterResult<( PaymentStatusOperation<'b, F, api::PaymentsRetrieveRequest>, operations::ValidateResult, )> { let request_merchant_id = request.merchant_id.as_ref(); helpers::validate_merchant_id( merchant_context.get_merchant_account().get_id(), request_merchant_id, ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "merchant_id".to_string(), expected_format: "merchant_id from merchant account".to_string(), })?; Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), payment_id: request.resource_id.clone(), storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: false, }, )) } } pub async fn get_payment_intent_payment_attempt( state: &SessionState, payment_id: &api::PaymentIdType, merchant_id: &common_utils::id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<(storage::PaymentIntent, storage::PaymentAttempt)> { let key_manager_state: KeyManagerState = state.into(); let db = &*state.store; let get_pi_pa = || async { let (pi, pa); match payment_id { api_models::payments::PaymentIdType::PaymentIntentId(ref id) => { pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, id, merchant_id, key_store, storage_scheme, ) .await?; pa = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &pi.payment_id, merchant_id, pi.active_attempt.get_id().as_str(), storage_scheme, ) .await?; } api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => { pa = db .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_id, id, storage_scheme, ) .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &pa.payment_id, merchant_id, key_store, storage_scheme, ) .await?; } api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => { pa = db .find_payment_attempt_by_attempt_id_merchant_id(id, merchant_id, storage_scheme) .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &pa.payment_id, merchant_id, key_store, storage_scheme, ) .await?; } api_models::payments::PaymentIdType::PreprocessingId(ref id) => { pa = db .find_payment_attempt_by_preprocessing_id_merchant_id( id, merchant_id, storage_scheme, ) .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &pa.payment_id, merchant_id, key_store, storage_scheme, ) .await?; } } error_stack::Result::<_, errors::StorageError>::Ok((pi, pa)) }; get_pi_pa() .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) // TODO (#7195): Add platform merchant account validation once client_secret auth is solved }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_status.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-1271735224781002084
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/tax_calculation.rs // Contains: 1 structs, 0 enums use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; use error_stack::ResultExt; use masking::PeekInterface; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payment_methods::cards::create_encrypted_data, payments::{self, helpers, operations, PaymentData, PaymentMethodChecker}, utils as core_utils, }, db::errors::ConnectorErrorExt, routes::{app::ReqState, SessionState}, services, types::{ self, api::{self, ConnectorCallType, PaymentIdTypeExt}, domain, storage::{self, enums as storage_enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, PaymentOperation)] #[operation(operations = "all", flow = "sdk_session_update")] pub struct PaymentSessionUpdate; type PaymentSessionUpdateOperation<'b, F> = BoxedOperation<'b, F, api::PaymentsDynamicTaxCalculationRequest, PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsDynamicTaxCalculationRequest> for PaymentSessionUpdate { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &api::PaymentsDynamicTaxCalculationRequest, merchant_context: &domain::MerchantContext, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult< operations::GetTrackerResponse< 'a, F, api::PaymentsDynamicTaxCalculationRequest, PaymentData<F>, >, > { let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let db = &*state.store; let key_manager_state: &KeyManagerState = &state.into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &state.into(), &payment_id, merchant_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; // TODO (#7195): Add platform merchant account validation once publishable key auth is solved helpers::validate_payment_status_against_not_allowed_statuses( payment_intent.status, &[ storage_enums::IntentStatus::Failed, storage_enums::IntentStatus::Succeeded, ], "create a session update for", )?; helpers::authenticate_client_secret(Some(request.client_secret.peek()), &payment_intent)?; let mut payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, payment_intent.active_attempt.get_id().as_str(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let currency = payment_intent.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount().into(); payment_attempt.payment_method_type = Some(request.payment_method_type); let shipping_address = helpers::get_address_by_id( state, payment_intent.shipping_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = db .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 tax_data = payments::TaxData { shipping_details: request.shipping.clone().into(), payment_method_type: request.payment_method_type, }; let payment_data = PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount, email: None, mandate_id: None, mandate_connector: None, customer_acceptance: None, token: None, token_data: None, setup_mandate: None, address: payments::PaymentAddress::new( shipping_address.as_ref().map(From::from), None, None, business_profile.use_billing_as_payment_method_billing, ), confirm: None, payment_method_data: None, payment_method_token: None, payment_method_info: None, force_sync: None, all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: None, creds_identifier: None, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, redirect_response: None, surcharge_details: None, frm_message: None, payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], authentication: None, recurring_details: None, poll_config: None, tax_data: Some(tax_data), session_id: request.session_id.clone(), service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, whole_connector_response: None, is_manual_retry_enabled: None, is_l2_l3_enabled: false, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, api::PaymentsDynamicTaxCalculationRequest, PaymentData<F>> for PaymentSessionUpdate { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut PaymentData<F>, _request: Option<payments::CustomerDetails>, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> errors::CustomResult< ( PaymentSessionUpdateOperation<'a, F>, Option<domain::Customer>, ), errors::StorageError, > { Ok((Box::new(self), None)) } async fn payments_dynamic_tax_calculation<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentData<F>, _connector_call_type: &ConnectorCallType, business_profile: &domain::Profile, merchant_context: &domain::MerchantContext, ) -> errors::CustomResult<(), errors::ApiErrorResponse> { let is_tax_connector_enabled = business_profile.get_is_tax_connector_enabled(); let skip_external_tax_calculation = payment_data .payment_intent .skip_external_tax_calculation .unwrap_or(false); if is_tax_connector_enabled && !skip_external_tax_calculation { let db = state.store.as_ref(); let key_manager_state: &KeyManagerState = &state.into(); let merchant_connector_id = business_profile .tax_connector_id .as_ref() .get_required_value("business_profile.tax_connector_id")?; #[cfg(feature = "v1")] let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, &business_profile.merchant_id, merchant_connector_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, )?; #[cfg(feature = "v2")] let mca = db .find_merchant_connector_account_by_id( key_manager_state, merchant_connector_id, key_store, ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, )?; let connector_data = api::TaxCalculateConnectorData::get_connector_by_name(&mca.connector_name)?; let router_data = core_utils::construct_payments_dynamic_tax_calculation_router_data( state, merchant_context, payment_data, &mca, ) .await?; let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::CalculateTax, types::PaymentsTaxCalculationData, types::TaxCalculationResponseData, > = connector_data.connector.get_connector_integration(); let response = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_payment_failed_response() .attach_printable("Tax connector Response Failed")?; let tax_response = response.response.map_err(|err| { errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: connector_data.connector_name.clone().to_string(), status_code: err.status_code, reason: err.reason, } })?; let payment_method_type = payment_data .tax_data .clone() .map(|tax_data| tax_data.payment_method_type) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing tax_data.payment_method_type")?; payment_data.payment_intent.tax_details = Some(diesel_models::TaxDetails { payment_method_type: Some(diesel_models::PaymentMethodTypeTax { order_tax_amount: tax_response.order_tax_amount, pmt: payment_method_type, }), default: None, }); Ok(()) } else { Ok(()) } } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut PaymentData<F>, _storage_scheme: storage_enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentSessionUpdateOperation<'a, F>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } async fn get_connector<'a>( &'a self, _merchant_context: &domain::MerchantContext, state: &SessionState, _request: &api::PaymentsDynamicTaxCalculationRequest, _payment_intent: &storage::PaymentIntent, ) -> errors::CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut PaymentData<F>, ) -> errors::CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsDynamicTaxCalculationRequest> for PaymentSessionUpdate { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, _req_state: ReqState, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(PaymentSessionUpdateOperation<'b, F>, PaymentData<F>)> where F: 'b + Send, { // For Google Pay and Apple Pay, we don’t need to call the connector again; we can directly confirm the payment after tax_calculation. So, we update the required fields in the database during the update_tracker call. if payment_data.should_update_in_update_tracker() { let shipping_address = payment_data .tax_data .clone() .map(|tax_data| tax_data.shipping_details); let key_manager_state = state.into(); let shipping_details = shipping_address .clone() .async_map(|shipping_details| { create_encrypted_data(&key_manager_state, key_store, shipping_details) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt shipping details")?; let shipping_address = helpers::create_or_update_address_for_payment_by_request( state, shipping_address.map(From::from).as_ref(), payment_data.payment_intent.shipping_address_id.as_deref(), &payment_data.payment_intent.merchant_id, payment_data.payment_intent.customer_id.as_ref(), key_store, &payment_data.payment_intent.payment_id, storage_scheme, ) .await?; let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::SessionResponseUpdate { tax_details: payment_data.payment_intent.tax_details.clone().ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("payment_intent.tax_details not found")?, shipping_address_id: shipping_address.map(|address| address.address_id), updated_by: payment_data.payment_intent.updated_by.clone(), shipping_details, }; let db = &*state.store; let payment_intent = payment_data.payment_intent.clone(); let updated_payment_intent = db .update_payment_intent( &state.into(), payment_intent, payment_intent_update, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_data.payment_intent = updated_payment_intent; Ok((Box::new(self), payment_data)) } else { Ok((Box::new(self), payment_data)) } } } impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsDynamicTaxCalculationRequest, PaymentData<F>> for PaymentSessionUpdate { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsDynamicTaxCalculationRequest, merchant_context: &'a domain::MerchantContext, ) -> RouterResult<( PaymentSessionUpdateOperation<'b, F>, operations::ValidateResult, )> { //paymentid is already generated and should be sent in the request let given_payment_id = request.payment_id.clone(); Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), payment_id: api::PaymentIdType::PaymentIntentId(given_payment_id), storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: false, }, )) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/tax_calculation.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_3896158049234897314
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_get.rs // Contains: 1 structs, 0 enums use api_models::{enums::FrmSuggestion, payments::PaymentsRetrieveRequest}; use async_trait::async_trait; use common_utils::ext_traits::AsyncExt; use error_stack::ResultExt; use hyperswitch_domain_models::payments::PaymentStatusData; use router_env::{instrument, tracing}; use super::{Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, payments::{ helpers, operations::{self, ValidateStatusForOperation}, }, }, routes::{app::ReqState, SessionState}, types::{ api::{self, ConnectorCallType}, domain::{self}, storage::{self, enums as storage_enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy)] pub struct PaymentGet; 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, ) -> Result<(), errors::ApiErrorResponse> { match intent_status { common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | 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 | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => 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::PartiallyAuthorizedAndRequiresCapture, 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(", "), }) } } } } type BoxedConfirmOperation<'b, F> = super::BoxedOperation<'b, F, PaymentsRetrieveRequest, PaymentStatusData<F>>; // TODO: change the macro to include changes for v2 // TODO: PaymentData in the macro should be an input impl<F: Send + Clone + Sync> Operation<F, PaymentsRetrieveRequest> for &PaymentGet { type Data = PaymentStatusData<F>; fn to_validate_request( &self, ) -> RouterResult<&(dyn ValidateRequest<F, PaymentsRetrieveRequest, Self::Data> + Send + Sync)> { Ok(*self) } fn to_get_tracker( &self, ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsRetrieveRequest> + Send + Sync)> { Ok(*self) } fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentsRetrieveRequest, Self::Data>)> { Ok(*self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsRetrieveRequest> + Send + Sync)> { Ok(*self) } } #[automatically_derived] impl<F: Send + Clone + Sync> Operation<F, PaymentsRetrieveRequest> for PaymentGet { type Data = PaymentStatusData<F>; fn to_validate_request( &self, ) -> RouterResult<&(dyn ValidateRequest<F, PaymentsRetrieveRequest, Self::Data> + Send + Sync)> { Ok(self) } fn to_get_tracker( &self, ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsRetrieveRequest> + Send + Sync)> { Ok(self) } fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsRetrieveRequest, Self::Data>> { Ok(self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsRetrieveRequest> + Send + Sync)> { Ok(self) } } impl<F: Send + Clone + Sync> ValidateRequest<F, PaymentsRetrieveRequest, PaymentStatusData<F>> for PaymentGet { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, _request: &PaymentsRetrieveRequest, merchant_context: &'a domain::MerchantContext, ) -> RouterResult<operations::ValidateResult> { let validate_result = operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: false, }; Ok(validate_result) } } #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentStatusData<F>, PaymentsRetrieveRequest> for PaymentGet { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &common_utils::id_type::GlobalPaymentId, request: &PaymentsRetrieveRequest, merchant_context: &domain::MerchantContext, _profile: &domain::Profile, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<operations::GetTrackerResponse<PaymentStatusData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_intent = db .find_payment_intent_by_id( key_manager_state, payment_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; 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 mut payment_attempt = db .find_payment_attempt_by_id( key_manager_state, merchant_context.get_merchant_key_store(), active_attempt_id, storage_scheme, ) .await .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(); // We need the address here to send it in the response let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new( payment_intent .shipping_address .clone() .map(|address| address.into_inner()), payment_intent .billing_address .clone() .map(|address| address.into_inner()), payment_attempt .payment_method_billing_address .clone() .map(|address| address.into_inner()), Some(true), ); let attempts = match request.expand_attempts { true => payment_intent .active_attempt_id .as_ref() .async_map(|active_attempt| async { db.find_payment_attempts_by_payment_intent_id( key_manager_state, payment_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not find payment attempts for the given the intent id") }) .await .transpose()?, false => None, }; let merchant_connector_details = request.merchant_connector_details.clone(); let payment_data = PaymentStatusData { flow: std::marker::PhantomData, payment_intent, payment_attempt, payment_address, attempts, should_sync_with_connector, merchant_connector_details, }; let get_trackers_response = operations::GetTrackerResponse { payment_data }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, PaymentsRetrieveRequest, PaymentStatusData<F>> for PaymentGet { async fn get_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentStatusData<F>, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<(BoxedConfirmOperation<'a, F>, Option<domain::Customer>), errors::StorageError> { match payment_data.payment_intent.customer_id.clone() { Some(id) => { let customer = state .store .find_customer_by_global_id( &state.into(), &id, merchant_key_store, storage_scheme, ) .await?; Ok((Box::new(self), Some(customer))) } None => Ok((Box::new(self), None)), } } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut PaymentStatusData<F>, _storage_scheme: storage_enums::MerchantStorageScheme, _key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( BoxedConfirmOperation<'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, // TODO: do not take the whole payment data here payment_data: &mut PaymentStatusData<F>, ) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse> { let payment_attempt = &payment_data.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 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")?; 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) } } #[cfg(feature = "v2")] async fn get_connector_from_request<'a>( &'a self, state: &SessionState, request: &PaymentsRetrieveRequest, payment_data: &mut PaymentStatusData<F>, ) -> CustomResult<api::ConnectorData, errors::ApiErrorResponse> { use crate::core::payments::OperationSessionSetters; let connector_data = helpers::get_connector_data_from_request( state, request.merchant_connector_details.clone(), ) .await?; payment_data .set_connector_in_payment_attempt(Some(connector_data.connector_name.to_string())); Ok(connector_data) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentStatusData<F>, PaymentsRetrieveRequest> for PaymentGet { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, _state: &'b SessionState, _req_state: ReqState, payment_data: PaymentStatusData<F>, _customer: Option<domain::Customer>, _storage_scheme: storage_enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, _key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(BoxedConfirmOperation<'b, F>, PaymentStatusData<F>)> where F: 'b + Send, { Ok((Box::new(self), payment_data)) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_get.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-8657459320152767626
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_confirm_intent.rs // Contains: 1 structs, 0 enums use api_models::{enums::FrmSuggestion, payments::PaymentsConfirmIntentRequest}; use async_trait::async_trait; use common_utils::{ext_traits::Encode, fp_utils::when, id_type, types::keymanager::ToEncryptable}; use error_stack::ResultExt; use hyperswitch_domain_models::payments::PaymentConfirmData; use hyperswitch_interfaces::api::ConnectorSpecifications; use masking::{ExposeOptionInterface, PeekInterface}; use router_env::{instrument, tracing}; use super::{Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ admin, errors::{self, CustomResult, RouterResult, StorageErrorExt}, payment_methods, payments::{ self, call_decision_manager, helpers, operations::{self, ValidateStatusForOperation}, populate_surcharge_details, CustomerDetails, OperationSessionSetters, PaymentAddress, PaymentData, }, utils as core_utils, }, routes::{app::ReqState, SessionState}, services::{self, connector_integration_interface::ConnectorEnum}, types::{ self, api::{self, ConnectorCallType, PaymentIdTypeExt}, domain::{self, types as domain_types}, storage::{self, enums as storage_enums}, }, utils::{self, OptionExt}, }; #[derive(Debug, Clone, Copy)] pub struct PaymentIntentConfirm; impl ValidateStatusForOperation for PaymentIntentConfirm { /// 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, ) -> Result<(), errors::ApiErrorResponse> { match intent_status { common_enums::IntentStatus::RequiresPaymentMethod => Ok(()), common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Processing | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::Expired => { Err(errors::ApiErrorResponse::PaymentUnexpectedState { current_flow: format!("{self:?}"), field_name: "status".to_string(), current_value: intent_status.to_string(), states: ["requires_payment_method".to_string()].join(", "), }) } } } } type BoxedConfirmOperation<'b, F> = super::BoxedOperation<'b, F, PaymentsConfirmIntentRequest, PaymentConfirmData<F>>; // TODO: change the macro to include changes for v2 // TODO: PaymentData in the macro should be an input impl<F: Send + Clone + Sync> Operation<F, PaymentsConfirmIntentRequest> for &PaymentIntentConfirm { type Data = PaymentConfirmData<F>; fn to_validate_request( &self, ) -> RouterResult< &(dyn ValidateRequest<F, PaymentsConfirmIntentRequest, Self::Data> + Send + Sync), > { Ok(*self) } fn to_get_tracker( &self, ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsConfirmIntentRequest> + Send + Sync)> { Ok(*self) } fn to_domain( &self, ) -> RouterResult<&(dyn Domain<F, PaymentsConfirmIntentRequest, Self::Data>)> { Ok(*self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsConfirmIntentRequest> + Send + Sync)> { Ok(*self) } } #[automatically_derived] impl<F: Send + Clone + Sync> Operation<F, PaymentsConfirmIntentRequest> for PaymentIntentConfirm { type Data = PaymentConfirmData<F>; fn to_validate_request( &self, ) -> RouterResult< &(dyn ValidateRequest<F, PaymentsConfirmIntentRequest, Self::Data> + Send + Sync), > { Ok(self) } fn to_get_tracker( &self, ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsConfirmIntentRequest> + Send + Sync)> { Ok(self) } fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsConfirmIntentRequest, Self::Data>> { Ok(self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsConfirmIntentRequest> + Send + Sync)> { Ok(self) } } impl<F: Send + Clone + Sync> ValidateRequest<F, PaymentsConfirmIntentRequest, PaymentConfirmData<F>> for PaymentIntentConfirm { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &PaymentsConfirmIntentRequest, merchant_context: &'a domain::MerchantContext, ) -> RouterResult<operations::ValidateResult> { let validate_result = operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: false, }; Ok(validate_result) } } #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, PaymentsConfirmIntentRequest> for PaymentIntentConfirm { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &id_type::GlobalPaymentId, request: &PaymentsConfirmIntentRequest, merchant_context: &domain::MerchantContext, profile: &domain::Profile, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<operations::GetTrackerResponse<PaymentConfirmData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_intent = db .find_payment_intent_by_id( key_manager_state, payment_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; // TODO (#7195): Add platform merchant account validation once publishable key auth is solved self.validate_status_for_operation(payment_intent.status)?; let cell_id = state.conf.cell_information.id.clone(); let batch_encrypted_data = domain_types::crypto_operation( key_manager_state, common_utils::type_name!(hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt), domain_types::CryptoOperation::BatchEncrypt( hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::to_encryptable( hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt { payment_method_billing_address: request.payment_method_data.billing.as_ref().map(|address| address.clone().encode_to_value()).transpose().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to encode payment_method_billing address")?.map(masking::Secret::new), }, ), ), common_utils::types::keymanager::Identifier::Merchant(merchant_context.get_merchant_account().get_id().to_owned()), merchant_context.get_merchant_key_store().key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting payment intent details".to_string())?; let encrypted_data = hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::from_encryptable(batch_encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting payment intent details")?; let payment_attempt_domain_model = hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt::create_domain_model( &payment_intent, cell_id, storage_scheme, request, encrypted_data ) .await?; let payment_attempt: hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt = db.insert_payment_attempt( key_manager_state, merchant_context.get_merchant_key_store(), payment_attempt_domain_model, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not insert payment attempt")?; let payment_method_data = request .payment_method_data .payment_method_data .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 .clone() .map(|address| address.into_inner()), payment_intent .billing_address .clone() .map(|address| address.into_inner()), payment_attempt .payment_method_billing_address .clone() .map(|address| address.into_inner()), Some(true), ); let merchant_connector_details = request.merchant_connector_details.clone(); let payment_data = PaymentConfirmData { flow: std::marker::PhantomData, payment_intent, payment_attempt, payment_method_data, payment_address, mandate_data: None, payment_method: None, merchant_connector_details, external_vault_pmd: None, webhook_url: request .webhook_url .as_ref() .map(|url| url.get_string_repr().to_string()), }; let get_trackers_response = operations::GetTrackerResponse { payment_data }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, PaymentsConfirmIntentRequest, PaymentConfirmData<F>> for PaymentIntentConfirm { async fn get_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentConfirmData<F>, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<(BoxedConfirmOperation<'a, F>, Option<domain::Customer>), errors::StorageError> { match payment_data.payment_intent.customer_id.clone() { Some(id) => { let customer = state .store .find_customer_by_global_id( &state.into(), &id, merchant_key_store, storage_scheme, ) .await?; Ok((Box::new(self), Some(customer))) } None => Ok((Box::new(self), None)), } } async fn run_decision_manager<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentConfirmData<F>, business_profile: &domain::Profile, ) -> CustomResult<(), errors::ApiErrorResponse> { let authentication_type = payment_data.payment_intent.authentication_type; let authentication_type = match business_profile.three_ds_decision_manager_config.as_ref() { Some(three_ds_decision_manager_config) => call_decision_manager( state, three_ds_decision_manager_config.clone(), payment_data, )?, None => authentication_type, }; if let Some(auth_type) = authentication_type { payment_data.payment_attempt.authentication_type = auth_type; } Ok(()) } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, state: &'a SessionState, payment_data: &mut PaymentConfirmData<F>, storage_scheme: storage_enums::MerchantStorageScheme, key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( BoxedConfirmOperation<'a, F>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } #[cfg(feature = "v2")] async fn perform_routing<'a>( &'a self, merchant_context: &domain::MerchantContext, business_profile: &domain::Profile, state: &SessionState, payment_data: &mut PaymentConfirmData<F>, ) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse> { payments::connector_selection( state, merchant_context, business_profile, payment_data, None, ) .await } #[instrument(skip_all)] async fn populate_payment_data<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentConfirmData<F>, _merchant_context: &domain::MerchantContext, business_profile: &domain::Profile, connector_data: &api::ConnectorData, ) -> CustomResult<(), errors::ApiErrorResponse> { let connector_request_reference_id = connector_data .connector .generate_connector_request_reference_id( &payment_data.payment_intent, &payment_data.payment_attempt, ); payment_data.set_connector_request_reference_id(Some(connector_request_reference_id)); 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 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", }) .or( payment_methods::vault::retrieve_and_delete_cvc_from_payment_token( state, payment_token, payment_data.payment_attempt.payment_method_type, merchant_context.get_merchant_key_store().key.get_inner(), ) .await, ) .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) = Box::pin(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(()) } #[cfg(feature = "v2")] async fn get_connector_from_request<'a>( &'a self, state: &SessionState, request: &PaymentsConfirmIntentRequest, payment_data: &mut PaymentConfirmData<F>, ) -> CustomResult<api::ConnectorData, errors::ApiErrorResponse> { let connector_data = helpers::get_connector_data_from_request( state, request.merchant_connector_details.clone(), ) .await?; payment_data .set_connector_in_payment_attempt(Some(connector_data.connector_name.to_string())); Ok(connector_data) } async fn get_connector_tokenization_action<'a>( &'a self, state: &SessionState, payment_data: &PaymentConfirmData<F>, ) -> RouterResult<payments::TokenizationAction> { let connector = payment_data.payment_attempt.connector.to_owned(); let is_connector_mandate_flow = payment_data .mandate_data .as_ref() .and_then(|mandate_details| mandate_details.mandate_reference_id.as_ref()) .map(|mandate_reference| match mandate_reference { api_models::payments::MandateReferenceId::ConnectorMandateId(_) => true, api_models::payments::MandateReferenceId::NetworkMandateId(_) | api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_) => false, }) .unwrap_or(false); let tokenization_action = match connector { Some(_) if is_connector_mandate_flow => { payments::TokenizationAction::SkipConnectorTokenization } Some(connector) => { let payment_method = payment_data .payment_attempt .get_payment_method() .ok_or_else(|| errors::ApiErrorResponse::InternalServerError) .attach_printable("Payment method not found")?; let payment_method_type: Option<common_enums::PaymentMethodType> = payment_data.payment_attempt.get_payment_method_type(); let mandate_flow_enabled = payment_data.payment_intent.setup_future_usage; let is_connector_tokenization_enabled = payments::is_payment_method_tokenization_enabled_for_connector( state, &connector, payment_method, payment_method_type, mandate_flow_enabled, )?; if is_connector_tokenization_enabled { payments::TokenizationAction::TokenizeInConnector } else { payments::TokenizationAction::SkipConnectorTokenization } } None => payments::TokenizationAction::SkipConnectorTokenization, }; Ok(tokenization_action) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentConfirmData<F>, PaymentsConfirmIntentRequest> for PaymentIntentConfirm { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, req_state: ReqState, mut payment_data: PaymentConfirmData<F>, customer: Option<domain::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, frm_suggestion: Option<FrmSuggestion>, header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(BoxedConfirmOperation<'b, F>, PaymentConfirmData<F>)> where F: 'b + Send, { let db = &*state.store; let key_manager_state = &state.into(); let intent_status = common_enums::IntentStatus::Processing; let attempt_status = common_enums::AttemptStatus::Pending; let connector = payment_data .payment_attempt .connector .clone() .get_required_value("connector") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Connector is none when constructing response")?; // If `merchant_connector_details` are present in the payment request, `merchant_connector_id` will not be populated. let merchant_connector_id = match &payment_data.merchant_connector_details { Some(_details) => None, None => Some( payment_data .payment_attempt .merchant_connector_id .clone() .get_required_value("merchant_connector_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Merchant connector id is none when constructing response")?, ), }; let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::ConfirmIntent { status: intent_status, updated_by: storage_scheme.to_string(), active_attempt_id: Some(payment_data.payment_attempt.id.clone()), }; let authentication_type = payment_data.payment_attempt.authentication_type; let connector_request_reference_id = payment_data .payment_attempt .connector_request_reference_id .clone(); // Updates payment_attempt for cases where authorize flow is not performed. let connector_response_reference_id = payment_data .payment_attempt .connector_response_reference_id .clone(); let payment_attempt_update = match &payment_data.payment_method { // In the case of a tokenized payment method, we update the payment attempt with the tokenized payment method details. Some(payment_method) => { hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ConfirmIntentTokenized { status: attempt_status, updated_by: storage_scheme.to_string(), connector, merchant_connector_id: merchant_connector_id.ok_or_else( || { error_stack::report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Merchant connector id is none when constructing response") })?, authentication_type, connector_request_reference_id, 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, connector_request_reference_id, connector_response_reference_id, } } }; let updated_payment_intent = db .update_payment_intent( key_manager_state, payment_data.payment_intent.clone(), payment_intent_update, key_store, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment intent")?; payment_data.payment_intent = updated_payment_intent; let updated_payment_attempt = db .update_payment_attempt( key_manager_state, key_store, payment_data.payment_attempt.clone(), payment_attempt_update, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment attempt")?; payment_data.payment_attempt = updated_payment_attempt; if let Some((customer, updated_customer)) = customer.zip(updated_customer) { let customer_id = customer.get_id().clone(); let customer_merchant_id = customer.merchant_id.clone(); let _updated_customer = db .update_customer_by_global_id( key_manager_state, &customer_id, customer, updated_customer, key_store, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update customer during `update_trackers`")?; } Ok((Box::new(self), payment_data)) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_confirm_intent.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_3278992756569434969
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payments_incremental_authorization.rs // Contains: 1 structs, 0 enums use std::marker::PhantomData; use api_models::{enums::FrmSuggestion, payments::PaymentsIncrementalAuthorizationRequest}; use async_trait::async_trait; use common_utils::errors::CustomResult; use diesel_models::authorization::AuthorizationNew; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{ self, helpers, operations, CustomerDetails, IncrementalAuthorizationDetails, PaymentAddress, }, }, routes::{app::ReqState, SessionState}, services, types::{ api::{self, PaymentIdTypeExt}, domain, storage::{self, enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, router_derive::PaymentOperation)] #[operation(operations = "all", flow = "incremental_authorization")] pub struct PaymentIncrementalAuthorization; type PaymentIncrementalAuthorizationOperation<'b, F> = BoxedOperation<'b, F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, PaymentsIncrementalAuthorizationRequest> for PaymentIncrementalAuthorization { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &PaymentsIncrementalAuthorizationRequest, merchant_context: &domain::MerchantContext, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult< operations::GetTrackerResponse< 'a, F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>, >, > { let db = &*state.store; let key_manager_state = &state.into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &state.into(), &payment_id, merchant_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; helpers::validate_payment_status_against_allowed_statuses( payment_intent.status, &[enums::IntentStatus::RequiresCapture], "increment authorization", )?; if payment_intent.incremental_authorization_allowed != Some(true) { Err(errors::ApiErrorResponse::PreconditionFailed { message: "You cannot increment authorization this payment because it is not allowed for incremental_authorization".to_owned(), })? } let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, attempt_id.clone().as_str(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; // Incremental authorization should be performed on an amount greater than the original authorized amount (in this case, greater than the net_amount which is sent for authorization) // request.amount is the total amount that should be authorized in incremental authorization which should be greater than the original authorized amount if payment_attempt.get_total_amount() >= request.amount { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Amount should be greater than original authorized amount".to_owned(), })? } let currency = payment_attempt.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount(); let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; 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 payment_data = payments::PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount: amount.into(), email: None, mandate_id: None, mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, token_data: None, address: PaymentAddress::new(None, None, None, None), confirm: None, payment_method_data: None, payment_method_token: None, payment_method_info: None, force_sync: None, all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: None, creds_identifier: None, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, redirect_response: None, surcharge_details: None, frm_message: None, payment_link_data: None, incremental_authorization_details: Some(IncrementalAuthorizationDetails { additional_amount: request.amount - amount, total_amount: request.amount, reason: request.reason.clone(), authorization_id: None, }), authorizations: vec![], authentication: None, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, whole_connector_response: None, is_manual_retry_enabled: None, is_l2_l3_enabled: false, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, payments::PaymentData<F>, PaymentsIncrementalAuthorizationRequest> for PaymentIncrementalAuthorization { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, _req_state: ReqState, mut payment_data: payments::PaymentData<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<( PaymentIncrementalAuthorizationOperation<'b, F>, payments::PaymentData<F>, )> where F: 'b + Send, { let new_authorization_count = payment_data .payment_intent .authorization_count .map(|count| count + 1) .unwrap_or(1); // Create new authorization record let authorization_new = AuthorizationNew { authorization_id: format!( "{}_{}", common_utils::generate_id_with_default_len("auth"), new_authorization_count ), merchant_id: payment_data.payment_intent.merchant_id.clone(), payment_id: payment_data.payment_intent.payment_id.clone(), amount: payment_data .incremental_authorization_details .clone() .map(|details| details.total_amount) .ok_or( report!(errors::ApiErrorResponse::InternalServerError).attach_printable( "missing incremental_authorization_details in payment_data", ), )?, status: common_enums::AuthorizationStatus::Processing, error_code: None, error_message: None, connector_authorization_id: None, previously_authorized_amount: payment_data.payment_attempt.get_total_amount(), }; let authorization = state .store .insert_authorization(authorization_new.clone()) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: format!( "Authorization with authorization_id {} already exists", authorization_new.authorization_id ), }) .attach_printable("failed while inserting new authorization")?; // Update authorization_count in payment_intent payment_data.payment_intent = state .store .update_payment_intent( &state.into(), payment_data.payment_intent.clone(), storage::PaymentIntentUpdate::AuthorizationCountUpdate { authorization_count: new_authorization_count, }, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Failed to update authorization_count in Payment Intent")?; match &payment_data.incremental_authorization_details { Some(details) => { payment_data.incremental_authorization_details = Some(IncrementalAuthorizationDetails { authorization_id: Some(authorization.authorization_id), ..details.clone() }); } None => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing incremental_authorization_details in payment_data")?, } Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>> for PaymentIncrementalAuthorization { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &PaymentsIncrementalAuthorizationRequest, merchant_context: &'a domain::MerchantContext, ) -> RouterResult<( PaymentIncrementalAuthorizationOperation<'b, F>, operations::ValidateResult, )> { Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()), storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: false, }, )) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>> for PaymentIncrementalAuthorization { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut payments::PaymentData<F>, _request: Option<CustomerDetails>, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation< 'a, F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<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::PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentIncrementalAuthorizationOperation<'a, F>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } async fn get_connector<'a>( &'a self, _merchant_context: &domain::MerchantContext, state: &SessionState, _request: &PaymentsIncrementalAuthorizationRequest, _payment_intent: &storage::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut payments::PaymentData<F>, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payments_incremental_authorization.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-5857375991359310413
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_reject.rs // Contains: 1 structs, 0 enums use std::marker::PhantomData; use api_models::{enums::FrmSuggestion, payments::PaymentsCancelRequest}; use async_trait::async_trait; use error_stack::ResultExt; use router_derive; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{helpers, operations, PaymentAddress, PaymentData}, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ api::{self, PaymentIdTypeExt}, domain, storage::{self, enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, router_derive::PaymentOperation)] #[operation(operations = "all", flow = "cancel")] pub struct PaymentReject; type PaymentRejectOperation<'b, F> = BoxedOperation<'b, F, PaymentsCancelRequest, PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for PaymentReject { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, _request: &PaymentsCancelRequest, merchant_context: &domain::MerchantContext, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsCancelRequest, PaymentData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, merchant_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; helpers::validate_payment_status_against_not_allowed_statuses( payment_intent.status, &[ enums::IntentStatus::Cancelled, enums::IntentStatus::Failed, enums::IntentStatus::Succeeded, enums::IntentStatus::Processing, ], "reject", )?; let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, attempt_id.clone().as_str(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let shipping_address = helpers::get_address_by_id( state, payment_intent.shipping_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let payment_method_billing = helpers::get_address_by_id( state, payment_attempt.payment_method_billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let currency = payment_attempt.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount().into(); let frm_response = if cfg!(feature = "frm") { db.find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_context.get_merchant_account().get_id().clone()) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {attempt_id}", merchant_context.get_merchant_account().get_id()) }) .ok() } else { None }; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; 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 payment_data = PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount, email: None, mandate_id: None, mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, address: PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ), token_data: None, confirm: None, payment_method_data: None, payment_method_token: None, payment_method_info: None, force_sync: None, all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: None, creds_identifier: None, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, redirect_response: None, surcharge_details: None, frm_message: frm_response, payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], authentication: None, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, whole_connector_response: None, is_manual_retry_enabled: None, is_l2_l3_enabled: false, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, PaymentsCancelRequest> for PaymentReject { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, req_state: ReqState, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, _should_decline_transaction: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(PaymentRejectOperation<'b, F>, PaymentData<F>)> where F: 'b + Send, { let intent_status_update = storage::PaymentIntentUpdate::RejectUpdate { status: enums::IntentStatus::Failed, merchant_decision: Some(enums::MerchantDecision::Rejected.to_string()), updated_by: storage_scheme.to_string(), }; let (error_code, error_message) = payment_data .frm_message .clone() .map_or((None, None), |fraud_check| { ( Some(Some(fraud_check.frm_status.to_string())), Some(fraud_check.frm_reason.map(|reason| reason.to_string())), ) }); let attempt_status_update = storage::PaymentAttemptUpdate::RejectUpdate { status: enums::AttemptStatus::Failure, error_code, error_message, updated_by: storage_scheme.to_string(), }; payment_data.payment_intent = state .store .update_payment_intent( &state.into(), payment_data.payment_intent, intent_status_update, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_data.payment_attempt = state .store .update_payment_attempt_with_attempt_id( payment_data.payment_attempt.clone(), attempt_status_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let error_code = payment_data.payment_attempt.error_code.clone(); let error_message = payment_data.payment_attempt.error_message.clone(); req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentReject { error_code, error_message, })) .with(payment_data.to_event()) .emit(); Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, PaymentsCancelRequest, PaymentData<F>> for PaymentReject { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &PaymentsCancelRequest, merchant_context: &'a domain::MerchantContext, ) -> RouterResult<(PaymentRejectOperation<'b, F>, operations::ValidateResult)> { Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()), storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: false, }, )) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_reject.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-4659886382746153415
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_capture_v2.rs // Contains: 1 structs, 0 enums use api_models::{enums::FrmSuggestion, payments::PaymentsCaptureRequest}; use async_trait::async_trait; use error_stack::ResultExt; use hyperswitch_domain_models::payments::PaymentCaptureData; use router_env::{instrument, tracing}; use super::{Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, payments::{ helpers, operations::{self, ValidateStatusForOperation}, }, }, routes::{app::ReqState, SessionState}, types::{ api::{self, ConnectorCallType}, domain::{self}, storage::{self, enums as storage_enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy)] pub struct PaymentsCapture; impl ValidateStatusForOperation for PaymentsCapture { /// 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, ) -> Result<(), errors::ApiErrorResponse> { match intent_status { common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable => Ok(()), common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Processing | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::Expired => { 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::PartiallyCapturedAndCapturable, ] .map(|enum_value| enum_value.to_string()) .join(", "), }) } } } } type BoxedConfirmOperation<'b, F> = super::BoxedOperation<'b, F, PaymentsCaptureRequest, PaymentCaptureData<F>>; // TODO: change the macro to include changes for v2 // TODO: PaymentData in the macro should be an input impl<F: Send + Clone> Operation<F, PaymentsCaptureRequest> for &PaymentsCapture { type Data = PaymentCaptureData<F>; fn to_validate_request( &self, ) -> RouterResult<&(dyn ValidateRequest<F, PaymentsCaptureRequest, Self::Data> + Send + Sync)> { Ok(*self) } fn to_get_tracker( &self, ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsCaptureRequest> + Send + Sync)> { Ok(*self) } fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentsCaptureRequest, Self::Data>)> { Ok(*self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsCaptureRequest> + Send + Sync)> { Ok(*self) } } #[automatically_derived] impl<F: Send + Clone> Operation<F, PaymentsCaptureRequest> for PaymentsCapture { type Data = PaymentCaptureData<F>; fn to_validate_request( &self, ) -> RouterResult<&(dyn ValidateRequest<F, PaymentsCaptureRequest, Self::Data> + Send + Sync)> { Ok(self) } fn to_get_tracker( &self, ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsCaptureRequest> + Send + Sync)> { Ok(self) } fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsCaptureRequest, Self::Data>> { Ok(self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsCaptureRequest> + Send + Sync)> { Ok(self) } } impl<F: Send + Clone> ValidateRequest<F, PaymentsCaptureRequest, PaymentCaptureData<F>> for PaymentsCapture { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, _request: &PaymentsCaptureRequest, merchant_context: &'a domain::MerchantContext, ) -> RouterResult<operations::ValidateResult> { let validate_result = operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: false, }; Ok(validate_result) } } #[async_trait] impl<F: Send + Clone> GetTracker<F, PaymentCaptureData<F>, PaymentsCaptureRequest> for PaymentsCapture { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &common_utils::id_type::GlobalPaymentId, request: &PaymentsCaptureRequest, merchant_context: &domain::MerchantContext, _profile: &domain::Profile, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<operations::GetTrackerResponse<PaymentCaptureData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_intent = db .find_payment_intent_by_id( key_manager_state, payment_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; self.validate_status_for_operation(payment_intent.status)?; let active_attempt_id = payment_intent .active_attempt_id .as_ref() .get_required_value("active_attempt_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Active attempt id is none when capturing the payment")?; let mut payment_attempt = db .find_payment_attempt_by_id( key_manager_state, merchant_context.get_merchant_key_store(), active_attempt_id, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not find payment attempt given the attempt id")?; if let Some(amount_to_capture) = request.amount_to_capture { payment_attempt .amount_details .validate_amount_to_capture(amount_to_capture) .change_context(errors::ApiErrorResponse::PreconditionFailed { message: format!( "`amount_to_capture` is greater than the net amount {}", payment_attempt.amount_details.get_net_amount() ), })?; payment_attempt .amount_details .set_amount_to_capture(amount_to_capture); } let payment_data = PaymentCaptureData { flow: std::marker::PhantomData, payment_intent, payment_attempt, }; let get_trackers_response = operations::GetTrackerResponse { payment_data }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Send> Domain<F, PaymentsCaptureRequest, PaymentCaptureData<F>> for PaymentsCapture { async fn get_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentCaptureData<F>, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<(BoxedConfirmOperation<'a, F>, Option<domain::Customer>), errors::StorageError> { match payment_data.payment_intent.customer_id.clone() { Some(id) => { let customer = state .store .find_customer_by_global_id( &state.into(), &id, merchant_key_store, storage_scheme, ) .await?; Ok((Box::new(self), Some(customer))) } None => Ok((Box::new(self), None)), } } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut PaymentCaptureData<F>, _storage_scheme: storage_enums::MerchantStorageScheme, _key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( BoxedConfirmOperation<'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, // TODO: do not take the whole payment data here payment_data: &mut PaymentCaptureData<F>, ) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse> { let payment_attempt = &payment_data.payment_attempt; 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 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")?; 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(connector_data.into())) } } #[async_trait] impl<F: Clone> UpdateTracker<F, PaymentCaptureData<F>, PaymentsCaptureRequest> for PaymentsCapture { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, _req_state: ReqState, mut payment_data: PaymentCaptureData<F>, _customer: Option<domain::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(BoxedConfirmOperation<'b, F>, PaymentCaptureData<F>)> where F: 'b + Send, { let payment_attempt_update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::PreCaptureUpdate { amount_to_capture: payment_data.payment_attempt.amount_details.get_amount_to_capture(), updated_by: storage_scheme.to_string() }; let payment_attempt = state .store .update_payment_attempt( &state.into(), key_store, payment_data.payment_attempt.clone(), payment_attempt_update, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not update payment attempt")?; payment_data.payment_attempt = payment_attempt; Ok((Box::new(self), payment_data)) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_capture_v2.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-2578791074357047888
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_update_metadata.rs // Contains: 1 structs, 0 enums use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; use common_utils::types::keymanager::KeyManagerState; use error_stack::ResultExt; use masking::ExposeInterface; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{self, helpers, operations, PaymentData}, }, routes::{app::ReqState, SessionState}, services, types::{ api::{self, PaymentIdTypeExt}, domain, storage::{self, enums as storage_enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, PaymentOperation)] #[operation(operations = "all", flow = "update_metadata")] pub struct PaymentUpdateMetadata; type PaymentUpdateMetadataOperation<'b, F> = BoxedOperation<'b, F, api::PaymentsUpdateMetadataRequest, PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsUpdateMetadataRequest> for PaymentUpdateMetadata { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &api::PaymentsUpdateMetadataRequest, merchant_context: &domain::MerchantContext, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsUpdateMetadataRequest, PaymentData<F>>, > { let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let db = &*state.store; let key_manager_state: &KeyManagerState = &state.into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let mut payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &state.into(), &payment_id, merchant_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; helpers::validate_payment_status_against_allowed_statuses( payment_intent.status, &[ storage_enums::IntentStatus::Succeeded, storage_enums::IntentStatus::Failed, storage_enums::IntentStatus::PartiallyCaptured, storage_enums::IntentStatus::PartiallyCapturedAndCapturable, storage_enums::IntentStatus::RequiresCapture, ], "update_metadata", )?; let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, payment_intent.active_attempt.get_id().as_str(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let currency = payment_intent.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount().into(); let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = db .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 merged_metadata = payment_intent .merge_metadata(request.metadata.clone().expose()) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Metadata should be an object and contain at least 1 key".to_owned(), })?; payment_intent.metadata = Some(merged_metadata); let payment_data = PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount, email: None, mandate_id: None, mandate_connector: None, customer_acceptance: None, token: None, token_data: None, setup_mandate: None, address: payments::PaymentAddress::new(None, None, None, None), confirm: None, payment_method_data: None, payment_method_token: None, payment_method_info: None, force_sync: None, all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: None, creds_identifier: None, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, redirect_response: None, surcharge_details: None, frm_message: None, payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], authentication: None, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, whole_connector_response: None, is_manual_retry_enabled: None, is_l2_l3_enabled: false, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, api::PaymentsUpdateMetadataRequest, PaymentData<F>> for PaymentUpdateMetadata { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut PaymentData<F>, _request: Option<payments::CustomerDetails>, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> errors::CustomResult< ( PaymentUpdateMetadataOperation<'a, 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 PaymentData<F>, _storage_scheme: storage_enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentUpdateMetadataOperation<'a, F>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } async fn get_connector<'a>( &'a self, _merchant_context: &domain::MerchantContext, state: &SessionState, _request: &api::PaymentsUpdateMetadataRequest, _payment_intent: &storage::PaymentIntent, ) -> errors::CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut PaymentData<F>, ) -> errors::CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsUpdateMetadataRequest> for PaymentUpdateMetadata { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, _state: &'b SessionState, _req_state: ReqState, payment_data: PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: storage_enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, _key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(PaymentUpdateMetadataOperation<'b, F>, PaymentData<F>)> where F: 'b + Send, { Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsUpdateMetadataRequest, PaymentData<F>> for PaymentUpdateMetadata { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsUpdateMetadataRequest, merchant_context: &'a domain::MerchantContext, ) -> RouterResult<( PaymentUpdateMetadataOperation<'b, F>, operations::ValidateResult, )> { //payment id is already generated and should be sent in the request let given_payment_id = request.payment_id.clone(); Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), payment_id: api::PaymentIdType::PaymentIntentId(given_payment_id), storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: false, }, )) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_update_metadata.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-2919406828149009584
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_approve.rs // Contains: 1 structs, 0 enums use std::marker::PhantomData; use api_models::enums::{AttemptStatus, FrmSuggestion, IntentStatus}; use async_trait::async_trait; use error_stack::ResultExt; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{helpers, operations, PaymentData}, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ api::{self, PaymentIdTypeExt}, domain, storage::{self, enums as storage_enums}, PaymentAddress, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, PaymentOperation)] #[operation(operations = "all", flow = "capture")] pub struct PaymentApprove; type PaymentApproveOperation<'a, F> = BoxedOperation<'a, F, api::PaymentsCaptureRequest, PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> for PaymentApprove { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, _request: &api::PaymentsCaptureRequest, merchant_context: &domain::MerchantContext, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsCaptureRequest, PaymentData<F>>, > { let db = &*state.store; let key_manager_state = &state.into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let (mut payment_intent, payment_attempt, currency, amount); let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; payment_intent = db .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, merchant_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; helpers::validate_payment_status_against_not_allowed_statuses( payment_intent.status, &[IntentStatus::Failed, IntentStatus::Succeeded], "approve", )?; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; 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 attempt_id = payment_intent.active_attempt.get_id().clone(); payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, &attempt_id.clone(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; currency = payment_attempt.currency.get_required_value("currency")?; amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( state, payment_intent.shipping_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let payment_method_billing = helpers::get_address_by_id( state, payment_attempt.payment_method_billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; payment_intent.shipping_address_id = shipping_address.clone().map(|i| i.address_id); payment_intent.billing_address_id = billing_address.clone().map(|i| i.address_id); let frm_response = if cfg!(feature = "frm") { db.find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_context.get_merchant_account().get_id().clone()) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving frm_response, merchant_id: {}, payment_id: {attempt_id}", merchant_context.get_merchant_account().get_id().get_string_repr()) }) .ok() } else { None }; let payment_data = PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount, email: None, mandate_id: None, mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, token_data: None, address: PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ), confirm: None, payment_method_data: None, payment_method_token: None, payment_method_info: None, force_sync: None, all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: None, creds_identifier: None, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, redirect_response: None, surcharge_details: None, frm_message: frm_response, payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], authentication: None, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, whole_connector_response: None, is_manual_retry_enabled: None, is_l2_l3_enabled: false, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> for PaymentApprove { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, req_state: ReqState, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(PaymentApproveOperation<'b, F>, PaymentData<F>)> where F: 'b + Send, { if matches!(frm_suggestion, Some(FrmSuggestion::FrmAuthorizeTransaction)) { payment_data.payment_intent.status = IntentStatus::RequiresCapture; // In Approve flow, payment which has payment_capture_method "manual" and attempt status as "Unresolved", payment_data.payment_attempt.status = AttemptStatus::Authorized; // We shouldn't call the connector instead we need to update the payment attempt and payment intent. } let intent_status_update = storage::PaymentIntentUpdate::ApproveUpdate { status: payment_data.payment_intent.status, merchant_decision: Some(api_models::enums::MerchantDecision::Approved.to_string()), updated_by: storage_scheme.to_string(), }; payment_data.payment_intent = state .store .update_payment_intent( &state.into(), payment_data.payment_intent, intent_status_update, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; state .store .update_payment_attempt_with_attempt_id( payment_data.payment_attempt.clone(), storage::PaymentAttemptUpdate::StatusUpdate { status: payment_data.payment_attempt.status, updated_by: storage_scheme.to_string(), }, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentApprove)) .with(payment_data.to_event()) .emit(); Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsCaptureRequest, PaymentData<F>> for PaymentApprove { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsCaptureRequest, merchant_context: &'a domain::MerchantContext, ) -> RouterResult<(PaymentApproveOperation<'b, F>, operations::ValidateResult)> { let request_merchant_id = request.merchant_id.as_ref(); helpers::validate_merchant_id( merchant_context.get_merchant_account().get_id(), request_merchant_id, ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "merchant_id".to_string(), expected_format: "merchant_id from merchant account".to_string(), })?; Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.clone()), storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: false, }, )) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_approve.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_8843035003352373050
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_response.rs // Contains: 2 structs, 0 enums use std::{collections::HashMap, ops::Deref}; use api_models::payments::{ConnectorMandateReferenceId, MandateReferenceId}; #[cfg(feature = "dynamic_routing")] use api_models::routing::RoutableConnectorChoice; use async_trait::async_trait; use common_enums::AuthorizationStatus; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use common_utils::ext_traits::ValueExt; use common_utils::{ ext_traits::{AsyncExt, Encode}, types::{keymanager::KeyManagerState, ConnectorTransactionId, MinorUnit}, }; use error_stack::{report, ResultExt}; use futures::FutureExt; use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt; #[cfg(feature = "v2")] use hyperswitch_domain_models::payments::{ PaymentConfirmData, PaymentIntentData, PaymentStatusData, }; use router_derive; use router_env::{instrument, logger, tracing}; use storage_impl::DataModelExt; use tracing_futures::Instrument; use super::{Operation, OperationSessionSetters, PostUpdateTracker}; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use crate::core::routing::helpers as routing_helpers; #[cfg(feature = "v2")] use crate::utils::OptionExt; use crate::{ connector::utils::PaymentResponseRouterData, consts, core::{ card_testing_guard::utils as card_testing_guard_utils, errors::{self, CustomResult, RouterResult, StorageErrorExt}, mandate, payment_methods::{self, cards::create_encrypted_data}, payments::{ helpers::{ self as payments_helpers, update_additional_payment_data_with_connector_response_pm_data, }, tokenization, types::MultipleCaptureData, PaymentData, PaymentMethodChecker, }, utils as core_utils, }, routes::{metrics, SessionState}, types::{ self, domain, storage::{self, enums}, transformers::{ForeignFrom, ForeignTryFrom}, CaptureSyncResponse, ErrorResponse, }, utils, }; #[cfg(feature = "v1")] #[derive(Debug, Clone, Copy, router_derive::PaymentOperation)] #[operation( operations = "post_update_tracker", flow = "sync_data, cancel_data, authorize_data, capture_data, complete_authorize_data, approve_data, reject_data, setup_mandate_data, session_data,incremental_authorization_data, sdk_session_update_data, post_session_tokens_data, update_metadata_data, cancel_post_capture_data, extend_authorization_data" )] pub struct PaymentResponse; #[cfg(feature = "v2")] #[derive(Debug, Clone, Copy)] pub struct PaymentResponse; #[cfg(feature = "v1")] #[async_trait] impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthorizeData> for PaymentResponse { async fn update_tracker<'b>( &'b self, db: &'b SessionState, mut payment_data: PaymentData<F>, router_data: types::RouterData< F, types::PaymentsAuthorizeData, types::PaymentsResponseData, >, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, locale: &Option<String>, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec< RoutableConnectorChoice, >, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile, ) -> RouterResult<PaymentData<F>> where F: 'b, { payment_data.mandate_id = payment_data .mandate_id .or_else(|| router_data.request.mandate_id.clone()); // update setup_future_usage incase it is downgraded to on-session payment_data.payment_attempt.setup_future_usage_applied = router_data.request.setup_future_usage; payment_data = Box::pin(payment_response_update_tracker( db, payment_data, router_data, key_store, storage_scheme, locale, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile, )) .await?; Ok(payment_data) } #[cfg(feature = "v2")] async fn save_pm_and_mandate<'b>( &self, state: &SessionState, resp: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, merchant_context: &domain::MerchantContext, payment_data: &mut PaymentData<F>, business_profile: &domain::Profile, ) -> CustomResult<(), errors::ApiErrorResponse> where F: 'b + Clone + Send + Sync, { todo!() } #[cfg(feature = "v1")] async fn save_pm_and_mandate<'b>( &self, state: &SessionState, resp: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, merchant_context: &domain::MerchantContext, payment_data: &mut PaymentData<F>, business_profile: &domain::Profile, ) -> CustomResult<(), errors::ApiErrorResponse> where F: 'b + Clone + Send + Sync, { let customer_id = payment_data.payment_intent.customer_id.clone(); let save_payment_data = tokenization::SavePaymentMethodData::from(resp); let payment_method_billing_address = payment_data.address.get_payment_method_billing(); let connector_name = payment_data .payment_attempt .connector .clone() .ok_or_else(|| { logger::error!("Missing required Param connector_name"); errors::ApiErrorResponse::MissingRequiredField { field_name: "connector_name", } })?; let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone(); let billing_name = resp .address .get_payment_method_billing() .and_then(|billing_details| billing_details.address.as_ref()) .and_then(|address| address.get_optional_full_name()); let mut should_avoid_saving = false; let vault_operation = payment_data.vault_operation.clone(); let payment_method_info = payment_data.payment_method_info.clone(); if let Some(payment_method_info) = &payment_data.payment_method_info { if payment_data.payment_intent.off_session.is_none() && resp.response.is_ok() { should_avoid_saving = resp.request.payment_method_type == Some(enums::PaymentMethodType::ApplePay) || resp.request.payment_method_type == Some(enums::PaymentMethodType::GooglePay); payment_methods::cards::update_last_used_at( payment_method_info, state, merchant_context.get_merchant_account().storage_scheme, merchant_context.get_merchant_key_store(), ) .await .map_err(|e| { logger::error!("Failed to update last used at: {:?}", e); }) .ok(); } }; let connector_mandate_reference_id = payment_data .payment_attempt .connector_mandate_detail .as_ref() .map(|detail| ConnectorMandateReferenceId::foreign_from(detail.clone())); let save_payment_call_future = Box::pin(tokenization::save_payment_method( state, connector_name.clone(), save_payment_data, customer_id.clone(), merchant_context, resp.request.payment_method_type, billing_name.clone(), payment_method_billing_address, business_profile, connector_mandate_reference_id.clone(), merchant_connector_id.clone(), vault_operation.clone(), payment_method_info.clone(), )); let is_connector_mandate = resp.request.customer_acceptance.is_some() && matches!( resp.request.setup_future_usage, Some(enums::FutureUsage::OffSession) ); let is_legacy_mandate = resp.request.setup_mandate_details.is_some() && matches!( resp.request.setup_future_usage, Some(enums::FutureUsage::OffSession) ); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; if is_legacy_mandate { // Mandate is created on the application side and at the connector. let tokenization::SavePaymentMethodDataResponse { payment_method_id, .. } = save_payment_call_future.await?; let mandate_id = mandate::mandate_procedure( state, resp, &customer_id.clone(), payment_method_id.clone(), merchant_connector_id.clone(), merchant_context.get_merchant_account().storage_scheme, payment_data.payment_intent.get_id(), ) .await?; payment_data.payment_attempt.payment_method_id = payment_method_id; payment_data.payment_attempt.mandate_id = mandate_id; Ok(()) } else if is_connector_mandate { // The mandate is created on connector's end. let tokenization::SavePaymentMethodDataResponse { payment_method_id, connector_mandate_reference_id, .. } = save_payment_call_future.await?; payment_data.payment_method_info = if let Some(payment_method_id) = &payment_method_id { match state .store .find_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), payment_method_id, storage_scheme, ) .await { Ok(payment_method) => Some(payment_method), Err(error) => { if error.current_context().is_db_not_found() { logger::info!("Payment Method not found in db {:?}", error); None } else { Err(error) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error retrieving payment method from db") .map_err(|err| logger::error!(payment_method_retrieve=?err)) .ok() } } } } else { None }; payment_data.payment_attempt.payment_method_id = payment_method_id; payment_data.payment_attempt.connector_mandate_detail = connector_mandate_reference_id .clone() .map(ForeignFrom::foreign_from); payment_data.set_mandate_id(api_models::payments::MandateIds { mandate_id: None, mandate_reference_id: connector_mandate_reference_id.map(|connector_mandate_id| { MandateReferenceId::ConnectorMandateId(connector_mandate_id) }), }); Ok(()) } else if should_avoid_saving { if let Some(pm_info) = &payment_data.payment_method_info { payment_data.payment_attempt.payment_method_id = Some(pm_info.get_id().clone()); }; Ok(()) } else { // Save card flow let save_payment_data = tokenization::SavePaymentMethodData::from(resp); let state = state.clone(); let customer_id = payment_data.payment_intent.customer_id.clone(); let payment_attempt = payment_data.payment_attempt.clone(); let business_profile = business_profile.clone(); let payment_method_type = resp.request.payment_method_type; let payment_method_billing_address = payment_method_billing_address.cloned(); let cloned_merchant_context = merchant_context.clone(); logger::info!("Call to save_payment_method in locker"); let _task_handle = tokio::spawn( async move { logger::info!("Starting async call to save_payment_method in locker"); let result = Box::pin(tokenization::save_payment_method( &state, connector_name, save_payment_data, customer_id, &cloned_merchant_context, payment_method_type, billing_name, payment_method_billing_address.as_ref(), &business_profile, connector_mandate_reference_id, merchant_connector_id.clone(), vault_operation.clone(), payment_method_info.clone(), )) .await; if let Err(err) = result { logger::error!("Asynchronously saving card in locker failed : {:?}", err); } else if let Ok(tokenization::SavePaymentMethodDataResponse { payment_method_id, .. }) = result { let payment_attempt_update = storage::PaymentAttemptUpdate::PaymentMethodDetailsUpdate { payment_method_id, updated_by: storage_scheme.clone().to_string(), }; #[cfg(feature = "v1")] let respond = state .store .update_payment_attempt_with_attempt_id( payment_attempt, payment_attempt_update, storage_scheme, ) .await; #[cfg(feature = "v2")] let respond = state .store .update_payment_attempt_with_attempt_id( &(&state).into(), &key_store, payment_attempt, payment_attempt_update, storage_scheme, ) .await; if let Err(err) = respond { logger::error!("Error updating payment attempt: {:?}", err); }; } } .in_current_span(), ); Ok(()) } } } #[cfg(feature = "v1")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsIncrementalAuthorizationData> for PaymentResponse { async fn update_tracker<'b>( &'b self, state: &'b SessionState, mut payment_data: PaymentData<F>, router_data: types::RouterData< F, types::PaymentsIncrementalAuthorizationData, types::PaymentsResponseData, >, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, _locale: &Option<String>, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] _routable_connector: Vec< RoutableConnectorChoice, >, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] _business_profile: &domain::Profile, ) -> RouterResult<PaymentData<F>> where F: 'b + Send, { let incremental_authorization_details = payment_data .incremental_authorization_details .clone() .ok_or_else(|| { report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing incremental_authorization_details in payment_data") })?; // Update payment_intent and payment_attempt 'amount' if incremental_authorization is successful let (option_payment_attempt_update, option_payment_intent_update) = match router_data .response .clone() { Err(_) => (None, None), Ok(types::PaymentsResponseData::IncrementalAuthorizationResponse { status, .. }) => { if status == AuthorizationStatus::Success { ( Some( storage::PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate { net_amount: hyperswitch_domain_models::payments::payment_attempt::NetAmount::new( // Internally, `NetAmount` is computed as (order_amount + additional_amount), so we subtract here to avoid double-counting. incremental_authorization_details.total_amount - payment_data.payment_attempt.net_amount.get_additional_amount(), None, None, None, None, ), amount_capturable: incremental_authorization_details.total_amount, }, ), Some( storage::PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate { amount: incremental_authorization_details.total_amount - payment_data.payment_attempt.net_amount.get_additional_amount(), }, ), ) } else { (None, None) } } _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("unexpected response in incremental_authorization flow")?, }; //payment_attempt update if let Some(payment_attempt_update) = option_payment_attempt_update { #[cfg(feature = "v1")] { payment_data.payment_attempt = state .store .update_payment_attempt_with_attempt_id( payment_data.payment_attempt.clone(), payment_attempt_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; } #[cfg(feature = "v2")] { payment_data.payment_attempt = state .store .update_payment_attempt_with_attempt_id( &state.into(), key_store, payment_data.payment_attempt.clone(), payment_attempt_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; } } // payment_intent update if let Some(payment_intent_update) = option_payment_intent_update { payment_data.payment_intent = state .store .update_payment_intent( &state.into(), payment_data.payment_intent.clone(), payment_intent_update, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; } // Update the status of authorization record let authorization_update = match &router_data.response { Err(res) => Ok(storage::AuthorizationUpdate::StatusUpdate { status: AuthorizationStatus::Failure, error_code: Some(res.code.clone()), error_message: Some(res.message.clone()), connector_authorization_id: None, }), Ok(types::PaymentsResponseData::IncrementalAuthorizationResponse { status, error_code, error_message, connector_authorization_id, }) => Ok(storage::AuthorizationUpdate::StatusUpdate { status: status.clone(), error_code: error_code.clone(), error_message: error_message.clone(), connector_authorization_id: connector_authorization_id.clone(), }), Ok(_) => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("unexpected response in incremental_authorization flow"), }?; let authorization_id = incremental_authorization_details .authorization_id .clone() .ok_or( report!(errors::ApiErrorResponse::InternalServerError).attach_printable( "missing authorization_id in incremental_authorization_details in payment_data", ), )?; state .store .update_authorization_by_merchant_id_authorization_id( router_data.merchant_id.clone(), authorization_id, authorization_update, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed while updating authorization")?; //Fetch all the authorizations of the payment and send in incremental authorization response let authorizations = state .store .find_all_authorizations_by_merchant_id_payment_id( &router_data.merchant_id, payment_data.payment_intent.get_id(), ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed while retrieving authorizations")?; payment_data.authorizations = authorizations; Ok(payment_data) } } #[cfg(feature = "v1")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSyncData> for PaymentResponse { async fn update_tracker<'b>( &'b self, db: &'b SessionState, payment_data: PaymentData<F>, router_data: types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, locale: &Option<String>, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec< RoutableConnectorChoice, >, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile, ) -> RouterResult<PaymentData<F>> where F: 'b + Send, { Box::pin(payment_response_update_tracker( db, payment_data, router_data, key_store, storage_scheme, locale, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile, )) .await } async fn save_pm_and_mandate<'b>( &self, state: &SessionState, resp: &types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>, merchant_context: &domain::MerchantContext, payment_data: &mut PaymentData<F>, _business_profile: &domain::Profile, ) -> CustomResult<(), errors::ApiErrorResponse> where F: 'b + Clone + Send + Sync, { let (connector_mandate_id, mandate_metadata, connector_mandate_request_reference_id) = resp .response .clone() .ok() .and_then(|resp| { if let types::PaymentsResponseData::TransactionResponse { mandate_reference, .. } = resp { mandate_reference.map(|mandate_ref| { ( mandate_ref.connector_mandate_id.clone(), mandate_ref.mandate_metadata.clone(), mandate_ref.connector_mandate_request_reference_id.clone(), ) }) } else { None } }) .unwrap_or((None, None, None)); update_connector_mandate_details_for_the_flow( connector_mandate_id, mandate_metadata, connector_mandate_request_reference_id, payment_data, )?; update_payment_method_status_and_ntid( state, merchant_context.get_merchant_key_store(), payment_data, resp.status, resp.response.clone(), merchant_context.get_merchant_account().storage_scheme, ) .await?; Ok(()) } } #[cfg(feature = "v1")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSessionData> for PaymentResponse { async fn update_tracker<'b>( &'b self, db: &'b SessionState, mut payment_data: PaymentData<F>, router_data: types::RouterData<F, types::PaymentsSessionData, types::PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, locale: &Option<String>, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec< RoutableConnectorChoice, >, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile, ) -> RouterResult<PaymentData<F>> where F: 'b + Send, { payment_data = Box::pin(payment_response_update_tracker( db, payment_data, router_data, key_store, storage_scheme, locale, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile, )) .await?; Ok(payment_data) } } #[cfg(feature = "v1")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SdkPaymentsSessionUpdateData> for PaymentResponse { async fn update_tracker<'b>( &'b self, db: &'b SessionState, mut payment_data: PaymentData<F>, router_data: types::RouterData< F, types::SdkPaymentsSessionUpdateData, types::PaymentsResponseData, >, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, _locale: &Option<String>, #[cfg(feature = "dynamic_routing")] _routable_connector: Vec<RoutableConnectorChoice>, #[cfg(feature = "dynamic_routing")] _business_profile: &domain::Profile, ) -> RouterResult<PaymentData<F>> where F: 'b + Send, { let connector = payment_data .payment_attempt .connector .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("connector not found")?; let key_manager_state = db.into(); // For PayPal, if we call TaxJar for tax calculation, we need to call the connector again to update the order amount so that we can confirm the updated amount and order details. Therefore, we will store the required changes in the database during the post_update_tracker call. if payment_data.should_update_in_post_update_tracker() { match router_data.response.clone() { Ok(types::PaymentsResponseData::PaymentResourceUpdateResponse { status }) => { if status.is_success() { let shipping_address = payment_data .tax_data .clone() .map(|tax_data| tax_data.shipping_details); let shipping_details = shipping_address .clone() .async_map(|shipping_details| { create_encrypted_data( &key_manager_state, key_store, shipping_details, ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt shipping details")?; let shipping_address = payments_helpers::create_or_update_address_for_payment_by_request( db, shipping_address.map(From::from).as_ref(), payment_data.payment_intent.shipping_address_id.as_deref(), &payment_data.payment_intent.merchant_id, payment_data.payment_intent.customer_id.as_ref(), key_store, &payment_data.payment_intent.payment_id, storage_scheme, ) .await?; let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::SessionResponseUpdate { tax_details: payment_data.payment_intent.tax_details.clone().ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("payment_intent.tax_details not found")?, shipping_address_id: shipping_address.map(|address| address.address_id), updated_by: payment_data.payment_intent.updated_by.clone(), shipping_details, }; let m_db = db.clone().store; let payment_intent = payment_data.payment_intent.clone(); let key_manager_state: KeyManagerState = db.into(); let updated_payment_intent = m_db .update_payment_intent( &key_manager_state, payment_intent, payment_intent_update, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_data.payment_intent = updated_payment_intent; } else { router_data.response.map_err(|err| { errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector, status_code: err.status_code, reason: err.reason, } })?; } } Err(err) => { Err(errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector, status_code: err.status_code, reason: err.reason, })?; } _ => { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unexpected response in session_update flow")?; } } } Ok(payment_data) } } #[cfg(feature = "v1")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsPostSessionTokensData> for PaymentResponse { async fn update_tracker<'b>( &'b self, db: &'b SessionState, mut payment_data: PaymentData<F>, router_data: types::RouterData< F, types::PaymentsPostSessionTokensData, types::PaymentsResponseData, >, _key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, _locale: &Option<String>, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] _routable_connector: Vec< RoutableConnectorChoice, >, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] _business_profile: &domain::Profile, ) -> RouterResult<PaymentData<F>> where F: 'b + Send, { match router_data.response.clone() { Ok(types::PaymentsResponseData::TransactionResponse { connector_metadata, .. }) => { let m_db = db.clone().store; let payment_attempt_update = storage::PaymentAttemptUpdate::PostSessionTokensUpdate { updated_by: storage_scheme.clone().to_string(), connector_metadata, }; let updated_payment_attempt = m_db .update_payment_attempt_with_attempt_id( payment_data.payment_attempt.clone(), payment_attempt_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_data.payment_attempt = updated_payment_attempt; } Err(err) => { logger::error!("Invalid request sent to connector: {:?}", err); Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid request sent to connector".to_string(), })?; } _ => { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unexpected response in PostSessionTokens flow")?; } } Ok(payment_data) } } #[cfg(feature = "v1")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsUpdateMetadataData> for PaymentResponse { async fn update_tracker<'b>( &'b self, db: &'b SessionState, mut payment_data: PaymentData<F>, router_data: types::RouterData< F, types::PaymentsUpdateMetadataData, types::PaymentsResponseData, >, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, _locale: &Option<String>, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] _routable_connector: Vec< RoutableConnectorChoice, >, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] _business_profile: &domain::Profile, ) -> RouterResult<PaymentData<F>> where F: 'b + Send, { let connector = payment_data .payment_attempt .connector .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("connector not found in payment_attempt")?; match router_data.response.clone() { Ok(types::PaymentsResponseData::PaymentResourceUpdateResponse { status, .. }) => { if status.is_success() { let m_db = db.clone().store; let payment_intent = payment_data.payment_intent.clone(); let key_manager_state: KeyManagerState = db.into(); let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::MetadataUpdate { metadata: payment_data .payment_intent .metadata .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("payment_intent.metadata not found")?, updated_by: payment_data.payment_intent.updated_by.clone(), }; let updated_payment_intent = m_db .update_payment_intent( &key_manager_state, payment_intent, payment_intent_update, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_data.payment_intent = updated_payment_intent; } else { router_data.response.map_err(|err| { errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector, status_code: err.status_code, reason: err.reason, } })?; } } Err(err) => { Err(errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector, status_code: err.status_code, reason: err.reason, })?; } _ => { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unexpected response in Update Metadata flow")?; } } Ok(payment_data) } } #[cfg(feature = "v1")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCaptureData> for PaymentResponse { async fn update_tracker<'b>( &'b self, db: &'b SessionState, mut payment_data: PaymentData<F>, router_data: types::RouterData<F, types::PaymentsCaptureData, types::PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, locale: &Option<String>, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec< RoutableConnectorChoice, >, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile, ) -> RouterResult<PaymentData<F>> where F: 'b + Send, { payment_data = Box::pin(payment_response_update_tracker( db, payment_data, router_data, key_store, storage_scheme, locale, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile, )) .await?; Ok(payment_data) } } #[cfg(feature = "v1")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCancelData> for PaymentResponse { async fn update_tracker<'b>( &'b self, db: &'b SessionState, mut payment_data: PaymentData<F>, router_data: types::RouterData<F, types::PaymentsCancelData, types::PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, locale: &Option<String>, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec< RoutableConnectorChoice, >, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile, ) -> RouterResult<PaymentData<F>> where F: 'b + Send, { payment_data = Box::pin(payment_response_update_tracker( db, payment_data, router_data, key_store, storage_scheme, locale, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile, )) .await?; Ok(payment_data) } } #[cfg(feature = "v1")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCancelPostCaptureData> for PaymentResponse { async fn update_tracker<'b>( &'b self, db: &'b SessionState, mut payment_data: PaymentData<F>, router_data: types::RouterData< F, types::PaymentsCancelPostCaptureData, types::PaymentsResponseData, >, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, locale: &Option<String>, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec< RoutableConnectorChoice, >, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile, ) -> RouterResult<PaymentData<F>> where F: 'b + Send, { payment_data = Box::pin(payment_response_update_tracker( db, payment_data, router_data, key_store, storage_scheme, locale, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile, )) .await?; Ok(payment_data) } } #[cfg(feature = "v1")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsExtendAuthorizationData> for PaymentResponse { async fn update_tracker<'b>( &'b self, db: &'b SessionState, mut payment_data: PaymentData<F>, router_data: types::RouterData< F, types::PaymentsExtendAuthorizationData, types::PaymentsResponseData, >, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, locale: &Option<String>, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec< RoutableConnectorChoice, >, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile, ) -> RouterResult<PaymentData<F>> where F: 'b + Send, { payment_data = Box::pin(payment_response_update_tracker( db, payment_data, router_data, key_store, storage_scheme, locale, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile, )) .await?; Ok(payment_data) } } #[cfg(feature = "v1")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsApproveData> for PaymentResponse { async fn update_tracker<'b>( &'b self, db: &'b SessionState, mut payment_data: PaymentData<F>, router_data: types::RouterData<F, types::PaymentsApproveData, types::PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, locale: &Option<String>, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec< RoutableConnectorChoice, >, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile, ) -> RouterResult<PaymentData<F>> where F: 'b + Send, { payment_data = Box::pin(payment_response_update_tracker( db, payment_data, router_data, key_store, storage_scheme, locale, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile, )) .await?; Ok(payment_data) } } #[cfg(feature = "v1")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsRejectData> for PaymentResponse { async fn update_tracker<'b>( &'b self, db: &'b SessionState, mut payment_data: PaymentData<F>, router_data: types::RouterData<F, types::PaymentsRejectData, types::PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, locale: &Option<String>, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec< RoutableConnectorChoice, >, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile, ) -> RouterResult<PaymentData<F>> where F: 'b + Send, { payment_data = Box::pin(payment_response_update_tracker( db, payment_data, router_data, key_store, storage_scheme, locale, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile, )) .await?; Ok(payment_data) } } #[cfg(feature = "v1")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestData> for PaymentResponse { async fn update_tracker<'b>( &'b self, db: &'b SessionState, mut payment_data: PaymentData<F>, router_data: types::RouterData< F, types::SetupMandateRequestData, types::PaymentsResponseData, >, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, locale: &Option<String>, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec< RoutableConnectorChoice, >, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile, ) -> RouterResult<PaymentData<F>> where F: 'b + Send, { payment_data.mandate_id = payment_data.mandate_id.or_else(|| { router_data.request.mandate_id.clone() // .map(api_models::payments::MandateIds::new) }); payment_data = Box::pin(payment_response_update_tracker( db, payment_data, router_data, key_store, storage_scheme, locale, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile, )) .await?; Ok(payment_data) } async fn save_pm_and_mandate<'b>( &self, state: &SessionState, resp: &types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData>, merchant_context: &domain::MerchantContext, payment_data: &mut PaymentData<F>, business_profile: &domain::Profile, ) -> CustomResult<(), errors::ApiErrorResponse> where F: 'b + Clone + Send + Sync, { let payment_method_billing_address = payment_data.address.get_payment_method_billing(); let billing_name = resp .address .get_payment_method_billing() .and_then(|billing_details| billing_details.address.as_ref()) .and_then(|address| address.get_optional_full_name()); let save_payment_data = tokenization::SavePaymentMethodData::from(resp); let customer_id = payment_data.payment_intent.customer_id.clone(); let connector_name = payment_data .payment_attempt .connector .clone() .ok_or_else(|| { logger::error!("Missing required Param connector_name"); errors::ApiErrorResponse::MissingRequiredField { field_name: "connector_name", } })?; let connector_mandate_reference_id = payment_data .payment_attempt .connector_mandate_detail .as_ref() .map(|detail| ConnectorMandateReferenceId::foreign_from(detail.clone())); let vault_operation = payment_data.vault_operation.clone(); let payment_method_info = payment_data.payment_method_info.clone(); let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone(); let tokenization::SavePaymentMethodDataResponse { payment_method_id, connector_mandate_reference_id, .. } = Box::pin(tokenization::save_payment_method( state, connector_name, save_payment_data, customer_id.clone(), merchant_context, resp.request.payment_method_type, billing_name, payment_method_billing_address, business_profile, connector_mandate_reference_id, merchant_connector_id.clone(), vault_operation, payment_method_info, )) .await?; payment_data.payment_method_info = if let Some(payment_method_id) = &payment_method_id { match state .store .find_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), payment_method_id, merchant_context.get_merchant_account().storage_scheme, ) .await { Ok(payment_method) => Some(payment_method), Err(error) => { if error.current_context().is_db_not_found() { logger::info!("Payment Method not found in db {:?}", error); None } else { Err(error) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error retrieving payment method from db") .map_err(|err| logger::error!(payment_method_retrieve=?err)) .ok() } } } } else { None }; let mandate_id = mandate::mandate_procedure( state, resp, &customer_id, payment_method_id.clone(), merchant_connector_id.clone(), merchant_context.get_merchant_account().storage_scheme, payment_data.payment_intent.get_id(), ) .await?; payment_data.payment_attempt.payment_method_id = payment_method_id; payment_data.payment_attempt.mandate_id = mandate_id; payment_data.payment_attempt.connector_mandate_detail = connector_mandate_reference_id .clone() .map(ForeignFrom::foreign_from); payment_data.set_mandate_id(api_models::payments::MandateIds { mandate_id: None, mandate_reference_id: connector_mandate_reference_id.map(|connector_mandate_id| { MandateReferenceId::ConnectorMandateId(connector_mandate_id) }), }); Ok(()) } } #[cfg(feature = "v1")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::CompleteAuthorizeData> for PaymentResponse { async fn update_tracker<'b>( &'b self, db: &'b SessionState, payment_data: PaymentData<F>, response: types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, locale: &Option<String>, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec< RoutableConnectorChoice, >, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile, ) -> RouterResult<PaymentData<F>> where F: 'b + Send, { Box::pin(payment_response_update_tracker( db, payment_data, response, key_store, storage_scheme, locale, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile, )) .await } async fn save_pm_and_mandate<'b>( &self, state: &SessionState, resp: &types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>, merchant_context: &domain::MerchantContext, payment_data: &mut PaymentData<F>, _business_profile: &domain::Profile, ) -> CustomResult<(), errors::ApiErrorResponse> where F: 'b + Clone + Send + Sync, { let (connector_mandate_id, mandate_metadata, connector_mandate_request_reference_id) = resp .response .clone() .ok() .and_then(|resp| { if let types::PaymentsResponseData::TransactionResponse { mandate_reference, .. } = resp { mandate_reference.map(|mandate_ref| { ( mandate_ref.connector_mandate_id.clone(), mandate_ref.mandate_metadata.clone(), mandate_ref.connector_mandate_request_reference_id.clone(), ) }) } else { None } }) .unwrap_or((None, None, None)); update_connector_mandate_details_for_the_flow( connector_mandate_id, mandate_metadata, connector_mandate_request_reference_id, payment_data, )?; update_payment_method_status_and_ntid( state, merchant_context.get_merchant_key_store(), payment_data, resp.status, resp.response.clone(), merchant_context.get_merchant_account().storage_scheme, ) .await?; Ok(()) } } #[cfg(feature = "v1")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( state: &SessionState, mut payment_data: PaymentData<F>, router_data: types::RouterData<F, T, types::PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, locale: &Option<String>, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connectors: Vec< RoutableConnectorChoice, >, #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile, ) -> RouterResult<PaymentData<F>> { // Update additional payment data with the payment method response that we received from connector // This is for details like whether 3ds was upgraded and which version of 3ds was used // also some connectors might send card network details in the response, which is captured and stored let additional_payment_data = payment_data.payment_attempt.get_payment_method_data(); let additional_payment_method_data = match payment_data.payment_method_data.clone() { Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::NetworkToken(_)) | Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardDetailsForNetworkTransactionId(_)) => { payment_data.payment_attempt.payment_method_data.clone() } _ => { additional_payment_data .map(|_| { update_additional_payment_data_with_connector_response_pm_data( payment_data.payment_attempt.payment_method_data.clone(), router_data .connector_response .as_ref() .and_then(|connector_response| { connector_response.additional_payment_method_data.clone() }), ) }) .transpose()? .flatten() } }; router_data.payment_method_status.and_then(|status| { payment_data .payment_method_info .as_mut() .map(|info| info.status = status) }); payment_data.whole_connector_response = router_data.raw_connector_response.clone(); // TODO: refactor of gsm_error_category with respective feature flag #[allow(unused_variables)] let (capture_update, mut payment_attempt_update, gsm_error_category) = match router_data .response .clone() { Err(err) => { let auth_update = if Some(router_data.auth_type) != payment_data.payment_attempt.authentication_type { Some(router_data.auth_type) } else { None }; let (capture_update, attempt_update, gsm_error_category) = match payment_data.multiple_capture_data { Some(multiple_capture_data) => { let capture_update = storage::CaptureUpdate::ErrorUpdate { status: match err.status_code { 500..=511 => enums::CaptureStatus::Pending, _ => enums::CaptureStatus::Failed, }, error_code: Some(err.code), error_message: Some(err.message), error_reason: err.reason, }; let capture_update_list = vec![( multiple_capture_data.get_latest_capture().clone(), capture_update, )]; ( Some((multiple_capture_data, capture_update_list)), auth_update.map(|auth_type| { storage::PaymentAttemptUpdate::AuthenticationTypeUpdate { authentication_type: auth_type, updated_by: storage_scheme.to_string(), } }), None, ) } None => { let connector_name = router_data.connector.to_string(); let flow_name = core_utils::get_flow_name::<F>()?; let option_gsm = payments_helpers::get_gsm_record( state, Some(err.code.clone()), Some(err.message.clone()), connector_name, flow_name.clone(), ) .await; let gsm_unified_code = option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone()); let gsm_unified_message = option_gsm.clone().and_then(|gsm| gsm.unified_message); let (unified_code, unified_message) = if let Some((code, message)) = gsm_unified_code.as_ref().zip(gsm_unified_message.as_ref()) { (code.to_owned(), message.to_owned()) } else { ( consts::DEFAULT_UNIFIED_ERROR_CODE.to_owned(), consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_owned(), ) }; let unified_translated_message = locale .as_ref() .async_and_then(|locale_str| async { payments_helpers::get_unified_translation( state, unified_code.to_owned(), unified_message.to_owned(), locale_str.to_owned(), ) .await }) .await .or(Some(unified_message)); let status = match err.attempt_status { // Use the status sent by connector in error_response if it's present Some(status) => status, None => // mark previous attempt status for technical failures in PSync and ExtendAuthorization flow { if flow_name == "PSync" || flow_name == "ExtendAuthorization" { match err.status_code { // marking failure for 2xx because this is genuine payment failure 200..=299 => enums::AttemptStatus::Failure, _ => router_data.status, } } else if flow_name == "Capture" { match err.status_code { 500..=511 => enums::AttemptStatus::Pending, // don't update the status for 429 error status 429 => router_data.status, _ => enums::AttemptStatus::Failure, } } else { match err.status_code { 500..=511 => enums::AttemptStatus::Pending, _ => enums::AttemptStatus::Failure, } } } }; ( None, Some(storage::PaymentAttemptUpdate::ErrorUpdate { connector: None, status, error_message: Some(Some(err.message.clone())), error_code: Some(Some(err.code.clone())), error_reason: Some(err.reason.clone()), amount_capturable: router_data .request .get_amount_capturable( &payment_data, router_data .minor_amount_capturable .map(MinorUnit::get_amount_as_i64), status, ) .map(MinorUnit::new), updated_by: storage_scheme.to_string(), unified_code: Some(Some(unified_code)), unified_message: Some(unified_translated_message), connector_transaction_id: err.connector_transaction_id.clone(), payment_method_data: additional_payment_method_data, authentication_type: auth_update, issuer_error_code: err.network_decline_code.clone(), issuer_error_message: err.network_error_message.clone(), network_details: Some(ForeignFrom::foreign_from(&err)), }), option_gsm.and_then(|option_gsm| option_gsm.error_category), ) } }; (capture_update, attempt_update, gsm_error_category) } Ok(payments_response) => { // match on connector integrity check match router_data.integrity_check.clone() { Err(err) => { let auth_update = if Some(router_data.auth_type) != payment_data.payment_attempt.authentication_type { Some(router_data.auth_type) } else { None }; let field_name = err.field_names; let connector_transaction_id = err.connector_transaction_id; ( None, Some(storage::PaymentAttemptUpdate::ErrorUpdate { connector: None, status: enums::AttemptStatus::IntegrityFailure, error_message: Some(Some("Integrity Check Failed!".to_string())), error_code: Some(Some("IE".to_string())), error_reason: Some(Some(format!( "Integrity Check Failed! Value mismatched for fields {field_name}" ))), amount_capturable: None, updated_by: storage_scheme.to_string(), unified_code: None, unified_message: None, connector_transaction_id, payment_method_data: None, authentication_type: auth_update, issuer_error_code: None, issuer_error_message: None, network_details: None, }), None, ) } Ok(()) => { let attempt_status = payment_data.payment_attempt.status.to_owned(); let connector_status = router_data.status.to_owned(); let updated_attempt_status = match ( connector_status, attempt_status, payment_data.frm_message.to_owned(), ) { ( enums::AttemptStatus::Authorized, enums::AttemptStatus::Unresolved, Some(frm_message), ) => match frm_message.frm_status { enums::FraudCheckStatus::Fraud | enums::FraudCheckStatus::ManualReview => attempt_status, _ => router_data.get_attempt_status_for_db_update( &payment_data, router_data.amount_captured, router_data .minor_amount_capturable .map(MinorUnit::get_amount_as_i64), )?, }, _ => router_data.get_attempt_status_for_db_update( &payment_data, router_data.amount_captured, router_data .minor_amount_capturable .map(MinorUnit::get_amount_as_i64), )?, }; match payments_response { types::PaymentsResponseData::PreProcessingResponse { pre_processing_id, connector_metadata, connector_response_reference_id, .. } => { let connector_transaction_id = match pre_processing_id.to_owned() { types::PreprocessingResponseId::PreProcessingId(_) => None, types::PreprocessingResponseId::ConnectorTransactionId( connector_txn_id, ) => Some(connector_txn_id), }; let preprocessing_step_id = match pre_processing_id { types::PreprocessingResponseId::PreProcessingId( pre_processing_id, ) => Some(pre_processing_id), types::PreprocessingResponseId::ConnectorTransactionId(_) => None, }; let payment_attempt_update = storage::PaymentAttemptUpdate::PreprocessingUpdate { status: updated_attempt_status, payment_method_id: payment_data .payment_attempt .payment_method_id .clone(), connector_metadata, preprocessing_step_id, connector_transaction_id, connector_response_reference_id, updated_by: storage_scheme.to_string(), }; (None, Some(payment_attempt_update), None) } types::PaymentsResponseData::TransactionResponse { resource_id, redirection_data, connector_metadata, connector_response_reference_id, incremental_authorization_allowed, charges, .. } => { payment_data .payment_intent .incremental_authorization_allowed = core_utils::get_incremental_authorization_allowed_value( incremental_authorization_allowed, payment_data .payment_intent .request_incremental_authorization, ); let connector_transaction_id = match resource_id { types::ResponseId::NoResponseId => None, types::ResponseId::ConnectorTransactionId(ref id) | types::ResponseId::EncodedData(ref id) => Some(id), }; let resp_network_transaction_id = router_data.response.as_ref() .map_err(|err| { logger::error!(error = ?err, "Failed to obtain the network_transaction_id from payment response"); }) .ok() .and_then(|resp| resp.get_network_transaction_id()); let encoded_data = payment_data.payment_attempt.encoded_data.clone(); let authentication_data = (*redirection_data) .as_ref() .map(Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not parse the connector response")?; let auth_update = if Some(router_data.auth_type) != payment_data.payment_attempt.authentication_type { Some(router_data.auth_type) } else { None }; // incase of success, update error code and error message let error_status = if router_data.status == enums::AttemptStatus::Charged { Some(None) } else { None }; // update connector_mandate_details in case of Authorized/Charged Payment Status if matches!( router_data.status, enums::AttemptStatus::Charged | enums::AttemptStatus::Authorized | enums::AttemptStatus::PartiallyAuthorized ) { payment_data .payment_intent .fingerprint_id .clone_from(&payment_data.payment_attempt.fingerprint_id); if let Some(payment_method) = payment_data.payment_method_info.clone() { // Parse value to check for mandates' existence let mandate_details = payment_method .get_common_mandate_reference() .change_context( errors::ApiErrorResponse::InternalServerError, ) .attach_printable( "Failed to deserialize to Payment Mandate Reference ", )?; if let Some(mca_id) = payment_data.payment_attempt.merchant_connector_id.clone() { // check if the mandate has not already been set to active if !mandate_details.payments .as_ref() .and_then(|payments| payments.0.get(&mca_id)) .map(|payment_mandate_reference_record| payment_mandate_reference_record.connector_mandate_status == Some(common_enums::ConnectorMandateStatus::Active)) .unwrap_or(false) { let (connector_mandate_id, mandate_metadata,connector_mandate_request_reference_id) = payment_data.payment_attempt.connector_mandate_detail.clone() .map(|cmr| (cmr.connector_mandate_id, cmr.mandate_metadata,cmr.connector_mandate_request_reference_id)) .unwrap_or((None, None,None)); // Update the connector mandate details with the payment attempt connector mandate id let connector_mandate_details = tokenization::update_connector_mandate_details( Some(mandate_details), payment_data.payment_attempt.payment_method_type, Some( payment_data .payment_attempt .net_amount .get_total_amount() .get_amount_as_i64(), ), payment_data.payment_attempt.currency, payment_data.payment_attempt.merchant_connector_id.clone(), connector_mandate_id, mandate_metadata, connector_mandate_request_reference_id )?; // Update the payment method table with the active mandate record payment_methods::cards::update_payment_method_connector_mandate_details( state, key_store, &*state.store, payment_method, connector_mandate_details, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; } } } metrics::SUCCESSFUL_PAYMENT.add(1, &[]); } let payment_method_id = payment_data.payment_attempt.payment_method_id.clone(); let debit_routing_savings = payment_data.payment_method_data.as_ref().and_then(|data| { payments_helpers::get_debit_routing_savings_amount( data, &payment_data.payment_attempt, ) }); utils::add_apple_pay_payment_status_metrics( router_data.status, router_data.apple_pay_flow.clone(), payment_data.payment_attempt.connector.clone(), payment_data.payment_attempt.merchant_id.clone(), ); let is_overcapture_enabled = router_data .connector_response .as_ref() .and_then(|connector_response| { connector_response.is_overcapture_enabled() }).or_else(|| { payment_data.payment_intent .enable_overcapture .as_ref() .map(|enable_overcapture| common_types::primitive_wrappers::OvercaptureEnabledBool::new(*enable_overcapture.deref())) }); let (capture_before, extended_authorization_applied) = router_data .connector_response .as_ref() .and_then(|connector_response| { connector_response.get_extended_authorization_response_data() }) .map(|extended_auth_resp| { ( extended_auth_resp.capture_before, extended_auth_resp.extended_authentication_applied, ) }) .unwrap_or((None, None)); let (capture_updates, payment_attempt_update) = match payment_data .multiple_capture_data { Some(multiple_capture_data) => { let (connector_capture_id, processor_capture_data) = match resource_id { types::ResponseId::NoResponseId => (None, None), types::ResponseId::ConnectorTransactionId(id) | types::ResponseId::EncodedData(id) => { let (txn_id, txn_data) = ConnectorTransactionId::form_id_and_data(id); (Some(txn_id), txn_data) } }; let capture_update = storage::CaptureUpdate::ResponseUpdate { status: enums::CaptureStatus::foreign_try_from( router_data.status, )?, connector_capture_id: connector_capture_id.clone(), connector_response_reference_id, processor_capture_data: processor_capture_data.clone(), }; let capture_update_list = vec![( multiple_capture_data.get_latest_capture().clone(), capture_update, )]; (Some((multiple_capture_data, capture_update_list)), auth_update.map(|auth_type| { storage::PaymentAttemptUpdate::AuthenticationTypeUpdate { authentication_type: auth_type, updated_by: storage_scheme.to_string(), } })) } None => ( None, Some(storage::PaymentAttemptUpdate::ResponseUpdate { status: updated_attempt_status, connector: None, connector_transaction_id: connector_transaction_id.cloned(), authentication_type: auth_update, amount_capturable: router_data .request .get_amount_capturable( &payment_data, router_data .minor_amount_capturable .map(MinorUnit::get_amount_as_i64), updated_attempt_status, ) .map(MinorUnit::new), payment_method_id, mandate_id: payment_data.payment_attempt.mandate_id.clone(), connector_metadata, payment_token: None, error_code: error_status.clone(), error_message: error_status.clone(), error_reason: error_status.clone(), unified_code: error_status.clone(), unified_message: error_status, connector_response_reference_id, updated_by: storage_scheme.to_string(), authentication_data, encoded_data, payment_method_data: additional_payment_method_data, capture_before, extended_authorization_applied, connector_mandate_detail: payment_data .payment_attempt .connector_mandate_detail .clone(), charges, setup_future_usage_applied: payment_data .payment_attempt .setup_future_usage_applied, debit_routing_savings, network_transaction_id: resp_network_transaction_id, is_overcapture_enabled, authorized_amount: router_data.authorized_amount, }), ), }; (capture_updates, payment_attempt_update, None) } types::PaymentsResponseData::TransactionUnresolvedResponse { resource_id, reason, connector_response_reference_id, } => { let connector_transaction_id = match resource_id { types::ResponseId::NoResponseId => None, types::ResponseId::ConnectorTransactionId(id) | types::ResponseId::EncodedData(id) => Some(id), }; ( None, Some(storage::PaymentAttemptUpdate::UnresolvedResponseUpdate { status: updated_attempt_status, connector: None, connector_transaction_id, payment_method_id: payment_data .payment_attempt .payment_method_id .clone(), error_code: Some(reason.clone().map(|cd| cd.code)), error_message: Some(reason.clone().map(|cd| cd.message)), error_reason: Some(reason.map(|cd| cd.message)), connector_response_reference_id, updated_by: storage_scheme.to_string(), }), None, ) } types::PaymentsResponseData::SessionResponse { .. } => (None, None, None), types::PaymentsResponseData::SessionTokenResponse { .. } => { (None, None, None) } types::PaymentsResponseData::TokenizationResponse { .. } => { (None, None, None) } types::PaymentsResponseData::ConnectorCustomerResponse(..) => { (None, None, None) } types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => { (None, None, None) } types::PaymentsResponseData::PostProcessingResponse { .. } => { (None, None, None) } types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => (None, None, None), types::PaymentsResponseData::PaymentResourceUpdateResponse { .. } => { (None, None, None) } types::PaymentsResponseData::MultipleCaptureResponse { capture_sync_response_list, } => match payment_data.multiple_capture_data { Some(multiple_capture_data) => { let capture_update_list = response_to_capture_update( &multiple_capture_data, capture_sync_response_list, )?; ( Some((multiple_capture_data, capture_update_list)), None, None, ) } None => (None, None, None), }, types::PaymentsResponseData::PaymentsCreateOrderResponse { .. } => { (None, None, None) } } } } } }; payment_data.multiple_capture_data = match capture_update { Some((mut multiple_capture_data, capture_updates)) => { for (capture, capture_update) in capture_updates { let updated_capture = state .store .update_capture_with_capture_id(capture, capture_update, storage_scheme) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; multiple_capture_data.update_capture(updated_capture); } let authorized_amount = payment_data .payment_attempt .authorized_amount .unwrap_or_else(|| payment_data.payment_attempt.get_total_amount()); payment_attempt_update = Some(storage::PaymentAttemptUpdate::AmountToCaptureUpdate { status: multiple_capture_data.get_attempt_status(authorized_amount), amount_capturable: authorized_amount - multiple_capture_data.get_total_blocked_amount(), updated_by: storage_scheme.to_string(), }); Some(multiple_capture_data) } None => None, }; // Stage 1 let payment_attempt = payment_data.payment_attempt.clone(); let m_db = state.clone().store; let m_payment_attempt_update = payment_attempt_update.clone(); let m_payment_attempt = payment_attempt.clone(); let payment_attempt = payment_attempt_update .map(|payment_attempt_update| { PaymentAttempt::from_storage_model( payment_attempt_update .to_storage_model() .apply_changeset(payment_attempt.clone().to_storage_model()), ) }) .unwrap_or_else(|| payment_attempt); let payment_attempt_fut = tokio::spawn( async move { Box::pin(async move { Ok::<_, error_stack::Report<errors::ApiErrorResponse>>( match m_payment_attempt_update { Some(payment_attempt_update) => m_db .update_payment_attempt_with_attempt_id( m_payment_attempt, payment_attempt_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?, None => m_payment_attempt, }, ) }) .await } .in_current_span(), ); payment_data.payment_attempt = payment_attempt; payment_data.authentication = match payment_data.authentication { Some(mut authentication_store) => { let authentication_update = storage::AuthenticationUpdate::PostAuthorizationUpdate { authentication_lifecycle_status: enums::AuthenticationLifecycleStatus::Used, }; let updated_authentication = state .store .update_authentication_by_merchant_id_authentication_id( authentication_store.authentication, authentication_update, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; authentication_store.authentication = updated_authentication; Some(authentication_store) } None => None, }; let amount_captured = get_total_amount_captured( &router_data.request, router_data.amount_captured.map(MinorUnit::new), router_data.status, &payment_data, ); let payment_intent_update = match &router_data.response { Err(_) => storage::PaymentIntentUpdate::PGStatusUpdate { status: api_models::enums::IntentStatus::foreign_from( payment_data.payment_attempt.status, ), updated_by: storage_scheme.to_string(), // make this false only if initial payment fails, if incremental authorization call fails don't make it false incremental_authorization_allowed: Some(false), feature_metadata: payment_data .payment_intent .feature_metadata .clone() .map(masking::Secret::new), }, Ok(_) => storage::PaymentIntentUpdate::ResponseUpdate { status: api_models::enums::IntentStatus::foreign_from( payment_data.payment_attempt.status, ), amount_captured, updated_by: storage_scheme.to_string(), fingerprint_id: payment_data.payment_attempt.fingerprint_id.clone(), incremental_authorization_allowed: payment_data .payment_intent .incremental_authorization_allowed, feature_metadata: payment_data .payment_intent .feature_metadata .clone() .map(masking::Secret::new), }, }; let m_db = state.clone().store; let m_key_store = key_store.clone(); let m_payment_data_payment_intent = payment_data.payment_intent.clone(); let m_payment_intent_update = payment_intent_update.clone(); let key_manager_state: KeyManagerState = state.into(); let payment_intent_fut = tokio::spawn( async move { m_db.update_payment_intent( &key_manager_state, m_payment_data_payment_intent, m_payment_intent_update, &m_key_store, storage_scheme, ) .map(|x| x.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)) .await } .in_current_span(), ); // When connector requires redirection for mandate creation it can update the connector mandate_id during Psync and CompleteAuthorize let m_db = state.clone().store; let m_router_data_merchant_id = router_data.merchant_id.clone(); let m_payment_method_id = payment_data.payment_attempt.payment_method_id.clone(); let m_payment_data_mandate_id = payment_data .payment_attempt .mandate_id .clone() .or(payment_data .mandate_id .clone() .and_then(|mandate_ids| mandate_ids.mandate_id)); let m_router_data_response = router_data.response.clone(); let mandate_update_fut = tokio::spawn( async move { mandate::update_connector_mandate_id( m_db.as_ref(), &m_router_data_merchant_id, m_payment_data_mandate_id, m_payment_method_id, m_router_data_response, storage_scheme, ) .await } .in_current_span(), ); let (payment_intent, _, payment_attempt) = futures::try_join!( utils::flatten_join_error(payment_intent_fut), utils::flatten_join_error(mandate_update_fut), utils::flatten_join_error(payment_attempt_fut) )?; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] { if payment_intent.status.is_in_terminal_state() && business_profile.dynamic_routing_algorithm.is_some() { let dynamic_routing_algo_ref: api_models::routing::DynamicRoutingAlgorithmRef = business_profile .dynamic_routing_algorithm .clone() .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")? .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("DynamicRoutingAlgorithmRef not found in profile")?; let state = state.clone(); let profile_id = business_profile.get_id().to_owned(); let payment_attempt = payment_attempt.clone(); let dynamic_routing_config_params_interpolator = routing_helpers::DynamicRoutingConfigParamsInterpolator::new( payment_attempt.payment_method, payment_attempt.payment_method_type, payment_attempt.authentication_type, payment_attempt.currency, payment_data .address .get_payment_billing() .and_then(|address| address.clone().address) .and_then(|address| address.country), payment_attempt .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|card| card.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()), payment_attempt .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|card| card.get("card")) .and_then(|data| data.as_object()) .and_then(|card| card.get("card_isin")) .and_then(|card_isin| card_isin.as_str()) .map(|card_isin| card_isin.to_string()), ); tokio::spawn( async move { let should_route_to_open_router = state.conf.open_router.dynamic_routing_enabled; let is_success_rate_based = matches!( payment_attempt.routing_approach, Some(enums::RoutingApproach::SuccessRateExploitation) | Some(enums::RoutingApproach::SuccessRateExploration) ); if should_route_to_open_router && is_success_rate_based { 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( &state, &payment_attempt, routable_connectors, &profile_id, dynamic_routing_algo_ref, dynamic_routing_config_params_interpolator, ) .await .map_err(|e| logger::error!(contract_based_routing_metrics_error=?e)) .ok(); } } .in_current_span(), ); } } payment_data.payment_intent = payment_intent; payment_data.payment_attempt = payment_attempt; router_data.payment_method_status.and_then(|status| { payment_data .payment_method_info .as_mut() .map(|info| info.status = status) }); if payment_data.payment_attempt.status == enums::AttemptStatus::Failure { let _ = card_testing_guard_utils::increment_blocked_count_in_cache( state, payment_data.card_testing_guard_data.clone(), ) .await; } match router_data.integrity_check { Ok(()) => Ok(payment_data), Err(err) => { metrics::INTEGRITY_CHECK_FAILED.add( 1, router_env::metric_attributes!( ( "connector", payment_data .payment_attempt .connector .clone() .unwrap_or_default(), ), ( "merchant_id", payment_data.payment_attempt.merchant_id.clone(), ) ), ); Err(error_stack::Report::new( errors::ApiErrorResponse::IntegrityCheckFailed { connector_transaction_id: payment_data .payment_attempt .get_connector_payment_id() .map(ToString::to_string), reason: payment_data .payment_attempt .error_message .unwrap_or_default(), field_names: err.field_names, }, )) } } } #[cfg(feature = "v2")] async fn update_payment_method_status_and_ntid<F: Clone>( state: &SessionState, key_store: &domain::MerchantKeyStore, payment_data: &mut PaymentData<F>, attempt_status: common_enums::AttemptStatus, payment_response: Result<types::PaymentsResponseData, ErrorResponse>, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<()> { todo!() } #[cfg(feature = "v1")] async fn update_payment_method_status_and_ntid<F: Clone>( state: &SessionState, key_store: &domain::MerchantKeyStore, payment_data: &mut PaymentData<F>, attempt_status: common_enums::AttemptStatus, payment_response: Result<types::PaymentsResponseData, ErrorResponse>, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<()> { // If the payment_method is deleted then ignore the error related to retrieving payment method // This should be handled when the payment method is soft deleted if let Some(id) = &payment_data.payment_attempt.payment_method_id { let payment_method = match state .store .find_payment_method(&(state.into()), key_store, id, storage_scheme) .await { Ok(payment_method) => payment_method, Err(error) => { if error.current_context().is_db_not_found() { logger::info!( "Payment Method not found in db and skipping payment method update {:?}", error ); return Ok(()); } else { Err(error) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error retrieving payment method from db in update_payment_method_status_and_ntid")? } } }; let pm_resp_network_transaction_id = payment_response .map(|resp| if let types::PaymentsResponseData::TransactionResponse { network_txn_id: network_transaction_id, .. } = resp { network_transaction_id } else {None}) .map_err(|err| { logger::error!(error=?err, "Failed to obtain the network_transaction_id from payment response"); }) .ok() .flatten(); let network_transaction_id = if payment_data.payment_intent.setup_future_usage == Some(diesel_models::enums::FutureUsage::OffSession) { if pm_resp_network_transaction_id.is_some() { pm_resp_network_transaction_id } else { logger::info!("Skip storing network transaction id"); None } } else { None }; let pm_update = if payment_method.status != common_enums::PaymentMethodStatus::Active && payment_method.status != attempt_status.into() { let updated_pm_status = common_enums::PaymentMethodStatus::from(attempt_status); payment_data .payment_method_info .as_mut() .map(|info| info.status = updated_pm_status); storage::PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate { network_transaction_id, status: Some(updated_pm_status), } } else { storage::PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate { network_transaction_id, status: None, } }; state .store .update_payment_method( &(state.into()), key_store, payment_method, pm_update, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; }; Ok(()) } #[cfg(feature = "v2")] impl<F: Send + Clone> Operation<F, types::PaymentsAuthorizeData> for &PaymentResponse { type Data = PaymentConfirmData<F>; fn to_post_update_tracker( &self, ) -> RouterResult< &(dyn PostUpdateTracker<F, Self::Data, types::PaymentsAuthorizeData> + Send + Sync), > { Ok(*self) } } #[cfg(feature = "v2")] impl<F: Send + Clone> Operation<F, types::PaymentsAuthorizeData> for PaymentResponse { type Data = PaymentConfirmData<F>; fn to_post_update_tracker( &self, ) -> RouterResult< &(dyn PostUpdateTracker<F, Self::Data, types::PaymentsAuthorizeData> + Send + Sync), > { Ok(self) } } #[cfg(feature = "v2")] impl<F: Send + Clone> Operation<F, types::PaymentsCaptureData> for PaymentResponse { type Data = hyperswitch_domain_models::payments::PaymentCaptureData<F>; fn to_post_update_tracker( &self, ) -> RouterResult< &(dyn PostUpdateTracker<F, Self::Data, types::PaymentsCaptureData> + Send + Sync), > { Ok(self) } } #[cfg(feature = "v2")] #[async_trait] impl<F: Clone> PostUpdateTracker< F, hyperswitch_domain_models::payments::PaymentCaptureData<F>, types::PaymentsCaptureData, > for PaymentResponse { async fn update_tracker<'b>( &'b self, state: &'b SessionState, mut payment_data: hyperswitch_domain_models::payments::PaymentCaptureData<F>, response: types::RouterData<F, types::PaymentsCaptureData, types::PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<hyperswitch_domain_models::payments::PaymentCaptureData<F>> where F: 'b + Send + Sync, types::RouterData<F, types::PaymentsCaptureData, types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects< F, types::PaymentsCaptureData, hyperswitch_domain_models::payments::PaymentCaptureData<F>, >, { use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects; let db = &*state.store; let key_manager_state = &state.into(); let response_router_data = response; let payment_intent_update = response_router_data.get_payment_intent_update(&payment_data, storage_scheme); let payment_attempt_update = response_router_data.get_payment_attempt_update(&payment_data, storage_scheme); let updated_payment_intent = db .update_payment_intent( key_manager_state, payment_data.payment_intent, payment_intent_update, key_store, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment intent")?; let updated_payment_attempt = db .update_payment_attempt( key_manager_state, key_store, payment_data.payment_attempt, payment_attempt_update, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment attempt")?; payment_data.payment_intent = updated_payment_intent; payment_data.payment_attempt = updated_payment_attempt; Ok(payment_data) } } #[cfg(feature = "v2")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::PaymentsAuthorizeData> for PaymentResponse { async fn update_tracker<'b>( &'b self, state: &'b SessionState, mut payment_data: PaymentConfirmData<F>, response: types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<PaymentConfirmData<F>> where F: 'b + Send + Sync, types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects< F, types::PaymentsAuthorizeData, PaymentConfirmData<F>, >, { use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects; let db = &*state.store; let key_manager_state = &state.into(); let response_router_data = response; let payment_intent_update = response_router_data.get_payment_intent_update(&payment_data, storage_scheme); let payment_attempt_update = response_router_data.get_payment_attempt_update(&payment_data, storage_scheme); let updated_payment_intent = db .update_payment_intent( key_manager_state, payment_data.payment_intent, payment_intent_update, key_store, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment intent")?; let updated_payment_attempt = db .update_payment_attempt( key_manager_state, key_store, payment_data.payment_attempt, payment_attempt_update, storage_scheme, ) .await .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::VoidedPostCharge | 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::Expired => (), common_enums::AttemptStatus::Started | common_enums::AttemptStatus::AuthenticationPending | common_enums::AttemptStatus::AuthenticationSuccessful | common_enums::AttemptStatus::Authorized | common_enums::AttemptStatus::PartiallyAuthorized | 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 | common_enums::AttemptStatus::IntegrityFailure => { 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) } } #[cfg(feature = "v2")] impl<F: Send + Clone> Operation<F, types::PaymentsSyncData> for PaymentResponse { type Data = PaymentStatusData<F>; fn to_post_update_tracker( &self, ) -> RouterResult<&(dyn PostUpdateTracker<F, Self::Data, types::PaymentsSyncData> + Send + Sync)> { Ok(self) } } #[cfg(feature = "v2")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentStatusData<F>, types::PaymentsSyncData> for PaymentResponse { async fn update_tracker<'b>( &'b self, state: &'b SessionState, mut payment_data: PaymentStatusData<F>, response: types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<PaymentStatusData<F>> where F: 'b + Send + Sync, types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects< F, types::PaymentsSyncData, PaymentStatusData<F>, >, { use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects; let db = &*state.store; let key_manager_state = &state.into(); let response_router_data = response; let payment_intent_update = response_router_data.get_payment_intent_update(&payment_data, storage_scheme); let payment_attempt_update = response_router_data.get_payment_attempt_update(&payment_data, storage_scheme); let payment_attempt = payment_data.payment_attempt; let updated_payment_intent = db .update_payment_intent( key_manager_state, payment_data.payment_intent, payment_intent_update, key_store, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment intent")?; let updated_payment_attempt = db .update_payment_attempt( key_manager_state, key_store, payment_attempt, payment_attempt_update, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment attempt")?; payment_data.payment_intent = updated_payment_intent; payment_data.payment_attempt = updated_payment_attempt; Ok(payment_data) } } #[cfg(feature = "v2")] impl<F: Send + Clone> Operation<F, types::SetupMandateRequestData> for &PaymentResponse { type Data = PaymentConfirmData<F>; fn to_post_update_tracker( &self, ) -> RouterResult< &(dyn PostUpdateTracker<F, Self::Data, types::SetupMandateRequestData> + Send + Sync), > { Ok(*self) } } #[cfg(feature = "v2")] impl<F: Send + Clone> Operation<F, types::SetupMandateRequestData> for PaymentResponse { type Data = PaymentConfirmData<F>; fn to_post_update_tracker( &self, ) -> RouterResult< &(dyn PostUpdateTracker<F, Self::Data, types::SetupMandateRequestData> + Send + Sync), > { Ok(self) } } #[cfg(feature = "v2")] impl Operation< hyperswitch_domain_models::router_flow_types::ExternalVaultProxy, hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData, > for PaymentResponse { type Data = PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>; fn to_post_update_tracker( &self, ) -> RouterResult< &(dyn PostUpdateTracker< hyperswitch_domain_models::router_flow_types::ExternalVaultProxy, Self::Data, hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData, > + Send + Sync), > { Ok(self) } } #[cfg(feature = "v2")] impl Operation< hyperswitch_domain_models::router_flow_types::ExternalVaultProxy, hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData, > for &PaymentResponse { type Data = PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>; fn to_post_update_tracker( &self, ) -> RouterResult< &(dyn PostUpdateTracker< hyperswitch_domain_models::router_flow_types::ExternalVaultProxy, Self::Data, hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData, > + Send + Sync), > { Ok(*self) } } #[cfg(feature = "v2")] #[async_trait] impl PostUpdateTracker< hyperswitch_domain_models::router_flow_types::ExternalVaultProxy, PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>, hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData, > for PaymentResponse { async fn update_tracker<'b>( &'b self, state: &'b SessionState, mut payment_data: PaymentConfirmData< hyperswitch_domain_models::router_flow_types::ExternalVaultProxy, >, response: types::RouterData< hyperswitch_domain_models::router_flow_types::ExternalVaultProxy, hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData, types::PaymentsResponseData, >, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult< PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>, > where types::RouterData< hyperswitch_domain_models::router_flow_types::ExternalVaultProxy, hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData, types::PaymentsResponseData, >: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects< hyperswitch_domain_models::router_flow_types::ExternalVaultProxy, hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData, PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>, >, { use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects; let db = &*state.store; let key_manager_state = &state.into(); let response_router_data = response; let payment_intent_update = response_router_data.get_payment_intent_update(&payment_data, storage_scheme); let payment_attempt_update = response_router_data.get_payment_attempt_update(&payment_data, storage_scheme); let updated_payment_intent = db .update_payment_intent( key_manager_state, payment_data.payment_intent, payment_intent_update, key_store, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment intent")?; let updated_payment_attempt = db .update_payment_attempt( key_manager_state, key_store, payment_data.payment_attempt, payment_attempt_update, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment attempt")?; payment_data.payment_intent = updated_payment_intent; payment_data.payment_attempt = updated_payment_attempt; // TODO: Add external vault specific post-update logic if needed Ok(payment_data) } } #[cfg(feature = "v2")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::SetupMandateRequestData> for PaymentResponse { async fn update_tracker<'b>( &'b self, state: &'b SessionState, mut payment_data: PaymentConfirmData<F>, response: types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<PaymentConfirmData<F>> where F: 'b + Send + Sync, types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects< F, types::SetupMandateRequestData, PaymentConfirmData<F>, >, { use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects; let db = &*state.store; let key_manager_state = &state.into(); let response_router_data = response; let payment_intent_update = response_router_data.get_payment_intent_update(&payment_data, storage_scheme); let payment_attempt_update = response_router_data.get_payment_attempt_update(&payment_data, storage_scheme); let updated_payment_intent = db .update_payment_intent( key_manager_state, payment_data.payment_intent, payment_intent_update, key_store, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment intent")?; let updated_payment_attempt = db .update_payment_attempt( key_manager_state, key_store, payment_data.payment_attempt, payment_attempt_update, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment attempt")?; payment_data.payment_intent = updated_payment_intent; payment_data.payment_attempt = updated_payment_attempt; Ok(payment_data) } async fn save_pm_and_mandate<'b>( &self, state: &SessionState, router_data: &types::RouterData< F, types::SetupMandateRequestData, types::PaymentsResponseData, >, merchant_context: &domain::MerchantContext, payment_data: &mut PaymentConfirmData<F>, business_profile: &domain::Profile, ) -> CustomResult<(), errors::ApiErrorResponse> where F: 'b + Clone + Send + Sync, { // If we received a payment_method_id from connector in the router data response // Then we either update the payment method or create a new payment method // The case for updating the payment method is when the payment is created from the payment method service let Ok(payments_response) = &router_data.response else { // In case there was an error response from the connector // We do not take any action related to the payment method return Ok(()); }; let connector_request_reference_id = payment_data .payment_attempt .connector_token_details .as_ref() .and_then(|token_details| token_details.get_connector_token_request_reference_id()); let connector_token = payments_response.get_updated_connector_token_details(connector_request_reference_id); let payment_method_id = payment_data.payment_attempt.payment_method_id.clone(); // TODO: check what all conditions we will need to see if card need to be saved match ( connector_token .as_ref() .and_then(|connector_token| connector_token.connector_mandate_id.clone()), payment_method_id, ) { (Some(token), Some(payment_method_id)) => { if !matches!( router_data.status, enums::AttemptStatus::Charged | enums::AttemptStatus::Authorized ) { return Ok(()); } let connector_id = payment_data .payment_attempt .merchant_connector_id .clone() .get_required_value("merchant_connector_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing connector id")?; let net_amount = payment_data.payment_attempt.amount_details.get_net_amount(); let currency = payment_data.payment_intent.amount_details.currency; let connector_token_details_for_payment_method_update = api_models::payment_methods::ConnectorTokenDetails { connector_id, status: common_enums::ConnectorTokenStatus::Active, connector_token_request_reference_id: connector_token .and_then(|details| details.connector_token_request_reference_id), original_payment_authorized_amount: Some(net_amount), original_payment_authorized_currency: Some(currency), metadata: None, token: masking::Secret::new(token), token_type: common_enums::TokenizationType::MultiUse, }; let payment_method_update_request = api_models::payment_methods::PaymentMethodUpdate { payment_method_data: None, connector_token_details: Some( connector_token_details_for_payment_method_update, ), }; payment_methods::update_payment_method_core( state, merchant_context, business_profile, payment_method_update_request, &payment_method_id, ) .await .attach_printable("Failed to update payment method")?; } (Some(_), None) => { // TODO: create a new payment method } (None, Some(_)) | (None, None) => {} } Ok(()) } } #[cfg(feature = "v1")] fn update_connector_mandate_details_for_the_flow<F: Clone>( connector_mandate_id: Option<String>, mandate_metadata: Option<masking::Secret<serde_json::Value>>, connector_mandate_request_reference_id: Option<String>, payment_data: &mut PaymentData<F>, ) -> RouterResult<()> { let mut original_connector_mandate_reference_id = payment_data .payment_attempt .connector_mandate_detail .as_ref() .map(|detail| ConnectorMandateReferenceId::foreign_from(detail.clone())); let connector_mandate_reference_id = if connector_mandate_id.is_some() { if let Some(ref mut record) = original_connector_mandate_reference_id { record.update( connector_mandate_id, None, None, mandate_metadata, connector_mandate_request_reference_id, ); Some(record.clone()) } else { Some(ConnectorMandateReferenceId::new( connector_mandate_id, None, None, mandate_metadata, connector_mandate_request_reference_id, )) } } else { original_connector_mandate_reference_id }; payment_data.payment_attempt.connector_mandate_detail = connector_mandate_reference_id .clone() .map(ForeignFrom::foreign_from); payment_data.set_mandate_id(api_models::payments::MandateIds { mandate_id: None, mandate_reference_id: connector_mandate_reference_id.map(|connector_mandate_id| { MandateReferenceId::ConnectorMandateId(connector_mandate_id) }), }); Ok(()) } fn response_to_capture_update( multiple_capture_data: &MultipleCaptureData, response_list: HashMap<String, CaptureSyncResponse>, ) -> RouterResult<Vec<(storage::Capture, storage::CaptureUpdate)>> { let mut capture_update_list = vec![]; let mut unmapped_captures = vec![]; for (connector_capture_id, capture_sync_response) in response_list { let capture = multiple_capture_data.get_capture_by_connector_capture_id(&connector_capture_id); if let Some(capture) = capture { capture_update_list.push(( capture.clone(), storage::CaptureUpdate::foreign_try_from(capture_sync_response)?, )) } else { // connector_capture_id may not be populated in the captures table in some case // if so, we try to map the unmapped capture response and captures in DB. unmapped_captures.push(capture_sync_response) } } capture_update_list.extend(get_capture_update_for_unmapped_capture_responses( unmapped_captures, multiple_capture_data, )?); Ok(capture_update_list) } fn get_capture_update_for_unmapped_capture_responses( unmapped_capture_sync_response_list: Vec<CaptureSyncResponse>, multiple_capture_data: &MultipleCaptureData, ) -> RouterResult<Vec<(storage::Capture, storage::CaptureUpdate)>> { let mut result = Vec::new(); let captures_without_connector_capture_id: Vec<_> = multiple_capture_data .get_pending_captures_without_connector_capture_id() .into_iter() .cloned() .collect(); for capture_sync_response in unmapped_capture_sync_response_list { if let Some(capture) = captures_without_connector_capture_id .iter() .find(|capture| { capture_sync_response.get_connector_response_reference_id() == Some(capture.capture_id.clone()) || capture_sync_response.get_amount_captured() == Some(capture.amount) }) { result.push(( capture.clone(), storage::CaptureUpdate::foreign_try_from(capture_sync_response)?, )) } } Ok(result) } fn get_total_amount_captured<F: Clone, T: types::Capturable>( request: &T, amount_captured: Option<MinorUnit>, router_data_status: enums::AttemptStatus, payment_data: &PaymentData<F>, ) -> Option<MinorUnit> { match &payment_data.multiple_capture_data { Some(multiple_capture_data) => { //multiple capture Some(multiple_capture_data.get_total_blocked_amount()) } None => { //Non multiple capture let amount = request .get_captured_amount( amount_captured.map(MinorUnit::get_amount_as_i64), payment_data, ) .map(MinorUnit::new); amount_captured.or_else(|| { if router_data_status == enums::AttemptStatus::Charged { amount } else { None } }) } } } #[cfg(feature = "v2")] impl<F: Send + Clone + Sync> Operation<F, types::PaymentsCancelData> for PaymentResponse { type Data = hyperswitch_domain_models::payments::PaymentCancelData<F>; fn to_post_update_tracker( &self, ) -> RouterResult< &(dyn PostUpdateTracker<F, Self::Data, types::PaymentsCancelData> + Send + Sync), > { Ok(self) } } #[cfg(feature = "v2")] #[async_trait] impl<F: Clone + Send + Sync> PostUpdateTracker< F, hyperswitch_domain_models::payments::PaymentCancelData<F>, types::PaymentsCancelData, > for PaymentResponse { async fn update_tracker<'b>( &'b self, state: &'b SessionState, mut payment_data: hyperswitch_domain_models::payments::PaymentCancelData<F>, router_data: types::RouterData<F, types::PaymentsCancelData, types::PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<hyperswitch_domain_models::payments::PaymentCancelData<F>> where F: 'b + Send + Sync, types::RouterData<F, types::PaymentsCancelData, types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects< F, types::PaymentsCancelData, hyperswitch_domain_models::payments::PaymentCancelData<F>, >, { let db = &*state.store; let key_manager_state = &state.into(); use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects; let payment_intent_update = router_data.get_payment_intent_update(&payment_data, storage_scheme); let updated_payment_intent = db .update_payment_intent( key_manager_state, payment_data.payment_intent.clone(), payment_intent_update, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Error while updating the payment_intent")?; let payment_attempt_update = router_data.get_payment_attempt_update(&payment_data, storage_scheme); let updated_payment_attempt = db .update_payment_attempt( key_manager_state, key_store, payment_data.payment_attempt.clone(), payment_attempt_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Error while updating the payment_attempt")?; payment_data.set_payment_intent(updated_payment_intent); payment_data.set_payment_attempt(updated_payment_attempt); Ok(payment_data) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_response.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_router_592966966356622010
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_get_intent.rs // Contains: 1 structs, 0 enums use std::marker::PhantomData; use api_models::{enums::FrmSuggestion, payments::PaymentsGetIntentRequest}; 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, helpers, operations}, }, db::errors::StorageErrorExt, routes::{app::ReqState, SessionState}, types::{ api, domain, storage::{self, enums}, }, }; #[derive(Debug, Clone, Copy)] pub struct PaymentGetIntent; impl<F: Send + Clone + Sync> Operation<F, PaymentsGetIntentRequest> for &PaymentGetIntent { type Data = payments::PaymentIntentData<F>; fn to_validate_request( &self, ) -> RouterResult<&(dyn ValidateRequest<F, PaymentsGetIntentRequest, Self::Data> + Send + Sync)> { Ok(*self) } fn to_get_tracker( &self, ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsGetIntentRequest> + Send + Sync)> { Ok(*self) } fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentsGetIntentRequest, Self::Data>)> { Ok(*self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsGetIntentRequest> + Send + Sync)> { Ok(*self) } } impl<F: Send + Clone + Sync> Operation<F, PaymentsGetIntentRequest> for PaymentGetIntent { type Data = payments::PaymentIntentData<F>; fn to_validate_request( &self, ) -> RouterResult<&(dyn ValidateRequest<F, PaymentsGetIntentRequest, Self::Data> + Send + Sync)> { Ok(self) } fn to_get_tracker( &self, ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsGetIntentRequest> + Send + Sync)> { Ok(self) } fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsGetIntentRequest, Self::Data>> { Ok(self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsGetIntentRequest> + Send + Sync)> { Ok(self) } } type PaymentsGetIntentOperation<'b, F> = BoxedOperation<'b, F, PaymentsGetIntentRequest, payments::PaymentIntentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentIntentData<F>, PaymentsGetIntentRequest> for PaymentGetIntent { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, _payment_id: &common_utils::id_type::GlobalPaymentId, request: &PaymentsGetIntentRequest, merchant_context: &domain::MerchantContext, _profile: &domain::Profile, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<operations::GetTrackerResponse<payments::PaymentIntentData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_intent = db .find_payment_intent_by_id( key_manager_state, &request.id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, // todo : add a way to fetch client secret if required client_secret: None, sessions_token: vec![], vault_session_details: None, connector_customer_id: None, }; let get_trackers_response = operations::GetTrackerResponse { payment_data }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, payments::PaymentIntentData<F>, PaymentsGetIntentRequest> for PaymentGetIntent { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, _state: &'b SessionState, _req_state: ReqState, payment_data: payments::PaymentIntentData<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<( PaymentsGetIntentOperation<'b, F>, payments::PaymentIntentData<F>, )> where F: 'b + Send, { Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, PaymentsGetIntentRequest, payments::PaymentIntentData<F>> for PaymentGetIntent { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, _request: &PaymentsGetIntentRequest, 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, PaymentsGetIntentRequest, payments::PaymentIntentData<F>> for PaymentGetIntent { #[instrument(skip_all)] async fn get_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut payments::PaymentIntentData<F>, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, PaymentsGetIntentRequest, payments::PaymentIntentData<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::PaymentIntentData<F>, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentsGetIntentOperation<'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, // TODO: do not take the whole payment data here payment_data: &mut payments::PaymentIntentData<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::PaymentIntentData<F>, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_get_intent.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-4740705064443298986
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_session.rs // Contains: 1 structs, 0 enums use std::marker::PhantomData; use api_models::{admin::PaymentMethodsEnabled, enums::FrmSuggestion}; use async_trait::async_trait; use common_utils::ext_traits::{AsyncExt, ValueExt}; use error_stack::ResultExt; use router_derive::PaymentOperation; use router_env::{instrument, logger, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{self, helpers, operations, PaymentData}, }, routes::{app::ReqState, SessionState}, services, types::{ api::{self, PaymentIdTypeExt}, domain, storage::{self, enums as storage_enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, PaymentOperation)] #[operation(operations = "all", flow = "session")] pub struct PaymentSession; type PaymentSessionOperation<'b, F> = BoxedOperation<'b, F, api::PaymentsSessionRequest, PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> for PaymentSession { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &api::PaymentsSessionRequest, merchant_context: &domain::MerchantContext, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsSessionRequest, PaymentData<F>>, > { let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let db = &*state.store; let key_manager_state = &state.into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let mut payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &state.into(), &payment_id, merchant_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; // TODO (#7195): Add platform merchant account validation once publishable key auth is solved helpers::validate_payment_status_against_not_allowed_statuses( payment_intent.status, &[ storage_enums::IntentStatus::Failed, storage_enums::IntentStatus::Succeeded, ], "create a session token for", )?; helpers::authenticate_client_secret(Some(&request.client_secret), &payment_intent)?; let mut payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, payment_intent.active_attempt.get_id().as_str(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let currency = payment_intent.currency.get_required_value("currency")?; payment_attempt.payment_method = Some(storage_enums::PaymentMethod::Wallet); let amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( state, payment_intent.shipping_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let payment_method_billing = helpers::get_address_by_id( state, payment_attempt.payment_method_billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; payment_intent.shipping_address_id = shipping_address.clone().map(|x| x.address_id); payment_intent.billing_address_id = billing_address.clone().map(|x| x.address_id); let customer_details = payments::CustomerDetails { customer_id: payment_intent.customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, tax_registration_id: None, }; let creds_identifier = request .merchant_connector_details .as_ref() .map(|mcd| mcd.creds_identifier.to_owned()); request .merchant_connector_details .to_owned() .async_map(|mcd| async { helpers::insert_merchant_connector_creds_to_config( db, merchant_context.get_merchant_account().get_id(), mcd, ) .await }) .await .transpose()?; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = db .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 payment_data = PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount, email: None, mandate_id: None, mandate_connector: None, customer_acceptance: None, token: None, token_data: None, setup_mandate: None, address: payments::PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ), confirm: None, payment_method_data: None, payment_method_token: None, payment_method_info: None, force_sync: None, all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: None, creds_identifier, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, redirect_response: None, surcharge_details: None, frm_message: None, payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], authentication: None, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, whole_connector_response: None, is_manual_retry_enabled: None, is_l2_l3_enabled: false, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details: Some(customer_details), payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsSessionRequest> for PaymentSession { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, _req_state: ReqState, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(PaymentSessionOperation<'b, F>, PaymentData<F>)> where F: 'b + Send, { let metadata = payment_data.payment_intent.metadata.clone(); payment_data.payment_intent = match metadata { Some(metadata) => state .store .update_payment_intent( &state.into(), payment_data.payment_intent, storage::PaymentIntentUpdate::MetadataUpdate { metadata, updated_by: storage_scheme.to_string(), }, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?, None => payment_data.payment_intent, }; Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsSessionRequest, PaymentData<F>> for PaymentSession { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsSessionRequest, merchant_context: &'a domain::MerchantContext, ) -> RouterResult<(PaymentSessionOperation<'b, F>, operations::ValidateResult)> { //paymentid is already generated and should be sent in the request let given_payment_id = request.payment_id.clone(); Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), payment_id: api::PaymentIdType::PaymentIntentId(given_payment_id), storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: false, }, )) } } #[async_trait] impl< F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsSessionRequest, Data = PaymentData<F>>, > Domain<F, api::PaymentsSessionRequest, PaymentData<F>> for Op where for<'a> &'a Op: Operation<F, api::PaymentsSessionRequest, Data = PaymentData<F>>, { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<payments::CustomerDetails>, key_store: &domain::MerchantKeyStore, storage_scheme: common_enums::enums::MerchantStorageScheme, ) -> errors::CustomResult< (PaymentSessionOperation<'a, F>, Option<domain::Customer>), errors::StorageError, > { helpers::create_customer_if_not_exist( state, Box::new(self), payment_data, request, &key_store.merchant_id, key_store, storage_scheme, ) .await } #[instrument(skip_all)] async fn make_pm_data<'b>( &'b self, _state: &'b SessionState, _payment_data: &mut PaymentData<F>, _storage_scheme: storage_enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentSessionOperation<'b, F>, Option<domain::PaymentMethodData>, Option<String>, )> { //No payment method data for this operation Ok((Box::new(self), None, None)) } /// Returns `SessionConnectorDatas` /// Steps carried out in this function /// Get all the `merchant_connector_accounts` which are not disabled /// Filter out connectors which have `invoke_sdk_client` enabled in `payment_method_types` /// If session token is requested for certain wallets only, then return them, else /// return all eligible connectors /// /// `GetToken` parameter specifies whether to get the session token from connector integration /// or from separate implementation ( for googlepay - from metadata and applepay - from metadata and call connector) async fn get_connector<'a>( &'a self, merchant_context: &domain::MerchantContext, state: &SessionState, request: &api::PaymentsSessionRequest, payment_intent: &storage::PaymentIntent, ) -> RouterResult<api::ConnectorChoice> { let db = &state.store; let all_connector_accounts = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( &state.into(), merchant_context.get_merchant_account().get_id(), false, merchant_context.get_merchant_key_store(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Database error when querying for merchant connector accounts")?; let profile_id = payment_intent .profile_id .clone() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")?; let filtered_connector_accounts = all_connector_accounts .filter_based_on_profile_and_connector_type( &profile_id, common_enums::ConnectorType::PaymentProcessor, ); let requested_payment_method_types = request.wallets.clone(); let mut connector_and_supporting_payment_method_type = Vec::new(); filtered_connector_accounts .iter() .for_each(|connector_account| { let res = connector_account .payment_methods_enabled .clone() .unwrap_or_default() .into_iter() .map(|payment_methods_enabled| { payment_methods_enabled .parse_value::<PaymentMethodsEnabled>("payment_methods_enabled") }) .filter_map(|parsed_payment_method_result| { parsed_payment_method_result .inspect_err(|err| { logger::error!(session_token_parsing_error=?err); }) .ok() }) .flat_map(|parsed_payment_methods_enabled| { parsed_payment_methods_enabled .payment_method_types .unwrap_or_default() .into_iter() .filter(|payment_method_type| { let is_invoke_sdk_client = matches!( payment_method_type.payment_experience, Some(api_models::enums::PaymentExperience::InvokeSdkClient) ); // If session token is requested for the payment method type, // filter it out // if not, then create all sessions tokens let is_sent_in_request = requested_payment_method_types .contains(&payment_method_type.payment_method_type) || requested_payment_method_types.is_empty(); is_invoke_sdk_client && is_sent_in_request }) .map(|payment_method_type| { ( connector_account, payment_method_type.payment_method_type, parsed_payment_methods_enabled.payment_method, ) }) .collect::<Vec<_>>() }) .collect::<Vec<_>>(); connector_and_supporting_payment_method_type.extend(res); }); let mut session_connector_data = api::SessionConnectorDatas::with_capacity( connector_and_supporting_payment_method_type.len(), ); for (merchant_connector_account, payment_method_type, payment_method) in connector_and_supporting_payment_method_type { if let Ok(connector_data) = helpers::get_connector_data_with_token( state, merchant_connector_account.connector_name.to_string(), Some(merchant_connector_account.get_id()), payment_method_type, ) { #[cfg(feature = "v1")] { let new_session_connector_data = api::SessionConnectorData::new( payment_method_type, connector_data, merchant_connector_account.business_sub_label.clone(), payment_method, ); session_connector_data.push(new_session_connector_data) } #[cfg(feature = "v2")] { let new_session_connector_data = api::SessionConnectorData::new(payment_method_type, connector_data, None); session_connector_data.push(new_session_connector_data) } }; } Ok(api::ConnectorChoice::SessionMultiple( session_connector_data, )) } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut PaymentData<F>, ) -> errors::CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_session.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-279206715400330046
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs // Contains: 1 structs, 0 enums use api_models::payments::ExternalVaultProxyPaymentsRequest; use async_trait::async_trait; use common_enums::enums; use common_utils::{ crypto::Encryptable, ext_traits::{AsyncExt, ValueExt}, types::keymanager::ToEncryptable, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, payments::PaymentConfirmData, }; use hyperswitch_interfaces::api::ConnectorSpecifications; use masking::PeekInterface; use router_env::{instrument, tracing}; use super::{Domain, GetTracker, Operation, PostUpdateTracker, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, payment_methods::{self, PaymentMethodExt}, payments::{ self, operations::{self, ValidateStatusForOperation}, OperationSessionGetters, OperationSessionSetters, }, }, routes::{app::ReqState, SessionState}, types::{ self, api::{self, ConnectorCallType}, domain::{self, types as domain_types}, storage::{self, enums as storage_enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy)] pub struct ExternalVaultProxyPaymentIntent; impl ValidateStatusForOperation for ExternalVaultProxyPaymentIntent { /// 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, ) -> Result<(), errors::ApiErrorResponse> { match intent_status { common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Processing => Ok(()), common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::Expired => { Err(errors::ApiErrorResponse::PaymentUnexpectedState { current_flow: format!("{self:?}"), field_name: "status".to_string(), current_value: intent_status.to_string(), states: ["requires_payment_method", "failed", "processing"].join(", "), }) } } } } type BoxedConfirmOperation<'b, F> = super::BoxedOperation<'b, F, ExternalVaultProxyPaymentsRequest, PaymentConfirmData<F>>; impl<F: Send + Clone + Sync> Operation<F, ExternalVaultProxyPaymentsRequest> for &ExternalVaultProxyPaymentIntent { type Data = PaymentConfirmData<F>; fn to_validate_request( &self, ) -> RouterResult< &(dyn ValidateRequest<F, ExternalVaultProxyPaymentsRequest, Self::Data> + Send + Sync), > { Ok(*self) } fn to_get_tracker( &self, ) -> RouterResult< &(dyn GetTracker<F, Self::Data, ExternalVaultProxyPaymentsRequest> + Send + Sync), > { Ok(*self) } fn to_domain( &self, ) -> RouterResult<&(dyn Domain<F, ExternalVaultProxyPaymentsRequest, Self::Data>)> { Ok(*self) } fn to_update_tracker( &self, ) -> RouterResult< &(dyn UpdateTracker<F, Self::Data, ExternalVaultProxyPaymentsRequest> + Send + Sync), > { Ok(*self) } } #[automatically_derived] impl<F: Send + Clone + Sync> Operation<F, ExternalVaultProxyPaymentsRequest> for ExternalVaultProxyPaymentIntent { type Data = PaymentConfirmData<F>; fn to_validate_request( &self, ) -> RouterResult< &(dyn ValidateRequest<F, ExternalVaultProxyPaymentsRequest, Self::Data> + Send + Sync), > { Ok(self) } fn to_get_tracker( &self, ) -> RouterResult< &(dyn GetTracker<F, Self::Data, ExternalVaultProxyPaymentsRequest> + Send + Sync), > { Ok(self) } fn to_domain( &self, ) -> RouterResult<&dyn Domain<F, ExternalVaultProxyPaymentsRequest, Self::Data>> { Ok(self) } fn to_update_tracker( &self, ) -> RouterResult< &(dyn UpdateTracker<F, Self::Data, ExternalVaultProxyPaymentsRequest> + Send + Sync), > { Ok(self) } } impl<F: Send + Clone + Sync> ValidateRequest<F, ExternalVaultProxyPaymentsRequest, PaymentConfirmData<F>> for ExternalVaultProxyPaymentIntent { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, _request: &ExternalVaultProxyPaymentsRequest, merchant_context: &'a domain::MerchantContext, ) -> RouterResult<operations::ValidateResult> { let validate_result = operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: false, }; Ok(validate_result) } } #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, ExternalVaultProxyPaymentsRequest> for ExternalVaultProxyPaymentIntent { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &common_utils::id_type::GlobalPaymentId, request: &ExternalVaultProxyPaymentsRequest, merchant_context: &domain::MerchantContext, _profile: &domain::Profile, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<operations::GetTrackerResponse<PaymentConfirmData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_intent = db .find_payment_intent_by_id( key_manager_state, payment_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; self.validate_status_for_operation(payment_intent.status)?; let cell_id = state.conf.cell_information.id.clone(); let batch_encrypted_data = domain_types::crypto_operation( key_manager_state, common_utils::type_name!(hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt), domain_types::CryptoOperation::BatchEncrypt( hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::to_encryptable( hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt { payment_method_billing_address: None, }, ), ), common_utils::types::keymanager::Identifier::Merchant(merchant_context.get_merchant_account().get_id().to_owned()), merchant_context.get_merchant_key_store().key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting payment intent details".to_string())?; let encrypted_data = hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::from_encryptable(batch_encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting payment intent details")?; let payment_attempt = match payment_intent.active_attempt_id.clone() { Some(ref active_attempt_id) => db .find_payment_attempt_by_id( key_manager_state, merchant_context.get_merchant_key_store(), active_attempt_id, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Could not find payment attempt")?, None => { // TODO: Implement external vault specific payment attempt creation logic let payment_attempt_domain_model: hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt = hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt::external_vault_proxy_create_domain_model( &payment_intent, cell_id, storage_scheme, request, encrypted_data ) .await?; db.insert_payment_attempt( key_manager_state, merchant_context.get_merchant_key_store(), payment_attempt_domain_model, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not insert payment attempt")? } }; // TODO: Extract external vault specific token/credentials from request let processor_payment_token = None; // request.external_vault_details.processor_payment_token.clone(); let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new( payment_intent .shipping_address .clone() .map(|address| address.into_inner()), payment_intent .billing_address .clone() .map(|address| address.into_inner()), payment_attempt .payment_method_billing_address .clone() .map(|address| address.into_inner()), Some(true), ); // TODO: Implement external vault specific mandate data handling let mandate_data_input = api_models::payments::MandateIds { mandate_id: None, mandate_reference_id: processor_payment_token.map(|token| { api_models::payments::MandateReferenceId::ConnectorMandateId( api_models::payments::ConnectorMandateReferenceId::new( Some(token), None, None, None, None, ), ) }), }; let payment_method_data = request.payment_method_data.payment_method_data.clone().map( hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::from, ); let payment_data = PaymentConfirmData { flow: std::marker::PhantomData, payment_intent, payment_attempt, payment_method_data: None, // TODO: Review for external vault payment_address, mandate_data: Some(mandate_data_input), payment_method: None, merchant_connector_details: None, external_vault_pmd: payment_method_data, webhook_url: None, }; let get_trackers_response = operations::GetTrackerResponse { payment_data }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, ExternalVaultProxyPaymentsRequest, PaymentConfirmData<F>> for ExternalVaultProxyPaymentIntent { async fn get_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentConfirmData<F>, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<(BoxedConfirmOperation<'a, F>, Option<domain::Customer>), errors::StorageError> { match payment_data.payment_intent.customer_id.clone() { Some(id) => { let customer = state .store .find_customer_by_global_id( &state.into(), &id, merchant_key_store, storage_scheme, ) .await?; Ok((Box::new(self), Some(customer))) } None => Ok((Box::new(self), None)), } } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut PaymentConfirmData<F>, _storage_scheme: storage_enums::MerchantStorageScheme, _key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( BoxedConfirmOperation<'a, F>, Option<PaymentMethodData>, Option<String>, )> { // TODO: Implement external vault specific payment method data creation Ok((Box::new(self), None, None)) } 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> { match ( payment_data.payment_intent.customer_id.clone(), payment_data.external_vault_pmd.clone(), payment_data.payment_attempt.customer_acceptance.clone(), payment_data.payment_attempt.payment_token.clone(), ) { (Some(customer_id), Some(hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::Card(card_details)), Some(_), None) => { let payment_method_data = api::PaymentMethodCreateData::ProxyCard(api::ProxyCardDetails::from(*card_details)); let billing = payment_data .payment_address .get_payment_method_billing() .cloned() .map(From::from); 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, billing, psp_tokenization: None, network_tokenization: None, }; let (_pm_response, payment_method) = Box::pin(payment_methods::create_payment_method_core( state, &state.get_req_state(), req, merchant_context, business_profile, )) .await?; payment_data.payment_method = Some(payment_method); } (_, Some(hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::VaultToken(vault_token)), None, Some(payment_token)) => { payment_data.external_vault_pmd = Some(payment_methods::get_external_vault_token( state, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, payment_token.clone(), vault_token.clone(), &payment_data.payment_attempt.payment_method_type ) .await?); } _ => { router_env::logger::debug!( "No payment method to create or fetch for external vault proxy payment intent" ); } } Ok(()) } #[cfg(feature = "v2")] async fn update_payment_method<'a>( &'a self, state: &SessionState, merchant_context: &domain::MerchantContext, payment_data: &mut PaymentConfirmData<F>, ) { if let (true, Some(payment_method)) = ( payment_data.payment_attempt.customer_acceptance.is_some(), payment_data.payment_method.as_ref(), ) { payment_methods::update_payment_method_status_internal( state, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, common_enums::PaymentMethodStatus::Active, payment_method.get_id(), ) .await .map_err(|err| router_env::logger::error!(err=?err)); }; } #[instrument(skip_all)] async fn populate_payment_data<'a>( &'a self, _state: &SessionState, payment_data: &mut PaymentConfirmData<F>, _merchant_context: &domain::MerchantContext, _business_profile: &domain::Profile, connector_data: &api::ConnectorData, ) -> CustomResult<(), errors::ApiErrorResponse> { let connector_request_reference_id = connector_data .connector .generate_connector_request_reference_id( &payment_data.payment_intent, &payment_data.payment_attempt, ); payment_data.set_connector_request_reference_id(Some(connector_request_reference_id)); Ok(()) } async fn perform_routing<'a>( &'a self, merchant_context: &domain::MerchantContext, business_profile: &domain::Profile, state: &SessionState, payment_data: &mut PaymentConfirmData<F>, ) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse> { payments::connector_selection( state, merchant_context, business_profile, payment_data, None, ) .await } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentConfirmData<F>, ExternalVaultProxyPaymentsRequest> for ExternalVaultProxyPaymentIntent { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, _req_state: ReqState, mut payment_data: PaymentConfirmData<F>, _customer: Option<domain::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<api_models::enums::FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(BoxedConfirmOperation<'b, F>, PaymentConfirmData<F>)> where F: 'b + Send, { let db = &*state.store; let key_manager_state = &state.into(); let intent_status = common_enums::IntentStatus::Processing; let attempt_status = common_enums::AttemptStatus::Pending; let connector = payment_data .payment_attempt .connector .clone() .get_required_value("connector") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Connector is none when constructing response")?; let merchant_connector_id = Some( payment_data .payment_attempt .merchant_connector_id .clone() .get_required_value("merchant_connector_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Merchant connector id is none when constructing response")?, ); let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::ConfirmIntent { status: intent_status, updated_by: storage_scheme.to_string(), active_attempt_id: Some(payment_data.payment_attempt.id.clone()), }; let authentication_type = payment_data .payment_intent .authentication_type .unwrap_or_default(); let connector_request_reference_id = payment_data .payment_attempt .connector_request_reference_id .clone(); let connector_response_reference_id = payment_data .payment_attempt .connector_response_reference_id .clone(); 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, connector_request_reference_id, connector_response_reference_id, }; let updated_payment_intent = db .update_payment_intent( key_manager_state, payment_data.payment_intent.clone(), payment_intent_update, key_store, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment intent")?; payment_data.payment_intent = updated_payment_intent; let updated_payment_attempt = db .update_payment_attempt( key_manager_state, key_store, payment_data.payment_attempt.clone(), payment_attempt_update, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment attempt")?; payment_data.payment_attempt = updated_payment_attempt; Ok((Box::new(self), payment_data)) } } #[cfg(feature = "v2")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::PaymentsAuthorizeData> for ExternalVaultProxyPaymentIntent { async fn update_tracker<'b>( &'b self, state: &'b SessionState, mut payment_data: PaymentConfirmData<F>, response: types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<PaymentConfirmData<F>> where F: 'b + Send + Sync, types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects< F, types::PaymentsAuthorizeData, PaymentConfirmData<F>, >, { use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects; let db = &*state.store; let key_manager_state = &state.into(); let response_router_data = response; let payment_intent_update = response_router_data.get_payment_intent_update(&payment_data, storage_scheme); let payment_attempt_update = response_router_data.get_payment_attempt_update(&payment_data, storage_scheme); let updated_payment_intent = db .update_payment_intent( key_manager_state, payment_data.payment_intent, payment_intent_update, key_store, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment intent")?; let updated_payment_attempt = db .update_payment_attempt( key_manager_state, key_store, payment_data.payment_attempt, payment_attempt_update, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment attempt")?; payment_data.payment_intent = updated_payment_intent; payment_data.payment_attempt = updated_payment_attempt; // TODO: Add external vault specific post-update logic Ok(payment_data) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-100351148784921077
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_post_session_tokens.rs // Contains: 1 structs, 0 enums use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; use common_utils::types::keymanager::KeyManagerState; use error_stack::ResultExt; use masking::PeekInterface; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{self, helpers, operations, PaymentData}, }, routes::{app::ReqState, SessionState}, services, types::{ api::{self, PaymentIdTypeExt}, domain, storage::{self, enums as storage_enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, PaymentOperation)] #[operation(operations = "all", flow = "post_session_tokens")] pub struct PaymentPostSessionTokens; type PaymentPostSessionTokensOperation<'b, F> = BoxedOperation<'b, F, api::PaymentsPostSessionTokensRequest, PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsPostSessionTokensRequest> for PaymentPostSessionTokens { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &api::PaymentsPostSessionTokensRequest, merchant_context: &domain::MerchantContext, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult< operations::GetTrackerResponse< 'a, F, api::PaymentsPostSessionTokensRequest, PaymentData<F>, >, > { let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let db = &*state.store; let key_manager_state: &KeyManagerState = &state.into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &state.into(), &payment_id, merchant_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; // TODO (#7195): Add platform merchant account validation once publishable key auth is solved helpers::authenticate_client_secret(Some(request.client_secret.peek()), &payment_intent)?; let mut payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, payment_intent.active_attempt.get_id().as_str(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let currency = payment_intent.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount().into(); let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = db .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(), })?; payment_attempt.payment_method = Some(request.payment_method); payment_attempt.payment_method_type = Some(request.payment_method_type); let shipping_address = helpers::get_address_by_id( state, payment_intent.shipping_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let payment_data = PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount, email: None, mandate_id: None, mandate_connector: None, customer_acceptance: None, token: None, token_data: None, setup_mandate: None, address: payments::PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), None, business_profile.use_billing_as_payment_method_billing, ), confirm: None, payment_method_data: None, payment_method_token: None, payment_method_info: None, force_sync: None, all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: None, creds_identifier: None, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, redirect_response: None, surcharge_details: None, frm_message: None, payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], authentication: None, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, whole_connector_response: None, is_manual_retry_enabled: None, is_l2_l3_enabled: false, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, api::PaymentsPostSessionTokensRequest, PaymentData<F>> for PaymentPostSessionTokens { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut PaymentData<F>, _request: Option<payments::CustomerDetails>, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> errors::CustomResult< ( PaymentPostSessionTokensOperation<'a, 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 PaymentData<F>, _storage_scheme: storage_enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentPostSessionTokensOperation<'a, F>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } async fn get_connector<'a>( &'a self, _merchant_context: &domain::MerchantContext, state: &SessionState, _request: &api::PaymentsPostSessionTokensRequest, _payment_intent: &storage::PaymentIntent, ) -> errors::CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut PaymentData<F>, ) -> errors::CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsPostSessionTokensRequest> for PaymentPostSessionTokens { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, _state: &'b SessionState, _req_state: ReqState, payment_data: PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: storage_enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, _key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(PaymentPostSessionTokensOperation<'b, F>, PaymentData<F>)> where F: 'b + Send, { Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsPostSessionTokensRequest, PaymentData<F>> for PaymentPostSessionTokens { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsPostSessionTokensRequest, merchant_context: &'a domain::MerchantContext, ) -> RouterResult<( PaymentPostSessionTokensOperation<'b, F>, operations::ValidateResult, )> { //payment id is already generated and should be sent in the request let given_payment_id = request.payment_id.clone(); Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), payment_id: api::PaymentIdType::PaymentIntentId(given_payment_id), storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: false, }, )) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_post_session_tokens.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_3794986675720163291
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_start.rs // Contains: 1 structs, 0 enums use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; use error_stack::ResultExt; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, }, routes::{app::ReqState, SessionState}, services, types::{ api::{self, PaymentIdTypeExt}, domain, storage::{self, enums as storage_enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, PaymentOperation)] #[operation(operations = "all", flow = "start")] pub struct PaymentStart; type PaymentSessionOperation<'b, F> = BoxedOperation<'b, F, api::PaymentsStartRequest, PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> for PaymentStart { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, _request: &api::PaymentsStartRequest, merchant_context: &domain::MerchantContext, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsStartRequest, PaymentData<F>>, > { let (mut payment_intent, payment_attempt, currency, amount); let db = &*state.store; let key_manager_state = &state.into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; payment_intent = db .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, merchant_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; // TODO (#7195): Add platform merchant account validation once Merchant ID auth is solved helpers::validate_payment_status_against_not_allowed_statuses( payment_intent.status, &[ storage_enums::IntentStatus::Failed, storage_enums::IntentStatus::Succeeded, ], "update", )?; helpers::authenticate_client_secret( payment_intent.client_secret.as_ref(), &payment_intent, )?; payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, payment_intent.active_attempt.get_id().as_str(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; currency = payment_attempt.currency.get_required_value("currency")?; amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( state, payment_intent.shipping_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let payment_method_billing = helpers::get_address_by_id( state, payment_attempt.payment_method_billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let token_data = if let Some(token) = payment_attempt.payment_token.clone() { Some( helpers::retrieve_payment_token_data(state, token, payment_attempt.payment_method) .await?, ) } else { None }; payment_intent.shipping_address_id = shipping_address.clone().map(|i| i.address_id); payment_intent.billing_address_id = billing_address.clone().map(|i| i.address_id); let customer_details = CustomerDetails { customer_id: payment_intent.customer_id.clone(), ..CustomerDetails::default() }; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = db .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 payment_data = PaymentData { flow: PhantomData, payment_intent, currency, amount, email: None, mandate_id: None, mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: payment_attempt.payment_token.clone(), address: PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ), token_data, confirm: Some(payment_attempt.confirm), payment_attempt, payment_method_data: None, payment_method_token: None, payment_method_info: None, force_sync: None, all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: None, creds_identifier: None, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, redirect_response: None, surcharge_details: None, frm_message: None, payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], authentication: None, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, whole_connector_response: None, is_manual_retry_enabled: None, is_l2_l3_enabled: false, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details: Some(customer_details), payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsStartRequest> for PaymentStart { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, _state: &'b SessionState, _req_state: ReqState, payment_data: PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: storage_enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, _mechant_key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(PaymentSessionOperation<'b, F>, PaymentData<F>)> where F: 'b + Send, { Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsStartRequest, PaymentData<F>> for PaymentStart { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsStartRequest, merchant_context: &'a domain::MerchantContext, ) -> RouterResult<(PaymentSessionOperation<'b, F>, operations::ValidateResult)> { let request_merchant_id = Some(&request.merchant_id); helpers::validate_merchant_id( merchant_context.get_merchant_account().get_id(), request_merchant_id, ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "merchant_id".to_string(), expected_format: "merchant_id from merchant account".to_string(), })?; let payment_id = request.payment_id.clone(); Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), payment_id: api::PaymentIdType::PaymentIntentId(payment_id), storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: false, }, )) } } #[async_trait] impl< F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsStartRequest, Data = PaymentData<F>>, > Domain<F, api::PaymentsStartRequest, PaymentData<F>> for Op where for<'a> &'a Op: Operation<F, api::PaymentsStartRequest, Data = PaymentData<F>>, { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, storage_scheme: common_enums::enums::MerchantStorageScheme, ) -> CustomResult< (PaymentSessionOperation<'a, F>, Option<domain::Customer>), errors::StorageError, > { helpers::create_customer_if_not_exist( state, Box::new(self), payment_data, request, &key_store.merchant_id, key_store, storage_scheme, ) .await } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, state: &'a SessionState, payment_data: &mut PaymentData<F>, storage_scheme: storage_enums::MerchantStorageScheme, merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, should_retry_with_pan: bool, ) -> RouterResult<( PaymentSessionOperation<'a, F>, Option<domain::PaymentMethodData>, Option<String>, )> { if payment_data .payment_attempt .connector .clone() .map(|connector_name| connector_name == *"bluesnap".to_string()) .unwrap_or(false) { Box::pin(helpers::make_pm_data( Box::new(self), state, payment_data, merchant_key_store, customer, storage_scheme, business_profile, should_retry_with_pan, )) .await } else { Ok((Box::new(self), None, None)) } } async fn get_connector<'a>( &'a self, _merchant_context: &domain::MerchantContext, state: &SessionState, _request: &api::PaymentsStartRequest, _payment_intent: &storage::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut PaymentData<F>, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_start.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_6267359995899009289
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_session_intent.rs // Contains: 1 structs, 0 enums use std::{collections::HashMap, marker::PhantomData}; use api_models::payments::PaymentsSessionRequest; use async_trait::async_trait; use common_utils::{errors::CustomResult, ext_traits::Encode}; use error_stack::ResultExt; use hyperswitch_domain_models::customer; use router_env::{instrument, logger, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{self, helpers, operations, operations::ValidateStatusForOperation}, }, routes::{app::ReqState, SessionState}, types::{api, domain, storage, storage::enums}, utils::ext_traits::OptionExt, }; #[derive(Debug, Clone, Copy)] pub struct PaymentSessionIntent; type PaymentSessionOperation<'b, F> = BoxedOperation<'b, F, PaymentsSessionRequest, payments::PaymentIntentData<F>>; impl ValidateStatusForOperation for PaymentSessionIntent { /// 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, ) -> Result<(), errors::ApiErrorResponse> { match intent_status { common_enums::IntentStatus::RequiresPaymentMethod => Ok(()), common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Processing | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => { Err(errors::ApiErrorResponse::PreconditionFailed { message: format!( "You cannot create session token for this payment because it has status {intent_status}. Expected status is requires_payment_method.", ), }) } } } } impl<F: Send + Clone + Sync> Operation<F, PaymentsSessionRequest> for &PaymentSessionIntent { type Data = payments::PaymentIntentData<F>; fn to_validate_request( &self, ) -> RouterResult<&(dyn ValidateRequest<F, PaymentsSessionRequest, Self::Data> + Send + Sync)> { Ok(*self) } fn to_get_tracker( &self, ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsSessionRequest> + Send + Sync)> { Ok(*self) } fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentsSessionRequest, Self::Data>)> { Ok(*self) } fn to_update_tracker( &self, ) -> RouterResult< &(dyn UpdateTracker<F, payments::PaymentIntentData<F>, PaymentsSessionRequest> + Send + Sync), > { Ok(*self) } } impl<F: Send + Clone + Sync> Operation<F, PaymentsSessionRequest> for PaymentSessionIntent { type Data = payments::PaymentIntentData<F>; fn to_validate_request( &self, ) -> RouterResult<&(dyn ValidateRequest<F, PaymentsSessionRequest, Self::Data> + Send + Sync)> { Ok(self) } fn to_get_tracker( &self, ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsSessionRequest> + Send + Sync)> { Ok(self) } fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsSessionRequest, Self::Data>> { Ok(self) } fn to_update_tracker( &self, ) -> RouterResult< &(dyn UpdateTracker<F, payments::PaymentIntentData<F>, PaymentsSessionRequest> + Send + Sync), > { Ok(self) } } type PaymentsCreateIntentOperation<'b, F> = BoxedOperation<'b, F, PaymentsSessionRequest, payments::PaymentIntentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentIntentData<F>, PaymentsSessionRequest> for PaymentSessionIntent { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &common_utils::id_type::GlobalPaymentId, _request: &PaymentsSessionRequest, merchant_context: &domain::MerchantContext, _profile: &domain::Profile, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<operations::GetTrackerResponse<payments::PaymentIntentData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_intent = db .find_payment_intent_by_id( key_manager_state, payment_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; // TODO (#7195): Add platform merchant account validation once publishable key auth is solved self.validate_status_for_operation(payment_intent.status)?; let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, client_secret: None, sessions_token: vec![], vault_session_details: None, connector_customer_id: None, }; let get_trackers_response = operations::GetTrackerResponse { payment_data }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, payments::PaymentIntentData<F>, PaymentsSessionRequest> for PaymentSessionIntent { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, _req_state: ReqState, mut payment_data: payments::PaymentIntentData<F>, customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, updated_customer: Option<customer::CustomerUpdate>, key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<common_enums::FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<( PaymentSessionOperation<'b, F>, payments::PaymentIntentData<F>, )> where F: 'b + Send, { let prerouting_algorithm = payment_data.payment_intent.prerouting_algorithm.clone(); payment_data.payment_intent = match prerouting_algorithm { Some(prerouting_algorithm) => state .store .update_payment_intent( &state.into(), payment_data.payment_intent, storage::PaymentIntentUpdate::SessionIntentUpdate { prerouting_algorithm, updated_by: storage_scheme.to_string(), }, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?, None => payment_data.payment_intent, }; Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone> ValidateRequest<F, PaymentsSessionRequest, payments::PaymentIntentData<F>> for PaymentSessionIntent { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, _request: &PaymentsSessionRequest, 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, PaymentsSessionRequest, payments::PaymentIntentData<F>> for PaymentSessionIntent { #[instrument(skip_all)] async fn get_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut payments::PaymentIntentData<F>, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, PaymentsSessionRequest, payments::PaymentIntentData<F>>, Option<domain::Customer>, ), errors::StorageError, > { match payment_data.payment_intent.customer_id.clone() { Some(id) => { let customer = state .store .find_customer_by_global_id( &state.into(), &id, merchant_key_store, storage_scheme, ) .await?; Ok((Box::new(self), Some(customer))) } None => Ok((Box::new(self), None)), } } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut payments::PaymentIntentData<F>, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentsCreateIntentOperation<'a, F>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } async fn perform_routing<'a>( &'a self, merchant_context: &domain::MerchantContext, business_profile: &domain::Profile, state: &SessionState, payment_data: &mut payments::PaymentIntentData<F>, ) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> { let db = &state.store; let all_connector_accounts = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( &state.into(), merchant_context.get_merchant_account().get_id(), false, merchant_context.get_merchant_key_store(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Database error when querying for merchant connector accounts")?; let profile_id = business_profile.get_id(); let filtered_connector_accounts = all_connector_accounts .filter_based_on_profile_and_connector_type( profile_id, common_enums::ConnectorType::PaymentProcessor, ); let connector_and_supporting_payment_method_type = filtered_connector_accounts .get_connector_and_supporting_payment_method_type_for_session_call(); let session_connector_data: api::SessionConnectorDatas = connector_and_supporting_payment_method_type .into_iter() .filter_map( |(merchant_connector_account, payment_method_type, payment_method)| { match helpers::get_connector_data_with_token( state, merchant_connector_account.connector_name.to_string(), Some(merchant_connector_account.get_id()), payment_method_type, ) { Ok(connector_data) => Some(api::SessionConnectorData::new( payment_method_type, connector_data, None, payment_method, )), Err(err) => { logger::error!(session_token_error=?err); None } } }, ) .collect(); let session_token_routing_result = payments::perform_session_token_routing( state.clone(), business_profile, merchant_context.clone(), payment_data, session_connector_data, ) .await?; let pre_routing = storage::PaymentRoutingInfo { algorithm: None, pre_routing_results: Some((|| { let mut pre_routing_results: HashMap< common_enums::PaymentMethodType, storage::PreRoutingConnectorChoice, > = HashMap::new(); for (pm_type, routing_choice) in session_token_routing_result.routing_result { let mut routable_choice_list = vec![]; for choice in routing_choice { let routable_choice = api::routing::RoutableConnectorChoice { choice_kind: api::routing::RoutableChoiceKind::FullStruct, connector: choice .connector .connector_name .to_string() .parse::<common_enums::RoutableConnectors>() .change_context(errors::ApiErrorResponse::InternalServerError)?, merchant_connector_id: choice.connector.merchant_connector_id.clone(), }; routable_choice_list.push(routable_choice); } pre_routing_results.insert( pm_type, storage::PreRoutingConnectorChoice::Multiple(routable_choice_list), ); } Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(pre_routing_results) })()?), }; // Store the routing results in payment intent payment_data.payment_intent.prerouting_algorithm = Some(pre_routing); Ok(api::ConnectorCallType::SessionMultiple( session_token_routing_result.final_result, )) } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut payments::PaymentIntentData<F>, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_session_intent.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_9182826777852583361
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_attempt_record.rs // Contains: 1 structs, 0 enums use std::marker::PhantomData; use api_models::{enums::FrmSuggestion, payments::PaymentsAttemptRecordRequest}; use async_trait::async_trait; use common_utils::{ errors::CustomResult, ext_traits::{AsyncExt, Encode, ValueExt}, types::keymanager::ToEncryptable, }; use error_stack::ResultExt; use hyperswitch_domain_models::payments::PaymentAttemptRecordData; use masking::PeekInterface; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, StorageErrorExt}, payments::{ self, cards::create_encrypted_data, helpers, operations::{self, ValidateStatusForOperation}, }, }, db::{domain::types, errors::RouterResult}, routes::{app::ReqState, SessionState}, services, types::{ api, domain::{self, types as domain_types}, storage::{self, enums}, }, utils::{self, OptionExt}, }; #[derive(Debug, Clone, Copy)] pub struct PaymentAttemptRecord; type PaymentsAttemptRecordOperation<'b, F> = BoxedOperation<'b, F, PaymentsAttemptRecordRequest, PaymentAttemptRecordData<F>>; impl<F: Send + Clone + Sync> Operation<F, PaymentsAttemptRecordRequest> for &PaymentAttemptRecord { type Data = PaymentAttemptRecordData<F>; fn to_validate_request( &self, ) -> RouterResult< &(dyn ValidateRequest<F, PaymentsAttemptRecordRequest, Self::Data> + Send + Sync), > { Ok(*self) } fn to_get_tracker( &self, ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsAttemptRecordRequest> + Send + Sync)> { Ok(*self) } fn to_domain( &self, ) -> RouterResult<&(dyn Domain<F, PaymentsAttemptRecordRequest, Self::Data>)> { Ok(*self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsAttemptRecordRequest> + Send + Sync)> { Ok(*self) } } impl ValidateStatusForOperation for PaymentAttemptRecord { fn validate_status_for_operation( &self, intent_status: common_enums::IntentStatus, ) -> Result<(), errors::ApiErrorResponse> { // need to verify this? match intent_status { // Payment attempt can be recorded for failed payment as well in revenue recovery flow. common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::Failed => Ok(()), common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Processing | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::Expired => { Err(errors::ApiErrorResponse::PaymentUnexpectedState { current_flow: format!("{self:?}"), field_name: "status".to_string(), current_value: intent_status.to_string(), states: [ common_enums::IntentStatus::RequiresPaymentMethod, common_enums::IntentStatus::Failed, ] .map(|enum_value| enum_value.to_string()) .join(", "), }) } } } } #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentAttemptRecordData<F>, PaymentsAttemptRecordRequest> for PaymentAttemptRecord { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &common_utils::id_type::GlobalPaymentId, request: &PaymentsAttemptRecordRequest, merchant_context: &domain::MerchantContext, _profile: &domain::Profile, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<operations::GetTrackerResponse<PaymentAttemptRecordData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_intent = db .find_payment_intent_by_id( key_manager_state, payment_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; self.validate_status_for_operation(payment_intent.status)?; let payment_method_billing_address = request .payment_method_data .as_ref() .and_then(|data| { data.billing .as_ref() .map(|address| address.clone().encode_to_value()) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode payment_method_billing address")? .map(masking::Secret::new); let batch_encrypted_data = domain_types::crypto_operation( key_manager_state, common_utils::type_name!(hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt), domain_types::CryptoOperation::BatchEncrypt( hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::to_encryptable( hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt { payment_method_billing_address, }, ), ), common_utils::types::keymanager::Identifier::Merchant(merchant_context.get_merchant_account().get_id().to_owned()), merchant_context.get_merchant_key_store().key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting payment intent details".to_string())?; let encrypted_data = hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::from_encryptable(batch_encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting payment intent details")?; let cell_id = state.conf.cell_information.id.clone(); let payment_attempt_domain_model = hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt::create_domain_model_using_record_request( &payment_intent, cell_id, storage_scheme, request, encrypted_data, ) .await?; let payment_attempt = db .insert_payment_attempt( key_manager_state, merchant_context.get_merchant_key_store(), payment_attempt_domain_model, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not insert payment attempt")?; let revenue_recovery_data = hyperswitch_domain_models::payments::RevenueRecoveryData { billing_connector_id: request.billing_connector_id.clone(), processor_payment_method_token: request.processor_payment_method_token.clone(), connector_customer_id: request.connector_customer_id.clone(), 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 .shipping_address .clone() .map(|address| address.into_inner()), payment_intent .billing_address .clone() .map(|address| address.into_inner()), payment_attempt .payment_method_billing_address .clone() .map(|address| address.into_inner()), Some(true), ); let payment_data = PaymentAttemptRecordData { flow: PhantomData, payment_intent, payment_attempt, payment_address, revenue_recovery_data, }; let get_trackers_response = operations::GetTrackerResponse { payment_data }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentAttemptRecordData<F>, PaymentsAttemptRecordRequest> for PaymentAttemptRecord { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, _req_state: ReqState, mut payment_data: PaymentAttemptRecordData<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<( PaymentsAttemptRecordOperation<'b, F>, PaymentAttemptRecordData<F>, )> where F: 'b + Send, { let feature_metadata = payment_data.get_updated_feature_metadata()?; let active_attempt_id = match payment_data.revenue_recovery_data.triggered_by { common_enums::TriggeredBy::Internal => Some(payment_data.payment_attempt.id.clone()), common_enums::TriggeredBy::External => None, }; let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::RecordUpdate { status: common_enums::IntentStatus::from(payment_data.payment_attempt.status), feature_metadata: Box::new(feature_metadata), updated_by: storage_scheme.to_string(), active_attempt_id } ; payment_data.payment_intent = state .store .update_payment_intent( &state.into(), payment_data.payment_intent, payment_intent_update, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone> ValidateRequest<F, PaymentsAttemptRecordRequest, PaymentAttemptRecordData<F>> for PaymentAttemptRecord { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, _request: &PaymentsAttemptRecordRequest, 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, PaymentsAttemptRecordRequest, PaymentAttemptRecordData<F>> for PaymentAttemptRecord { #[instrument(skip_all)] async fn get_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut PaymentAttemptRecordData<F>, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, PaymentsAttemptRecordRequest, PaymentAttemptRecordData<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 PaymentAttemptRecordData<F>, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentsAttemptRecordOperation<'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 PaymentAttemptRecordData<F>, ) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> { Ok(api::ConnectorCallType::Skip) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_attempt_record.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_3370355477910616538
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_cancel_v2.rs // Contains: 1 structs, 0 enums use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; use common_enums; use common_utils::{ext_traits::AsyncExt, id_type::GlobalPaymentId}; use error_stack::ResultExt; use router_env::{instrument, tracing}; use super::{ BoxedOperation, Domain, GetTracker, Operation, OperationSessionSetters, UpdateTracker, ValidateRequest, ValidateStatusForOperation, }; use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, payments::operations, }, routes::{app::ReqState, SessionState}, types::{ self, api::{self, ConnectorCallType, PaymentIdTypeExt}, domain, storage::{self, enums}, PaymentsCancelData, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy)] pub struct PaymentsCancel; type BoxedCancelOperation<'b, F> = BoxedOperation< 'b, F, api::PaymentsCancelRequest, hyperswitch_domain_models::payments::PaymentCancelData<F>, >; // Manual Operation trait implementation for V2 impl<F: Send + Clone + Sync> Operation<F, api::PaymentsCancelRequest> for &PaymentsCancel { type Data = hyperswitch_domain_models::payments::PaymentCancelData<F>; fn to_validate_request( &self, ) -> RouterResult<&(dyn ValidateRequest<F, api::PaymentsCancelRequest, Self::Data> + Send + Sync)> { Ok(*self) } fn to_get_tracker( &self, ) -> RouterResult<&(dyn GetTracker<F, Self::Data, api::PaymentsCancelRequest> + Send + Sync)> { Ok(*self) } fn to_domain(&self) -> RouterResult<&(dyn Domain<F, api::PaymentsCancelRequest, Self::Data>)> { Ok(*self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, api::PaymentsCancelRequest> + Send + Sync)> { Ok(*self) } } #[automatically_derived] impl<F: Send + Clone + Sync> Operation<F, api::PaymentsCancelRequest> for PaymentsCancel { type Data = hyperswitch_domain_models::payments::PaymentCancelData<F>; fn to_validate_request( &self, ) -> RouterResult<&(dyn ValidateRequest<F, api::PaymentsCancelRequest, Self::Data> + Send + Sync)> { Ok(self) } fn to_get_tracker( &self, ) -> RouterResult<&(dyn GetTracker<F, Self::Data, api::PaymentsCancelRequest> + Send + Sync)> { Ok(self) } fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsCancelRequest, Self::Data>> { Ok(self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, api::PaymentsCancelRequest> + Send + Sync)> { Ok(self) } } #[cfg(feature = "v2")] impl<F: Send + Clone + Sync> ValidateRequest< F, api::PaymentsCancelRequest, hyperswitch_domain_models::payments::PaymentCancelData<F>, > for PaymentsCancel { #[instrument(skip_all)] fn validate_request( &self, _request: &api::PaymentsCancelRequest, merchant_context: &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, }) } } #[cfg(feature = "v2")] #[async_trait] impl<F: Send + Clone + Sync> GetTracker< F, hyperswitch_domain_models::payments::PaymentCancelData<F>, api::PaymentsCancelRequest, > for PaymentsCancel { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &common_utils::id_type::GlobalPaymentId, request: &api::PaymentsCancelRequest, merchant_context: &domain::MerchantContext, profile: &domain::Profile, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult< operations::GetTrackerResponse<hyperswitch_domain_models::payments::PaymentCancelData<F>>, > { let db = &*state.store; let key_manager_state = &state.into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_intent = db .find_payment_intent_by_id( key_manager_state, payment_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Failed to find payment intent for cancellation")?; self.validate_status_for_operation(payment_intent.status)?; let active_attempt_id = payment_intent.active_attempt_id.as_ref().ok_or_else(|| { errors::ApiErrorResponse::InvalidRequestData { message: "Payment cancellation not possible - no active payment attempt found" .to_string(), } })?; let payment_attempt = db .find_payment_attempt_by_id( key_manager_state, merchant_context.get_merchant_key_store(), active_attempt_id, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Failed to find payment attempt for cancellation")?; let mut payment_data = hyperswitch_domain_models::payments::PaymentCancelData { flow: PhantomData, payment_intent, payment_attempt, }; payment_data.set_cancellation_reason(request.cancellation_reason.clone()); let get_trackers_response = operations::GetTrackerResponse { payment_data }; Ok(get_trackers_response) } } #[cfg(feature = "v2")] #[async_trait] impl<F: Clone + Send + Sync> UpdateTracker< F, hyperswitch_domain_models::payments::PaymentCancelData<F>, api::PaymentsCancelRequest, > for PaymentsCancel { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, req_state: ReqState, mut payment_data: hyperswitch_domain_models::payments::PaymentCancelData<F>, _customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, merchant_key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<( BoxedCancelOperation<'b, F>, hyperswitch_domain_models::payments::PaymentCancelData<F>, )> where F: 'b + Send, { let db = &*state.store; let key_manager_state = &state.into(); let payment_attempt_update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::VoidUpdate { status: enums::AttemptStatus::VoidInitiated, cancellation_reason: payment_data.payment_attempt.cancellation_reason.clone(), updated_by: storage_scheme.to_string(), }; let updated_payment_attempt = db .update_payment_attempt( key_manager_state, merchant_key_store, payment_data.payment_attempt.clone(), payment_attempt_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Failed to update payment attempt for cancellation")?; payment_data.set_payment_attempt(updated_payment_attempt); Ok((Box::new(self), payment_data)) } } #[cfg(feature = "v2")] #[async_trait] impl<F: Send + Clone + Sync> Domain<F, api::PaymentsCancelRequest, hyperswitch_domain_models::payments::PaymentCancelData<F>> for PaymentsCancel { async fn get_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut hyperswitch_domain_models::payments::PaymentCancelData<F>, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<(BoxedCancelOperation<'a, F>, Option<domain::Customer>), errors::StorageError> { Ok((Box::new(*self), None)) } async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut hyperswitch_domain_models::payments::PaymentCancelData<F>, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( BoxedCancelOperation<'a, F>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(*self), None, None)) } async fn perform_routing<'a>( &'a self, _merchant_context: &domain::MerchantContext, _business_profile: &domain::Profile, state: &SessionState, payment_data: &mut hyperswitch_domain_models::payments::PaymentCancelData<F>, ) -> RouterResult<api::ConnectorCallType> { let payment_attempt = &payment_data.payment_attempt; let connector = payment_attempt .connector .as_ref() .get_required_value("connector") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Connector not found for payment cancellation")?; 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 not found for payment cancellation")?; 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(api::ConnectorCallType::PreDetermined(connector_data.into())) } } impl ValidateStatusForOperation for PaymentsCancel { fn validate_status_for_operation( &self, intent_status: common_enums::IntentStatus, ) -> Result<(), errors::ApiErrorResponse> { match intent_status { common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::RequiresCapture => Ok(()), common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Processing | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => { 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::PartiallyCapturedAndCapturable, common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture, ] .map(|enum_value| enum_value.to_string()) .join(", "), }) } } } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_cancel_v2.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-112944504270409091
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_attempt_list.rs // Contains: 1 structs, 0 enums 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) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_attempt_list.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_2939527664089907075
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_cancel_post_capture.rs // Contains: 1 structs, 0 enums use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; use error_stack::ResultExt; use router_derive; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{self, helpers, operations, PaymentData}, }, routes::{app::ReqState, SessionState}, services, types::{ self as core_types, api::{self, PaymentIdTypeExt}, domain, storage::{self, enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, router_derive::PaymentOperation)] #[operation(operations = "all", flow = "cancel_post_capture")] pub struct PaymentCancelPostCapture; type PaymentCancelPostCaptureOperation<'b, F> = BoxedOperation<'b, F, api::PaymentsCancelPostCaptureRequest, PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelPostCaptureRequest> for PaymentCancelPostCapture { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &api::PaymentsCancelPostCaptureRequest, merchant_context: &domain::MerchantContext, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult< operations::GetTrackerResponse< 'a, F, api::PaymentsCancelPostCaptureRequest, PaymentData<F>, >, > { let db = &*state.store; let key_manager_state = &state.into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, merchant_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; helpers::validate_payment_status_against_allowed_statuses( payment_intent.status, &[ enums::IntentStatus::Succeeded, enums::IntentStatus::PartiallyCaptured, enums::IntentStatus::PartiallyCapturedAndCapturable, ], "cancel_post_capture", )?; let mut payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, payment_intent.active_attempt.get_id().as_str(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let shipping_address = helpers::get_address_by_id( state, payment_intent.shipping_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let payment_method_billing = helpers::get_address_by_id( state, payment_attempt.payment_method_billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let currency = payment_attempt.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount().into(); payment_attempt .cancellation_reason .clone_from(&request.cancellation_reason); let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = db .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 payment_data = PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount, email: None, mandate_id: None, mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, token_data: None, address: core_types::PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ), confirm: None, payment_method_data: None, payment_method_token: None, payment_method_info: None, force_sync: None, all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: None, creds_identifier: None, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, redirect_response: None, surcharge_details: None, frm_message: None, payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], authentication: None, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, whole_connector_response: None, is_manual_retry_enabled: None, is_l2_l3_enabled: false, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, api::PaymentsCancelPostCaptureRequest, PaymentData<F>> for PaymentCancelPostCapture { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut PaymentData<F>, _request: Option<payments::CustomerDetails>, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> errors::CustomResult< ( PaymentCancelPostCaptureOperation<'a, 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 PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentCancelPostCaptureOperation<'a, F>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } async fn get_connector<'a>( &'a self, _merchant_context: &domain::MerchantContext, state: &SessionState, _request: &api::PaymentsCancelPostCaptureRequest, _payment_intent: &storage::PaymentIntent, ) -> errors::CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut PaymentData<F>, ) -> errors::CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelPostCaptureRequest> for PaymentCancelPostCapture { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, _state: &'b SessionState, _req_state: ReqState, payment_data: PaymentData<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<(PaymentCancelPostCaptureOperation<'b, F>, PaymentData<F>)> where F: 'b + Send, { Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsCancelPostCaptureRequest, PaymentData<F>> for PaymentCancelPostCapture { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsCancelPostCaptureRequest, merchant_context: &'a domain::MerchantContext, ) -> RouterResult<( PaymentCancelPostCaptureOperation<'b, F>, operations::ValidateResult, )> { Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()), storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: false, }, )) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_cancel_post_capture.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_-5828219993654708436
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_create_intent.rs // Contains: 1 structs, 0 enums use std::marker::PhantomData; use api_models::{enums::FrmSuggestion, payments::PaymentsCreateIntentRequest}; use async_trait::async_trait; use common_utils::{ errors::CustomResult, ext_traits::Encode, types::{authentication, keymanager::ToEncryptable}, }; use error_stack::ResultExt; use masking::PeekInterface; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{self, helpers, operations}, }, routes::{app::ReqState, SessionState}, types::{ api, domain::{self, types as domain_types}, storage::{self, enums}, }, }; #[derive(Debug, Clone, Copy)] pub struct PaymentIntentCreate; impl<F: Send + Clone + Sync> Operation<F, PaymentsCreateIntentRequest> for &PaymentIntentCreate { type Data = payments::PaymentIntentData<F>; fn to_validate_request( &self, ) -> RouterResult< &(dyn ValidateRequest<F, PaymentsCreateIntentRequest, Self::Data> + Send + Sync), > { Ok(*self) } fn to_get_tracker( &self, ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsCreateIntentRequest> + Send + Sync)> { Ok(*self) } fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentsCreateIntentRequest, Self::Data>)> { Ok(*self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsCreateIntentRequest> + Send + Sync)> { Ok(*self) } } impl<F: Send + Clone + Sync> Operation<F, PaymentsCreateIntentRequest> for PaymentIntentCreate { type Data = payments::PaymentIntentData<F>; fn to_validate_request( &self, ) -> RouterResult< &(dyn ValidateRequest<F, PaymentsCreateIntentRequest, Self::Data> + Send + Sync), > { Ok(self) } fn to_get_tracker( &self, ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsCreateIntentRequest> + Send + Sync)> { Ok(self) } fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsCreateIntentRequest, Self::Data>> { Ok(self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsCreateIntentRequest> + Send + Sync)> { Ok(self) } } type PaymentsCreateIntentOperation<'b, F> = BoxedOperation<'b, F, PaymentsCreateIntentRequest, payments::PaymentIntentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentIntentData<F>, PaymentsCreateIntentRequest> for PaymentIntentCreate { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &common_utils::id_type::GlobalPaymentId, request: &PaymentsCreateIntentRequest, merchant_context: &domain::MerchantContext, 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 batch_encrypted_data = domain_types::crypto_operation( key_manager_state, common_utils::type_name!(hyperswitch_domain_models::payments::PaymentIntent), domain_types::CryptoOperation::BatchEncrypt( hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent::to_encryptable( hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent { shipping_address: request.shipping.clone().map(|address| address.encode_to_value()).transpose().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to encode shipping address")?.map(masking::Secret::new), billing_address: request.billing.clone().map(|address| address.encode_to_value()).transpose().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to encode billing address")?.map(masking::Secret::new), customer_details: None, }, ), ), common_utils::types::keymanager::Identifier::Merchant(merchant_context.get_merchant_account().get_id().to_owned()), merchant_context.get_merchant_key_store().key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting payment intent details".to_string())?; let encrypted_data = hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent::from_encryptable(batch_encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting payment intent details")?; let payment_intent_domain = hyperswitch_domain_models::payments::PaymentIntent::create_domain_model_from_request( payment_id, merchant_context, profile, request.clone(), encrypted_data, ) .await?; let payment_intent = db .insert_payment_intent( key_manager_state, payment_intent_domain, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: format!( "Payment Intent with payment_id {} already exists", payment_id.get_string_repr() ), }) .attach_printable("failed while inserting new payment intent")?; let client_secret = helpers::create_client_secret( state, merchant_context.get_merchant_account().get_id(), authentication::ResourceId::Payment(payment_id.clone()), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to create client secret")?; let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, client_secret: Some(client_secret.secret), sessions_token: vec![], vault_session_details: None, connector_customer_id: None, }; let get_trackers_response = operations::GetTrackerResponse { payment_data }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, payments::PaymentIntentData<F>, PaymentsCreateIntentRequest> for PaymentIntentCreate { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, _state: &'b SessionState, _req_state: ReqState, payment_data: payments::PaymentIntentData<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<( PaymentsCreateIntentOperation<'b, F>, payments::PaymentIntentData<F>, )> where F: 'b + Send, { Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone> ValidateRequest<F, PaymentsCreateIntentRequest, payments::PaymentIntentData<F>> for PaymentIntentCreate { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, _request: &PaymentsCreateIntentRequest, 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, PaymentsCreateIntentRequest, payments::PaymentIntentData<F>> for PaymentIntentCreate { #[instrument(skip_all)] async fn get_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut payments::PaymentIntentData<F>, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, PaymentsCreateIntentRequest, payments::PaymentIntentData<F>>, Option<domain::Customer>, ), errors::StorageError, > { // validate customer_id if sent in the request if let Some(id) = payment_data.payment_intent.customer_id.clone() { state .store .find_customer_by_global_id(&state.into(), &id, merchant_key_store, storage_scheme) .await?; } Ok((Box::new(self), None)) } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut payments::PaymentIntentData<F>, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentsCreateIntentOperation<'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, // TODO: do not take the whole payment data here payment_data: &mut payments::PaymentIntentData<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::PaymentIntentData<F>, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_create_intent.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_614863014174332914
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_complete_authorize.rs // Contains: 1 structs, 0 enums use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; use error_stack::{report, ResultExt}; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, mandate::helpers as m_helpers, payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ api::{self, CustomerAcceptance, PaymentIdTypeExt}, domain, storage::{self, enums as storage_enums}, }, utils::{self, OptionExt}, }; #[derive(Debug, Clone, Copy, PaymentOperation)] #[operation(operations = "all", flow = "authorize")] pub struct CompleteAuthorize; type CompleteAuthorizeOperation<'b, F> = BoxedOperation<'b, F, api::PaymentsRequest, PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for CompleteAuthorize { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &api::PaymentsRequest, merchant_context: &domain::MerchantContext, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let (mut payment_intent, mut payment_attempt, currency, amount); let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; payment_intent = db .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, merchant_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; // TODO (#7195): Add platform merchant account validation once client_secret auth is solved payment_intent.setup_future_usage = request .setup_future_usage .or(payment_intent.setup_future_usage); helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?; helpers::validate_payment_status_against_not_allowed_statuses( payment_intent.status, &[ storage_enums::IntentStatus::Failed, storage_enums::IntentStatus::Succeeded, ], "confirm", )?; let browser_info = request .browser_info .clone() .as_ref() .map(utils::Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; let recurring_details = request.recurring_details.clone(); payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, &payment_intent.active_attempt.get_id(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let mandate_type = m_helpers::get_mandate_type( request.mandate_data.clone(), request.off_session, payment_intent.setup_future_usage, request.customer_acceptance.clone(), request.payment_token.clone(), payment_attempt.payment_method, ) .change_context(errors::ApiErrorResponse::MandateValidationFailed { reason: "Expected one out of recurring_details and mandate_data but got both".into(), })?; let m_helpers::MandateGenericData { token, payment_method, payment_method_type, mandate_data, recurring_mandate_payment_data, mandate_connector, payment_method_info, } = Box::pin(helpers::get_token_pm_type_mandate_details( state, request, mandate_type.to_owned(), merchant_context, payment_attempt.payment_method_id.clone(), payment_intent.customer_id.as_ref(), )) .await?; let customer_acceptance: Option<CustomerAcceptance> = request.customer_acceptance.clone().or(payment_method_info .clone() .map(|pm| { pm.customer_acceptance .parse_value::<CustomerAcceptance>("CustomerAcceptance") }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize to CustomerAcceptance")?); let token = token.or_else(|| payment_attempt.payment_token.clone()); if let Some(payment_method) = payment_method { let should_validate_pm_or_token_given = //this validation should happen if data was stored in the vault helpers::should_store_payment_method_data_in_vault( &state.conf.temp_locker_enable_config, payment_attempt.connector.clone(), payment_method, ); if should_validate_pm_or_token_given { helpers::validate_pm_or_token_given( &request.payment_method, &request .payment_method_data .as_ref() .and_then(|pmd| pmd.payment_method_data.clone()), &request.payment_method_type, &mandate_type, &token, &request.ctp_service_details, )?; } } let token_data = if let Some((token, payment_method)) = token .as_ref() .zip(payment_method.or(payment_attempt.payment_method)) { Some( helpers::retrieve_payment_token_data(state, token.clone(), Some(payment_method)) .await?, ) } else { None }; payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method); payment_attempt.browser_info = browser_info.or(payment_attempt.browser_info); payment_attempt.payment_method_type = payment_method_type.or(payment_attempt.payment_method_type); payment_attempt.payment_experience = request .payment_experience .or(payment_attempt.payment_experience); currency = payment_attempt.currency.get_required_value("currency")?; amount = payment_attempt.get_total_amount().into(); let customer_id = payment_intent .customer_id .as_ref() .or(request.customer_id.as_ref()) .cloned(); helpers::validate_customer_id_mandatory_cases( request.setup_future_usage.is_some(), customer_id.as_ref(), )?; let shipping_address = helpers::create_or_update_address_for_payment_by_request( state, request.shipping.as_ref(), payment_intent.shipping_address_id.clone().as_deref(), merchant_id, payment_intent.customer_id.as_ref(), merchant_context.get_merchant_key_store(), &payment_id, storage_scheme, ) .await?; payment_intent.shipping_address_id = shipping_address .as_ref() .map(|shipping_address| shipping_address.address_id.clone()); let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let payment_method_billing = helpers::get_address_by_id( state, payment_attempt.payment_method_billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let redirect_response = request .feature_metadata .as_ref() .and_then(|fm| fm.redirect_response.clone()); payment_intent.shipping_address_id = shipping_address.clone().map(|i| i.address_id); payment_intent.billing_address_id = billing_address.clone().map(|i| i.address_id); payment_intent.return_url = request .return_url .as_ref() .map(|a| a.to_string()) .or(payment_intent.return_url); payment_intent.allowed_payment_method_types = request .get_allowed_payment_method_types_as_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error converting allowed_payment_types to Value")? .or(payment_intent.allowed_payment_method_types); payment_intent.connector_metadata = request .get_connector_metadata_as_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error converting connector_metadata to Value")? .or(payment_intent.connector_metadata); payment_intent.feature_metadata = request .get_feature_metadata_as_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error converting feature_metadata to Value")? .or(payment_intent.feature_metadata); payment_intent.metadata = request.metadata.clone().or(payment_intent.metadata); // The operation merges mandate data from both request and payment_attempt let setup_mandate = mandate_data; let mandate_details_present = payment_attempt.mandate_details.is_some() || request.mandate_data.is_some(); helpers::validate_mandate_data_and_future_usage( payment_intent.setup_future_usage, mandate_details_present, )?; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = db .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 creds_identifier = request .merchant_connector_details .as_ref() .map(|merchant_connector_details| { merchant_connector_details.creds_identifier.to_owned() }); let payment_data = PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount, email: request.email.clone(), mandate_id: None, mandate_connector, setup_mandate, customer_acceptance, token, token_data, address: PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ), confirm: request.confirm, payment_method_data: request .payment_method_data .as_ref() .and_then(|pmd| pmd.payment_method_data.clone().map(Into::into)), payment_method_token: None, payment_method_info, force_sync: None, all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: request.card_cvc.clone(), creds_identifier, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data, ephemeral_key: None, multiple_capture_data: None, redirect_response, surcharge_details: None, frm_message: None, payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], authentication: None, recurring_details, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: request.threeds_method_comp_ind.clone(), whole_connector_response: None, is_manual_retry_enabled: None, is_l2_l3_enabled: business_profile.is_l2_l3_enabled, }; let customer_details = Some(CustomerDetails { customer_id, name: request.name.clone(), email: request.email.clone(), phone: request.phone.clone(), phone_country_code: request.phone_country_code.clone(), tax_registration_id: None, }); let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details, payment_data, business_profile, mandate_type, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for CompleteAuthorize { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, storage_scheme: common_enums::enums::MerchantStorageScheme, ) -> CustomResult< (CompleteAuthorizeOperation<'a, F>, Option<domain::Customer>), errors::StorageError, > { helpers::create_customer_if_not_exist( state, Box::new(self), payment_data, request, &key_store.merchant_id, key_store, storage_scheme, ) .await } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, state: &'a SessionState, payment_data: &mut PaymentData<F>, storage_scheme: storage_enums::MerchantStorageScheme, merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, should_retry_with_pan: bool, ) -> RouterResult<( CompleteAuthorizeOperation<'a, F>, Option<domain::PaymentMethodData>, Option<String>, )> { let (op, payment_method_data, pm_id) = Box::pin(helpers::make_pm_data( Box::new(self), state, payment_data, merchant_key_store, customer, storage_scheme, business_profile, should_retry_with_pan, )) .await?; Ok((op, payment_method_data, pm_id)) } #[instrument(skip_all)] async fn add_task_to_process_tracker<'a>( &'a self, _state: &'a SessionState, _payment_attempt: &storage::PaymentAttempt, _requeue: bool, _schedule_time: Option<time::PrimitiveDateTime>, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } async fn get_connector<'a>( &'a self, _merchant_context: &domain::MerchantContext, state: &SessionState, request: &api::PaymentsRequest, _payment_intent: &storage::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { // Use a new connector in the confirm call or use the same one which was passed when // creating the payment or if none is passed then use the routing algorithm helpers::get_connector_default(state, request.routing.clone()).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut PaymentData<F>, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for CompleteAuthorize { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, req_state: ReqState, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(CompleteAuthorizeOperation<'b, F>, PaymentData<F>)> where F: 'b + Send, { let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::CompleteAuthorizeUpdate { shipping_address_id: payment_data.payment_intent.shipping_address_id.clone() }; let db = &*state.store; let payment_intent = payment_data.payment_intent.clone(); let updated_payment_intent = db .update_payment_intent( &state.into(), payment_intent, payment_intent_update, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentCompleteAuthorize)) .with(payment_data.to_event()) .emit(); payment_data.payment_intent = updated_payment_intent; Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRequest, PaymentData<F>> for CompleteAuthorize { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsRequest, merchant_context: &'a domain::MerchantContext, ) -> RouterResult<( CompleteAuthorizeOperation<'b, F>, operations::ValidateResult, )> { let payment_id = request .payment_id .clone() .ok_or(report!(errors::ApiErrorResponse::PaymentNotFound))?; let request_merchant_id = request.merchant_id.as_ref(); helpers::validate_merchant_id( merchant_context.get_merchant_account().get_id(), request_merchant_id, ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "merchant_id".to_string(), expected_format: "merchant_id from merchant account".to_string(), })?; helpers::validate_payment_method_fields_present(request)?; let _mandate_type = helpers::validate_mandate(request, payments::is_operation_confirm(self))?; helpers::validate_recurring_details_and_token( &request.recurring_details, &request.payment_token, &request.mandate_id, )?; Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), payment_id, storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: matches!( request.retry_action, Some(api_models::enums::RetryAction::Requeue) ), }, )) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_complete_authorize.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_3279735586958301484
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_capture.rs // Contains: 1 structs, 0 enums use std::{marker::PhantomData, ops::Deref}; use api_models::enums::FrmSuggestion; use async_trait::async_trait; use common_utils::ext_traits::AsyncExt; use error_stack::ResultExt; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{self, helpers, operations, types::MultipleCaptureData}, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ self as core_types, api::{self, PaymentIdTypeExt}, domain, storage::{self, enums, payment_attempt::PaymentAttemptExt}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, router_derive::PaymentOperation)] #[operation(operations = "all", flow = "capture")] pub struct PaymentCapture; type PaymentCaptureOperation<'b, F> = BoxedOperation<'b, F, api::PaymentsCaptureRequest, payments::PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRequest> for PaymentCapture { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &api::PaymentsCaptureRequest, merchant_context: &domain::MerchantContext, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult< operations::GetTrackerResponse< 'a, F, api::PaymentsCaptureRequest, payments::PaymentData<F>, >, > { let db = &*state.store; let key_manager_state = &state.into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let (payment_intent, mut payment_attempt, currency, amount); let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; payment_intent = db .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, merchant_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, payment_intent.active_attempt.get_id().as_str(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_attempt .amount_to_capture .update_value(request.amount_to_capture); let capture_method = payment_attempt .capture_method .get_required_value("capture_method")?; helpers::validate_status_with_capture_method(payment_intent.status, capture_method)?; if !*payment_attempt .is_overcapture_enabled .unwrap_or_default() .deref() { helpers::validate_amount_to_capture( payment_attempt.amount_capturable.get_amount_as_i64(), request .amount_to_capture .map(|capture_amount| capture_amount.get_amount_as_i64()), )?; } helpers::validate_capture_method(capture_method)?; let multiple_capture_data = if capture_method == enums::CaptureMethod::ManualMultiple { let amount_to_capture = request .amount_to_capture .get_required_value("amount_to_capture")?; helpers::validate_amount_to_capture( payment_attempt.amount_capturable.get_amount_as_i64(), Some(amount_to_capture.get_amount_as_i64()), )?; let previous_captures = db .find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &payment_attempt.merchant_id, &payment_attempt.payment_id, &payment_attempt.attempt_id, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let capture = db .insert_capture( payment_attempt .make_new_capture(amount_to_capture, enums::CaptureStatus::Started)?, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::DuplicatePayment { payment_id: payment_id.clone(), })?; Some(MultipleCaptureData::new_for_create( previous_captures, capture, )) } else { None }; currency = payment_attempt.currency.get_required_value("currency")?; amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( state, payment_intent.shipping_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let payment_method_billing = helpers::get_address_by_id( state, payment_attempt.payment_method_billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let creds_identifier = request .merchant_connector_details .as_ref() .map(|mcd| mcd.creds_identifier.to_owned()); request .merchant_connector_details .to_owned() .async_map(|mcd| async { helpers::insert_merchant_connector_creds_to_config( db, merchant_context.get_merchant_account().get_id(), mcd, ) .await }) .await .transpose()?; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = db .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 payment_data = payments::PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, force_sync: None, all_keys_required: None, amount, email: None, mandate_id: None, mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, token_data: None, address: core_types::PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ), confirm: None, payment_method_data: None, payment_method_token: None, payment_method_info: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: None, creds_identifier, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data, redirect_response: None, surcharge_details: None, frm_message: None, payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], authentication: None, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, whole_connector_response: None, is_manual_retry_enabled: None, is_l2_l3_enabled: false, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRequest> for PaymentCapture { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, db: &'b SessionState, req_state: ReqState, mut payment_data: payments::PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, _mechant_key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(PaymentCaptureOperation<'b, F>, payments::PaymentData<F>)> where F: 'b + Send, { payment_data.payment_attempt = if payment_data.multiple_capture_data.is_some() || payment_data.payment_attempt.amount_to_capture.is_some() { let multiple_capture_count = payment_data .multiple_capture_data .as_ref() .map(|multiple_capture_data| multiple_capture_data.get_captures_count()) .transpose()?; let amount_to_capture = payment_data.payment_attempt.amount_to_capture; db.store .update_payment_attempt_with_attempt_id( payment_data.payment_attempt, storage::PaymentAttemptUpdate::CaptureUpdate { amount_to_capture, multiple_capture_count, updated_by: storage_scheme.to_string(), }, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)? } else { payment_data.payment_attempt }; let capture_amount = payment_data.payment_attempt.amount_to_capture; let multiple_capture_count = payment_data.payment_attempt.multiple_capture_count; req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentCapture { capture_amount, multiple_capture_count, })) .with(payment_data.to_event()) .emit(); Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsCaptureRequest, payments::PaymentData<F>> for PaymentCapture { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsCaptureRequest, merchant_context: &'a domain::MerchantContext, ) -> RouterResult<(PaymentCaptureOperation<'b, F>, operations::ValidateResult)> { Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()), storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: false, }, )) } }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_capture.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }