id
stringlengths
24
57
type
stringclasses
1 value
granularity
stringclasses
4 values
content
stringlengths
8.08k
87.1k
metadata
dict
large_file_786303003785188127
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/phonepe.rs </path> <file> 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 PhonepeTest; impl ConnectorActions for PhonepeTest {} impl utils::Connector for PhonepeTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Phonepe; utils::construct_connector_data_old( Box::new(Phonepe::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .phonepe .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "phonepe".to_string() } } static CONNECTOR: PhonepeTest = PhonepeTest {}; 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/phonepe.rs", "files": null, "module": null, "num_files": null, "token_count": 2914 }
large_file_8768686823204189943
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/bluesnap.rs </path> <file> use std::str::FromStr; use common_utils::pii::Email; use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::Secret; use router::types::{self, domain, storage::enums, ConnectorAuthType, PaymentAddress}; use crate::{ connector_auth, utils::{self, ConnectorActions, PaymentInfo}, }; #[derive(Clone, Copy)] struct BluesnapTest; impl ConnectorActions for BluesnapTest {} static CONNECTOR: BluesnapTest = BluesnapTest {}; impl utils::Connector for BluesnapTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Bluesnap; utils::construct_connector_data_old( Box::new(Bluesnap::new()), types::Connector::Bluesnap, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .bluesnap .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "bluesnap".to_string() } } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { email: Some(Email::from_str("[email protected]").unwrap()), ..utils::PaymentAuthorizeType::default().0 }) } fn get_payment_info() -> Option<PaymentInfo> { Some(PaymentInfo { address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("joseph".to_string())), last_name: Some(Secret::new("Doe".to_string())), ..Default::default() }), phone: None, email: None, }), None, None, )), ..Default::default() }) } // 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_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_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_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_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() }), None, ) .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_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_payment_info()) .await .unwrap(); let rsync_response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( rsync_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_payment_info(), ) .await .unwrap(); let rsync_response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( rsync_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[serial_test::serial] #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund(payment_method_details(), None, None, get_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, ); } // 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_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_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). #[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_payment_info()) .await .unwrap(); let rsync_response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( rsync_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_payment_info(), ) .await .unwrap(); let rsync_response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( rsync_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() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let transaction_id = utils::get_connector_transaction_id(authorize_response.response).unwrap(); for _x in 0..2 { tokio::time::sleep(std::time::Duration::from_secs(5)).await; // to avoid 404 error let refund_response = CONNECTOR .refund_payment( transaction_id.clone(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); let rsync_response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( rsync_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[serial_test::serial] #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_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, ); } // 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 { email: Some(Email::from_str("[email protected]").unwrap()), payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "VALIDATION_GENERAL_FAILURE".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 { email: Some(Email::from_str("[email protected]").unwrap()), 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_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "VALIDATION_GENERAL_FAILURE".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 { email: Some(Email::from_str("[email protected]").unwrap()), 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_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "VALIDATION_GENERAL_FAILURE".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_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, None) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "TRANSACTION_ALREADY_CAPTURED" ); } // 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, None) .await .unwrap(); capture_response .response .unwrap_err() .message .contains("is not authorized to view transaction"); } // 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_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "REFUND_MAX_AMOUNT_FAILURE", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests </file>
{ "crate": "router", "file": "crates/router/tests/connectors/bluesnap.rs", "files": null, "module": null, "num_files": null, "token_count": 3550 }
large_file_-232663732075199576
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/trustpayments.rs </path> <file> use std::str::FromStr; 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 TrustpaymentsTest; impl ConnectorActions for TrustpaymentsTest {} impl utils::Connector for TrustpaymentsTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Trustpayments; utils::construct_connector_data_old( Box::new(Trustpayments::new()), types::Connector::Trustpayments, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .trustpayments .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "trustpayments".to_string() } } static CONNECTOR: TrustpaymentsTest = TrustpaymentsTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(types::PaymentAddress::new( None, None, Some(hyperswitch_domain_models::address::Address { address: Some(hyperswitch_domain_models::address::AddressDetails { country: Some(common_enums::CountryAlpha2::US), city: Some("New York".to_string()), zip: Some(Secret::new("10001".to_string())), line1: Some(Secret::new("123 Main St".to_string())), line2: None, line3: None, state: Some(Secret::new("NY".to_string())), first_name: Some(Secret::new("John".to_string())), last_name: Some(Secret::new("Doe".to_string())), origin_zip: None, }), phone: Some(hyperswitch_domain_models::address::PhoneDetails { number: Some(Secret::new("1234567890".to_string())), country_code: Some("+1".to_string()), }), email: None, }), None, )), ..Default::default() }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("12".to_string()), card_exp_year: Secret::new("2025".to_string()), card_cvc: Secret::new("123".to_string()), card_issuer: None, card_network: None, card_type: None, card_issuing_country: None, bank_code: None, nick_name: None, card_holder_name: Some(Secret::new("John Doe".to_string())), co_badged_card_data: None, }), confirm: true, amount: 100, minor_amount: common_utils::types::MinorUnit::new(100), currency: enums::Currency::USD, capture_method: Some(enums::CaptureMethod::Manual), ..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(), 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/trustpayments.rs", "files": null, "module": null, "num_files": null, "token_count": 3404 }
large_file_7664409505542100747
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/helcim.rs </path> <file> use masking::Secret; use router::types::{self, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct HelcimTest; impl ConnectorActions for HelcimTest {} impl utils::Connector for HelcimTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Helcim; utils::construct_connector_data_old( Box::new(Helcim::new()), types::Connector::Helcim, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .helcim .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "helcim".to_string() } } static CONNECTOR: HelcimTest = HelcimTest {}; 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/helcim.rs", "files": null, "module": null, "num_files": null, "token_count": 2924 }
large_file_-2972888874478170509
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/celero.rs </path> <file> 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 CeleroTest; impl ConnectorActions for CeleroTest {} impl utils::Connector for CeleroTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Celero; utils::construct_connector_data_old( Box::new(Celero::new()), types::Connector::Celero, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .celero .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "celero".to_string() } } static CONNECTOR: CeleroTest = CeleroTest {}; 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/celero.rs", "files": null, "module": null, "num_files": null, "token_count": 2912 }
large_file_-3339693283464899650
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/plaid.rs </path> <file> use masking::Secret; use router::types::{self, api, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, Connector, ConnectorActions}; #[derive(Clone, Copy)] struct PlaidTest; impl ConnectorActions for PlaidTest {} static CONNECTOR: PlaidTest = PlaidTest {}; impl Connector for PlaidTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Plaid; utils::construct_connector_data_old( Box::new(Plaid::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .plaid .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "plaid".to_string() } } 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, "Invalid card cvc.".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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/plaid.rs", "files": null, "module": null, "num_files": null, "token_count": 2909 }
large_file_198252293958666669
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/mifinity.rs </path> <file> use masking::Secret; use router::types::{self, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct MifinityTest; impl ConnectorActions for MifinityTest {} impl utils::Connector for MifinityTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Mifinity; utils::construct_connector_data_old( Box::new(Mifinity::new()), types::Connector::Mifinity, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .mifinity .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "mifinity".to_string() } } static CONNECTOR: MifinityTest = MifinityTest {}; 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/mifinity.rs", "files": null, "module": null, "num_files": null, "token_count": 2923 }
large_file_6699107117192435890
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/worldline.rs </path> <file> use std::str::FromStr; use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::Secret; use router::{ connector::Worldline, core::errors, types::{self, storage::enums, PaymentAddress}, }; use crate::{ connector_auth::ConnectorAuthentication, utils::{self, ConnectorActions, PaymentInfo}, }; struct WorldlineTest; impl ConnectorActions for WorldlineTest {} impl utils::Connector for WorldlineTest { fn get_data(&self) -> types::api::ConnectorData { utils::construct_connector_data_old( Box::new(&Worldline), types::Connector::Worldline, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( ConnectorAuthentication::new() .worldline .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { String::from("worldline") } } impl WorldlineTest { fn get_payment_info() -> Option<PaymentInfo> { Some(PaymentInfo { address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { country: Some(api_models::enums::CountryAlpha2::US), first_name: Some(Secret::new(String::from("John"))), last_name: Some(Secret::new(String::from("Dough"))), ..Default::default() }), phone: None, email: None, }), None, None, )), ..Default::default() }) } fn get_payment_authorize_data( card_number: &str, card_exp_month: &str, card_exp_year: &str, card_cvc: &str, capture_method: enums::CaptureMethod, ) -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { amount: 3500, currency: enums::Currency::USD, payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str(card_number).unwrap(), card_exp_month: Secret::new(card_exp_month.to_string()), card_exp_year: Secret::new(card_exp_year.to_string()), card_cvc: Secret::new(card_cvc.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, }), confirm: true, statement_descriptor_suffix: None, statement_descriptor: None, setup_future_usage: None, mandate_id: None, off_session: None, setup_mandate_details: None, capture_method: Some(capture_method), browser_info: None, 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, webhook_url: None, complete_authorize_url: None, customer_id: None, surcharge_details: None, request_incremental_authorization: false, metadata: None, authentication_data: None, customer_acceptance: None, ..utils::PaymentAuthorizeType::default().0 }) } } #[actix_web::test] async fn should_requires_manual_authorization() { let authorize_data = WorldlineTest::get_payment_authorize_data( "5424 1802 7979 1732", "10", "25", "123", enums::CaptureMethod::Manual, ); let response = WorldlineTest {} .authorize_payment(authorize_data, WorldlineTest::get_payment_info()) .await; assert_eq!(response.unwrap().status, enums::AttemptStatus::Authorized); } #[actix_web::test] async fn should_auto_authorize_and_request_capture() { let authorize_data = WorldlineTest::get_payment_authorize_data( "4012000033330026", "10", "2025", "123", enums::CaptureMethod::Automatic, ); let response = WorldlineTest {} .make_payment(authorize_data, WorldlineTest::get_payment_info()) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Pending); } #[actix_web::test] async fn should_throw_not_implemented_for_unsupported_issuer() { let authorize_data = WorldlineTest::get_payment_authorize_data( "630495060000000000", "10", "25", "123", enums::CaptureMethod::Automatic, ); let response = WorldlineTest {} .make_payment(authorize_data, WorldlineTest::get_payment_info()) .await; assert_eq!( *response.unwrap_err().current_context(), errors::ConnectorError::NotSupported { message: "Maestro".to_string(), connector: "worldline", } ) } #[actix_web::test] async fn should_throw_missing_required_field_for_country() { let authorize_data = WorldlineTest::get_payment_authorize_data( "4012 0000 3333 0026", "10", "2025", "123", enums::CaptureMethod::Automatic, ); let response = WorldlineTest {} .make_payment( authorize_data, Some(PaymentInfo { address: Some(PaymentAddress::new(None, None, None, None)), ..Default::default() }), ) .await; assert_eq!( *response.unwrap_err().current_context(), errors::ConnectorError::MissingRequiredField { field_name: "billing.address.country" } ) } #[actix_web::test] async fn should_fail_payment_for_invalid_cvc() { let authorize_data = WorldlineTest::get_payment_authorize_data( "4012000033330026", "10", "25", "", enums::CaptureMethod::Automatic, ); let response = WorldlineTest {} .make_payment(authorize_data, WorldlineTest::get_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "NULL VALUE NOT ALLOWED FOR cardPaymentMethodSpecificInput.card.cvv".to_string(), ); } #[actix_web::test] async fn should_sync_manual_auth_payment() { let connector = WorldlineTest {}; let authorize_data = WorldlineTest::get_payment_authorize_data( "4012 0000 3333 0026", "10", "2025", "123", enums::CaptureMethod::Manual, ); let response = connector .authorize_payment(authorize_data, WorldlineTest::get_payment_info()) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); let connector_payment_id = utils::get_connector_transaction_id(response.response).unwrap_or_default(); let sync_response = connector .sync_payment( Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( connector_payment_id, ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); } #[actix_web::test] async fn should_sync_auto_auth_payment() { let connector = WorldlineTest {}; let authorize_data = WorldlineTest::get_payment_authorize_data( "4012000033330026", "10", "25", "123", enums::CaptureMethod::Automatic, ); let response = connector .make_payment(authorize_data, WorldlineTest::get_payment_info()) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Pending); let connector_payment_id = utils::get_connector_transaction_id(response.response).unwrap_or_default(); let sync_response = connector .sync_payment( Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( connector_payment_id, ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); } #[actix_web::test] async fn should_capture_authorized_payment() { let connector = WorldlineTest {}; let authorize_data = WorldlineTest::get_payment_authorize_data( "4012 0000 3333 0026", "10", "2025", "123", enums::CaptureMethod::Manual, ); let response = connector .authorize_payment(authorize_data, WorldlineTest::get_payment_info()) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); let connector_payment_id = utils::get_connector_transaction_id(response.response).unwrap_or_default(); let capture_response = WorldlineTest {} .capture_payment(connector_payment_id, None, None) .await .unwrap(); assert_eq!( capture_response.status, enums::AttemptStatus::CaptureInitiated ); } #[actix_web::test] async fn should_fail_capture_payment() { let capture_response = WorldlineTest {} .capture_payment("123456789".to_string(), None, None) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, "UNKNOWN_PAYMENT_ID".to_string() ); } #[actix_web::test] async fn should_cancel_unauthorized_payment() { let connector = WorldlineTest {}; let authorize_data = WorldlineTest::get_payment_authorize_data( "4012 0000 3333 0026", "10", "25", "123", enums::CaptureMethod::Manual, ); let response = connector .authorize_payment(authorize_data, WorldlineTest::get_payment_info()) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); let connector_payment_id = utils::get_connector_transaction_id(response.response).unwrap_or_default(); let cancel_response = connector .void_payment(connector_payment_id, None, None) .await .unwrap(); assert_eq!(cancel_response.status, enums::AttemptStatus::Voided); } #[actix_web::test] async fn should_cancel_uncaptured_payment() { let connector = WorldlineTest {}; let authorize_data = WorldlineTest::get_payment_authorize_data( "4012000033330026", "10", "2025", "123", enums::CaptureMethod::Automatic, ); let response = connector .make_payment(authorize_data, WorldlineTest::get_payment_info()) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Pending); let connector_payment_id = utils::get_connector_transaction_id(response.response).unwrap_or_default(); let cancel_response = connector .void_payment(connector_payment_id, None, None) .await .unwrap(); assert_eq!(cancel_response.status, enums::AttemptStatus::Voided); } #[actix_web::test] async fn should_fail_cancel_with_invalid_payment_id() { let response = WorldlineTest {} .void_payment("123456789".to_string(), None, None) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "UNKNOWN_PAYMENT_ID".to_string(), ); } #[actix_web::test] async fn should_fail_refund_with_invalid_payment_status() { let connector = WorldlineTest {}; let authorize_data = WorldlineTest::get_payment_authorize_data( "4012 0000 3333 0026", "10", "25", "123", enums::CaptureMethod::Manual, ); let response = connector .authorize_payment(authorize_data, WorldlineTest::get_payment_info()) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); let connector_payment_id = utils::get_connector_transaction_id(response.response).unwrap_or_default(); let refund_response = connector .refund_payment(connector_payment_id, None, None) .await .unwrap(); assert_eq!( refund_response.response.unwrap_err().message, "ORDER WITHOUT REFUNDABLE PAYMENTS".to_string(), ); } </file>
{ "crate": "router", "file": "crates/router/tests/connectors/worldline.rs", "files": null, "module": null, "num_files": null, "token_count": 2967 }
large_file_3256637684295312662
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/bankofamerica.rs </path> <file> use masking::Secret; use router::types::{self, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct BankofamericaTest; impl ConnectorActions for BankofamericaTest {} impl utils::Connector for BankofamericaTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Bankofamerica; utils::construct_connector_data_old( Box::new(Bankofamerica::new()), // 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() .bankofamerica .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "bankofamerica".to_string() } } static CONNECTOR: BankofamericaTest = BankofamericaTest {}; 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/bankofamerica.rs", "files": null, "module": null, "num_files": null, "token_count": 2958 }
large_file_3757248826969451660
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/square.rs </path> <file> use std::{str::FromStr, time::Duration}; use masking::Secret; use router::types::{self, storage::enums, PaymentsResponseData}; use test_utils::connector_auth::ConnectorAuthentication; use crate::utils::{self, get_connector_transaction_id, Connector, ConnectorActions}; #[derive(Clone, Copy)] struct SquareTest; impl ConnectorActions for SquareTest {} impl Connector for SquareTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Square; utils::construct_connector_data_old( Box::new(&Square), types::Connector::Square, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( ConnectorAuthentication::new() .square .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "square".to_string() } } static CONNECTOR: SquareTest = SquareTest {}; fn get_default_payment_info(payment_method_token: Option<String>) -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: None, auth_type: None, access_token: None, connector_meta_data: None, connector_customer: None, payment_method_token, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] currency: None, }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } fn token_details() -> Option<types::PaymentMethodTokenizationData> { Some(types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("04".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("100".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, split_payments: None, mandate_id: None, setup_future_usage: None, customer_acceptance: None, setup_mandate_details: None, }) } async fn create_token() -> Option<String> { let token_response = CONNECTOR .create_connector_pm_token(token_details(), get_default_payment_info(None)) .await .expect("Authorize payment response"); match token_response.response.unwrap() { PaymentsResponseData::TokenizationResponse { token } => Some(token), _ => 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(create_token().await), ) .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(create_token().await), ) .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] #[ignore = "Connector does not support partial capture"] 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(create_token().await), ) .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(create_token().await), ) .await .expect("Authorize payment response"); let txn_id = 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(None), ) .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(create_token().await), ) .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 refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(create_token().await), ) .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(None), ) .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 refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(create_token().await), ) .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(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 refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(create_token().await), ) .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(None), ) .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(create_token().await), ) .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(create_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = 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(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 refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), None, get_default_payment_info(create_token().await), ) .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(None), ) .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(create_token().await), ) .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(None), ) .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() { //make a successful payment let response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .unwrap(); let refund_data = Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }); //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(CONNECTOR.get_request_interval())).await; // to avoid 404 error let refund_response = CONNECTOR .refund_payment( transaction_id.clone(), refund_data.clone(), get_default_payment_info(None), ) .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(None), ) .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( payment_method_details(), None, get_default_payment_info(create_token().await), ) .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(None), ) .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 token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("11".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, split_payments: None, mandate_id: None, setup_future_usage: None, customer_acceptance: None, setup_mandate_details: None, }), get_default_payment_info(None), ) .await .expect("Authorize payment response"); assert_eq!( token_response .response .unwrap_err() .reason .unwrap_or("".to_string()), "Missing required parameter.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("20".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, split_payments: None, mandate_id: None, setup_future_usage: None, customer_acceptance: None, setup_mandate_details: None, }), get_default_payment_info(None), ) .await .expect("Authorize payment response"); assert_eq!( token_response .response .unwrap_err() .reason .unwrap_or("".to_string()), "Invalid card expiration date.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("11".to_string()), card_exp_year: Secret::new("2000".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, split_payments: None, mandate_id: None, setup_future_usage: None, customer_acceptance: None, setup_mandate_details: None, }), get_default_payment_info(None), ) .await .expect("Authorize payment response"); assert_eq!( token_response .response .unwrap_err() .reason .unwrap_or("".to_string()), "Invalid card expiration date.".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(create_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment( txn_id.clone().unwrap(), None, get_default_payment_info(None), ) .await .unwrap(); let connector_transaction_id = txn_id.unwrap(); assert_eq!( void_response.response.unwrap_err().reason.unwrap_or("".to_string()), format!("Payment {connector_transaction_id} is in inflight state COMPLETED, which is invalid for the requested operation") ); } // 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(create_token().await), ) .await .unwrap(); assert_eq!( capture_response .response .unwrap_err() .reason .unwrap_or("".to_string()), String::from("Could not find payment with id: 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(create_token().await), ) .await .unwrap(); assert_eq!( response .response .unwrap_err() .reason .unwrap_or("".to_string()), "The requested refund amount exceeds the amount available to refund.", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests </file>
{ "crate": "router", "file": "crates/router/tests/connectors/square.rs", "files": null, "module": null, "num_files": null, "token_count": 4283 }
large_file_5076001575415347500
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/redsys.rs </path> <file> 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 RedsysTest; impl ConnectorActions for RedsysTest {} impl utils::Connector for RedsysTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Redsys; utils::construct_connector_data_old( Box::new(Redsys::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .redsys .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "redsys".to_string() } } static CONNECTOR: RedsysTest = RedsysTest {}; 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/redsys.rs", "files": null, "module": null, "num_files": null, "token_count": 2914 }
large_file_-8756935692255700978
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/loonio.rs </path> <file> 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 LoonioTest; impl ConnectorActions for LoonioTest {} impl utils::Connector for LoonioTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Loonio; utils::construct_connector_data_old( Box::new(Loonio::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .loonio .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "loonio".to_string() } } static CONNECTOR: LoonioTest = LoonioTest {}; 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/loonio.rs", "files": null, "module": null, "num_files": null, "token_count": 2914 }
large_file_4129191998687961781
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/stripebilling.rs </path> <file> 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 StripebillingTest; impl ConnectorActions for StripebillingTest {} impl utils::Connector for StripebillingTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Stripebilling; utils::construct_connector_data_old( Box::new(Stripebilling::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .stripebilling .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "stripebilling".to_string() } } static CONNECTOR: StripebillingTest = StripebillingTest {}; 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/stripebilling.rs", "files": null, "module": null, "num_files": null, "token_count": 2914 }
large_file_3818609189642665839
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/gocardless.rs </path> <file> use masking::Secret; use router::types::{self, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct GocardlessTest; impl ConnectorActions for GocardlessTest {} impl utils::Connector for GocardlessTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Gocardless; utils::construct_connector_data_old( Box::new(Gocardless::new()), types::Connector::Gocardless, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .gocardless .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "gocardless".to_string() } } static CONNECTOR: GocardlessTest = GocardlessTest {}; 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/gocardless.rs", "files": null, "module": null, "num_files": null, "token_count": 2923 }
large_file_-6352524388209630340
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/globalpay.rs </path> <file> use std::str::FromStr; use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::Secret; use router::types::{self, api, domain, storage::enums, AccessToken, ConnectorAuthType}; use serde_json::json; use crate::{ connector_auth, utils::{self, Connector, ConnectorActions, PaymentInfo}, }; struct Globalpay; impl ConnectorActions for Globalpay {} static CONNECTOR: Globalpay = Globalpay {}; impl Connector for Globalpay { fn get_data(&self) -> api::ConnectorData { use router::connector::Globalpay; utils::construct_connector_data_old( Box::new(Globalpay::new()), types::Connector::Globalpay, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .globalpay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "globalpay".to_string() } fn get_connector_meta(&self) -> Option<serde_json::Value> { Some(json!({"account_name": "transaction_processing"})) } } fn get_access_token() -> Option<AccessToken> { match Connector::get_auth_token(&CONNECTOR) { ConnectorAuthType::BodyKey { api_key, key1: _ } => Some(AccessToken { token: api_key, expires: 18600, }), _ => None, } } impl Globalpay { fn get_request_interval(&self) -> u64 { 5 } fn get_payment_info() -> Option<PaymentInfo> { Some(PaymentInfo { address: Some(types::PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { country: Some(api_models::enums::CountryAlpha2::US), ..Default::default() }), phone: None, ..Default::default() }), None, None, )), access_token: get_access_token(), connector_meta_data: CONNECTOR.get_connector_meta(), ..Default::default() }) } } #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(None, Globalpay::get_payment_info()) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); } #[actix_web::test] async fn should_make_payment() { let response = CONNECTOR .make_payment(None, Globalpay::get_payment_info()) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged); } #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( None, Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), Globalpay::get_payment_info(), ) .await; assert_eq!(response.unwrap().status, enums::AttemptStatus::Charged); } #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .authorize_payment(None, Globalpay::get_payment_info()) .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() }), Globalpay::get_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } #[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_number: cards::CardNumber::from_str("4024007134364842").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), Globalpay::get_payment_info(), ) .await .unwrap(); let x = response.status; assert_eq!(x, enums::AttemptStatus::Failure); } #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(None, None, Globalpay::get_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment(None, None, Globalpay::get_payment_info()) .await; assert_eq!(response.unwrap().status, enums::AttemptStatus::Voided); } #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(None, None, Globalpay::get_payment_info()) .await .unwrap(); tokio::time::sleep(std::time::Duration::from_secs( CONNECTOR.get_request_interval(), )) .await; let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, Globalpay::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // 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( None, Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), Globalpay::get_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } #[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 }), Globalpay::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 authorize_response = CONNECTOR .make_payment(None, Globalpay::get_payment_info()) .await .unwrap(); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); let refund_response = CONNECTOR .refund_payment( txn_id, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), Globalpay::get_payment_info(), ) .await .unwrap(); assert_eq!( refund_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(None, None, None, Globalpay::get_payment_info()) .await .unwrap(); tokio::time::sleep(std::time::Duration::from_secs( CONNECTOR.get_request_interval(), )) .await; let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, Globalpay::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // 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( None, Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), Globalpay::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "You may only refund up to 115% of the original amount ", ); } // 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("123ddsa12".to_string(), None, Globalpay::get_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("Transaction 123ddsa12 not found at this location.") ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] #[ignore] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(None, Globalpay::get_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, Globalpay::get_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // 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 }), Globalpay::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Expiry date 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 }), Globalpay::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Invalid Expiry Date".to_string(), ); } // 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( None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), Globalpay::get_payment_info(), ) .await; } // 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(None, Globalpay::get_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() }), Globalpay::get_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // 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(None, None, None, Globalpay::get_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } </file>
{ "crate": "router", "file": "crates/router/tests/connectors/globalpay.rs", "files": null, "module": null, "num_files": null, "token_count": 2990 }
large_file_-884014369461973432
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/airwallex.rs </path> <file> use std::str::FromStr; use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::{PeekInterface, Secret}; use router::types::{self, domain, storage::enums, AccessToken}; use crate::{ connector_auth, utils::{self, Connector, ConnectorActions}, }; #[derive(Clone, Copy)] struct AirwallexTest; impl ConnectorActions for AirwallexTest {} static CONNECTOR: AirwallexTest = AirwallexTest {}; impl Connector for AirwallexTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Airwallex; utils::construct_connector_data_old( Box::new(Airwallex::new()), types::Connector::Airwallex, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .airwallex .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "airwallex".to_string() } } fn get_access_token() -> Option<AccessToken> { match CONNECTOR.get_auth_token() { types::ConnectorAuthType::BodyKey { api_key, key1 } => Some(AccessToken { token: api_key, expires: key1.peek().parse::<i64>().unwrap(), }), _ => None, } } fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { access_token: get_access_token(), 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: None, }), None, )), ..Default::default() }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4035501000000008").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), card_cvc: Secret::new("123".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, }), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), router_return_url: Some("https://google.com".to_string()), complete_authorize_url: Some("https://google.com".to_string()), ..utils::PaymentAuthorizeType::default().0 }) } // 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] #[ignore] 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] #[ignore] 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). // #[serial_test::serial] #[actix_web::test] #[ignore] 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(), ), ..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] #[ignore] 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] #[ignore] 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] #[ignore] 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). // #[serial_test::serial] #[actix_web::test] #[ignore] 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 card number. #[serial_test::serial] #[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("1234567891011").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Invalid card number".to_string(), ); } // 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, "Invalid card cvc".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, "Invalid expiry month".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, "payment_method.card should not be 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().message, "The PaymentIntent status SUCCEEDED is invalid for operation cancel." ); } // 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().message, String::from( "The requested endpoint does not exist [/api/v1/pa/payment_intents/123456789/capture]" ) ); } // Refunds a payment with refund amount higher than payment amount. // #[serial_test::serial] #[actix_web::test] #[ignore] 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/airwallex.rs", "files": null, "module": null, "num_files": null, "token_count": 3677 }
large_file_6343829934023048935
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/calida.rs </path> <file> 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 CalidaTest; impl ConnectorActions for CalidaTest {} impl utils::Connector for CalidaTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Calida; utils::construct_connector_data_old( Box::new(Calida::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .calida .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "calida".to_string() } } static CONNECTOR: CalidaTest = CalidaTest {}; 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/calida.rs", "files": null, "module": null, "num_files": null, "token_count": 2914 }
large_file_-8856920195362581725
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/stripe.rs </path> <file> use std::str::FromStr; use masking::Secret; use router::types::{self, domain, storage::enums}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; struct Stripe; impl ConnectorActions for Stripe {} impl utils::Connector for Stripe { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Stripe; utils::construct_connector_data_old( Box::new(Stripe::new()), types::Connector::Stripe, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .stripe .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "stripe".to_string() } } fn get_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4242424242424242").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }) } #[actix_web::test] async fn should_only_authorize_payment() { let response = Stripe {} .authorize_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); } #[actix_web::test] async fn should_make_payment() { let response = Stripe {} .make_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged); } #[actix_web::test] async fn should_capture_already_authorized_payment() { let connector = Stripe {}; let response = connector .authorize_and_capture_payment(get_payment_authorize_data(), None, None) .await; assert_eq!(response.unwrap().status, enums::AttemptStatus::Charged); } #[actix_web::test] async fn should_partially_capture_already_authorized_payment() { let connector = Stripe {}; let response = connector .authorize_and_capture_payment( get_payment_authorize_data(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), None, ) .await; assert_eq!(response.unwrap().status, enums::AttemptStatus::Charged); } #[actix_web::test] async fn should_sync_authorized_payment() { let connector = Stripe {}; let authorize_response = connector .authorize_payment(get_payment_authorize_data(), 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,); } #[actix_web::test] async fn should_sync_payment() { let connector = Stripe {}; let authorize_response = connector .make_payment(get_payment_authorize_data(), None) .await .unwrap(); let txn_id = utils::get_connector_transaction_id(authorize_response.response); 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,); } #[actix_web::test] async fn should_void_already_authorized_payment() { let connector = Stripe {}; let response = connector .authorize_and_void_payment( get_payment_authorize_data(), Some(types::PaymentsCancelData { connector_transaction_id: "".to_string(), // this connector_transaction_id will be ignored and the transaction_id from payment authorize data will be used for void cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), None, ) .await; assert_eq!(response.unwrap().status, enums::AttemptStatus::Voided); } #[actix_web::test] async fn should_fail_payment_for_incorrect_card_number() { let response = Stripe {} .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(); let x = response.response.unwrap_err(); assert_eq!( x.reason.unwrap(), "Your card was declined. Your request was in test mode, but used a non test (live) card. For a list of valid test cards, visit: https://stripe.com/docs/testing.", ); } #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = Stripe {} .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("13".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); let x = response.response.unwrap_err(); assert_eq!( x.reason.unwrap(), "Your card's expiration month is invalid.", ); } #[actix_web::test] async fn should_fail_payment_for_invalid_exp_year() { let response = Stripe {} .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2022".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); let x = response.response.unwrap_err(); assert_eq!(x.reason.unwrap(), "Your card's expiration year is invalid."); } #[actix_web::test] async fn should_fail_payment_for_invalid_card_cvc() { let response = Stripe {} .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); let x = response.response.unwrap_err(); assert_eq!(x.reason.unwrap(), "Your card's security code is invalid."); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let connector = Stripe {}; // Authorize let authorize_response = connector .make_payment(get_payment_authorize_data(), 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.response.unwrap_err().reason.unwrap(), "You cannot cancel this PaymentIntent because it has a status of succeeded. Only a PaymentIntent with one of the following statuses may be canceled: requires_payment_method, requires_capture, requires_confirmation, requires_action, processing." ); } #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let connector = Stripe {}; let response = connector .capture_payment("12345".to_string(), None, None) .await .unwrap(); let err = response.response.unwrap_err(); assert_eq!( err.reason.unwrap(), "No such payment_intent: '12345'".to_string() ); assert_eq!(err.code, "resource_missing".to_string()); } #[actix_web::test] async fn should_refund_succeeded_payment() { let connector = Stripe {}; let response = connector .make_payment_and_refund(get_payment_authorize_data(), None, None) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } #[actix_web::test] async fn should_refund_manually_captured_payment() { let connector = Stripe {}; let response = connector .auth_capture_and_refund(get_payment_authorize_data(), 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 = Stripe {}; let refund_response = connector .make_payment_and_refund( get_payment_authorize_data(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let connector = Stripe {}; let response = connector .auth_capture_and_refund( get_payment_authorize_data(), 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 = Stripe {}; connector .make_payment_and_multiple_refund( get_payment_authorize_data(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await; } #[actix_web::test] async fn should_fail_refund_for_invalid_amount() { let connector = Stripe {}; let response = connector .make_payment_and_refund( get_payment_authorize_data(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().reason.unwrap(), "Refund amount ($1.50) is greater than charge amount ($1.00)", ); } #[actix_web::test] async fn should_sync_refund() { let connector = Stripe {}; let refund_response = connector .make_payment_and_refund(get_payment_authorize_data(), 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, ); } #[actix_web::test] async fn should_sync_manually_captured_refund() { let connector = Stripe {}; let refund_response = connector .auth_capture_and_refund(get_payment_authorize_data(), 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, ); } </file>
{ "crate": "router", "file": "crates/router/tests/connectors/stripe.rs", "files": null, "module": null, "num_files": null, "token_count": 2807 }
large_file_-1581548459812970871
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/shift4.rs </path> <file> 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, ); } </file>
{ "crate": "router", "file": "crates/router/tests/connectors/shift4.rs", "files": null, "module": null, "num_files": null, "token_count": 2845 }
large_file_-7647951628140390548
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/tsys.rs </path> <file> 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/tsys.rs", "files": null, "module": null, "num_files": null, "token_count": 3301 }
large_file_4237545919992214623
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/hyperwallet.rs </path> <file> 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/hyperwallet.rs", "files": null, "module": null, "num_files": null, "token_count": 2914 }
large_file_-8734190442894906389
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/checkout.rs </path> <file> 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/checkout.rs", "files": null, "module": null, "num_files": null, "token_count": 3004 }
large_file_2416301938101630371
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/billwerk.rs </path> <file> 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/billwerk.rs", "files": null, "module": null, "num_files": null, "token_count": 2930 }
large_file_-8127131585330903590
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/nmi.rs </path> <file> use std::{str::FromStr, time::Duration}; use router::types::{self, domain, storage::enums}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; struct NmiTest; impl ConnectorActions for NmiTest {} impl utils::Connector for NmiTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Nmi; utils::construct_connector_data_old( Box::new(Nmi::new()), types::Connector::Nmi, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .nmi .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "nmi".to_string() } } static CONNECTOR: NmiTest = NmiTest {}; fn get_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), ..utils::CCardType::default().0 }), amount: 2023, ..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(get_payment_authorize_data(), None) .await .expect("Authorize payment response"); let transaction_id = utils::get_connector_transaction_id(response.response).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); // Assert the sync response, it will be authorized in case of manual capture, for automatic it will be Completed Success assert_eq!(sync_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(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorizing); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); let capture_response = CONNECTOR .capture_payment(transaction_id.clone(), None, None) .await .unwrap(); assert_eq!( capture_response.status, enums::AttemptStatus::CaptureInitiated ); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); } // 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(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorizing); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); let capture_response = CONNECTOR .capture_payment( transaction_id.clone(), Some(types::PaymentsCaptureData { amount_to_capture: 1000, ..utils::PaymentCaptureType::default().0 }), None, ) .await .unwrap(); assert_eq!( capture_response.status, enums::AttemptStatus::CaptureInitiated ); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorizing); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); let void_response = CONNECTOR .void_payment( transaction_id.clone(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("user_cancel".to_string()), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(void_response.status, enums::AttemptStatus::VoidInitiated); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Voided, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_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 .authorize_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorizing); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); let capture_response = CONNECTOR .capture_payment(transaction_id.clone(), None, None) .await .unwrap(); assert_eq!( capture_response.status, enums::AttemptStatus::CaptureInitiated ); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); let refund_response = CONNECTOR .refund_payment(transaction_id.clone(), None, None) .await .unwrap(); assert_eq!(refund_response.status, enums::AttemptStatus::Pending); let sync_response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Pending, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( sync_response.response.unwrap().refund_status, enums::RefundStatus::Pending ); } // 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 .authorize_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorizing); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); let capture_response = CONNECTOR .capture_payment( transaction_id.clone(), Some(types::PaymentsCaptureData { amount_to_capture: 2023, ..utils::PaymentCaptureType::default().0 }), None, ) .await .unwrap(); assert_eq!( capture_response.status, enums::AttemptStatus::CaptureInitiated ); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); let refund_response = CONNECTOR .refund_payment( transaction_id.clone(), Some(types::RefundsData { refund_amount: 1023, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!(refund_response.status, enums::AttemptStatus::Pending); let sync_response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Pending, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( sync_response.response.unwrap().refund_status, enums::RefundStatus::Pending ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let response = CONNECTOR .make_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); } // 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(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); let refund_response = CONNECTOR .refund_payment(transaction_id.clone(), None, None) .await .unwrap(); assert_eq!(refund_response.status, enums::AttemptStatus::Pending); let sync_response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Pending, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( sync_response.response.unwrap().refund_status, enums::RefundStatus::Pending ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let response = CONNECTOR .make_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); let refund_response = CONNECTOR .refund_payment( transaction_id.clone(), Some(types::RefundsData { refund_amount: 1000, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!(refund_response.status, enums::AttemptStatus::Pending); let sync_response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Pending, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( sync_response.response.unwrap().refund_status, enums::RefundStatus::Pending ); } // 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 response = CONNECTOR .make_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); //try refund for previous payment let transaction_id = utils::get_connector_transaction_id(response.response).unwrap(); for _x in 0..2 { tokio::time::sleep(Duration::from_secs(5)).await; // to avoid 404 error let refund_response = CONNECTOR .refund_payment( transaction_id.clone(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); let sync_response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Pending, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( sync_response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } } // Creates a payment with incorrect CVC. #[ignore = "Connector returns SUCCESS status in case of invalid CVC"] #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() {} // Creates a payment with incorrect expiry month. #[ignore = "Connector returns SUCCESS status in case of expired month."] #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() {} // Creates a payment with incorrect expiry year. #[ignore = "Connector returns SUCCESS status in case of expired year."] #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() {} // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let response = CONNECTOR .make_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); let void_response = CONNECTOR .void_payment(transaction_id.clone(), None, None) .await .unwrap(); assert_eq!(void_response.status, enums::AttemptStatus::VoidFailed); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let response = CONNECTOR .authorize_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorizing); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); let capture_response = CONNECTOR .capture_payment("9123456789".to_string(), None, None) .await .unwrap(); assert_eq!(capture_response.status, enums::AttemptStatus::CaptureFailed); } // 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(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); let refund_response = CONNECTOR .refund_payment( transaction_id, Some(types::RefundsData { refund_amount: 3024, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Failure ); } </file>
{ "crate": "router", "file": "crates/router/tests/connectors/nmi.rs", "files": null, "module": null, "num_files": null, "token_count": 4874 }
large_file_7079637758352354401
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/ebanx.rs </path> <file> 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/ebanx.rs", "files": null, "module": null, "num_files": null, "token_count": 2933 }
large_file_6710056229976616321
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/aci.rs </path> <file> 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" ); } </file>
{ "crate": "router", "file": "crates/router/tests/connectors/aci.rs", "files": null, "module": null, "num_files": null, "token_count": 3869 }
large_file_-6228980417792450061
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/zen.rs </path> <file> 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("[email protected]").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("[email protected]").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("[email protected]").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("[email protected]").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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/zen.rs", "files": null, "module": null, "num_files": null, "token_count": 4233 }
large_file_-943085178761792187
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/elavon.rs </path> <file> 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/elavon.rs", "files": null, "module": null, "num_files": null, "token_count": 2986 }
large_file_-4582117092235984794
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/taxjar.rs </path> <file> 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/taxjar.rs", "files": null, "module": null, "num_files": null, "token_count": 2912 }
large_file_-7274849284306038152
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/authorizedotnet.rs </path> <file> 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/authorizedotnet.rs", "files": null, "module": null, "num_files": null, "token_count": 4212 }
large_file_-5007842245863755425
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/payeezy.rs </path> <file> 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"), ); } </file>
{ "crate": "router", "file": "crates/router/tests/connectors/payeezy.rs", "files": null, "module": null, "num_files": null, "token_count": 3878 }
large_file_-5248979432977555290
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/fiservemea.rs </path> <file> 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/fiservemea.rs", "files": null, "module": null, "num_files": null, "token_count": 2940 }
large_file_2145122407963248367
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/payload.rs </path> <file> 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/payload.rs", "files": null, "module": null, "num_files": null, "token_count": 2904 }
large_file_-7107509937981534016
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/mpgs.rs </path> <file> 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/mpgs.rs", "files": null, "module": null, "num_files": null, "token_count": 2920 }
large_file_682237048620331295
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/placetopay.rs </path> <file> 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/placetopay.rs", "files": null, "module": null, "num_files": null, "token_count": 2934 }
large_file_-3120479711276862134
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/utils.rs </path> <file> 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("[email protected]").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, } } </file>
{ "crate": "router", "file": "crates/router/tests/connectors/utils.rs", "files": null, "module": null, "num_files": null, "token_count": 9605 }
large_file_4847528251014139225
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/santander.rs </path> <file> 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/santander.rs", "files": null, "module": null, "num_files": null, "token_count": 2916 }
large_file_-4850338847632014996
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/tokenio.rs </path> <file> 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/tokenio.rs", "files": null, "module": null, "num_files": null, "token_count": 2913 }
large_file_-118633614644464232
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/vgs.rs </path> <file> 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/vgs.rs", "files": null, "module": null, "num_files": null, "token_count": 2912 }
large_file_9030791245816294946
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/bamboraapac.rs </path> <file> 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/bamboraapac.rs", "files": null, "module": null, "num_files": null, "token_count": 2933 }
large_file_1173417544872424675
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/moneris.rs </path> <file> 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/moneris.rs", "files": null, "module": null, "num_files": null, "token_count": 2923 }
large_file_-4965139493537720590
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/tests/connectors/nexixpay.rs </path> <file> 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 </file>
{ "crate": "router", "file": "crates/router/tests/connectors/nexixpay.rs", "files": null, "module": null, "num_files": null, "token_count": 2924 }
large_file_3503871558924691937
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/consts.rs </path> <file> pub mod opensearch; #[cfg(feature = "olap")] pub mod user; pub mod user_role; use std::{collections::HashSet, str::FromStr, sync}; use api_models::enums::Country; use common_utils::{consts, id_type}; pub use hyperswitch_domain_models::consts::{ CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH, ROUTING_ENABLED_PAYMENT_METHODS, ROUTING_ENABLED_PAYMENT_METHOD_TYPES, }; pub use hyperswitch_interfaces::consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}; // ID generation pub(crate) const ID_LENGTH: usize = 20; pub(crate) const MAX_ID_LENGTH: usize = 64; #[rustfmt::skip] pub(crate) const ALPHABETS: [char; 62] = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ]; /// API client request timeout (in seconds) pub const REQUEST_TIME_OUT: u64 = 30; pub const REQUEST_TIMEOUT_ERROR_CODE: &str = "TIMEOUT"; pub const REQUEST_TIMEOUT_ERROR_MESSAGE: &str = "Connector did not respond in specified time"; pub const REQUEST_TIMEOUT_PAYMENT_NOT_FOUND: &str = "Timed out ,payment not found"; pub const REQUEST_TIMEOUT_ERROR_MESSAGE_FROM_PSYNC: &str = "This Payment has been moved to failed as there is no response from the connector"; ///Payment intent fulfillment default timeout (in seconds) pub const DEFAULT_FULFILLMENT_TIME: i64 = 15 * 60; /// Payment intent default client secret expiry (in seconds) pub const DEFAULT_SESSION_EXPIRY: i64 = 15 * 60; /// The length of a merchant fingerprint secret pub const FINGERPRINT_SECRET_LENGTH: usize = 64; pub const DEFAULT_LIST_API_LIMIT: u16 = 10; // String literals pub(crate) const UNSUPPORTED_ERROR_MESSAGE: &str = "Unsupported response type"; // General purpose base64 engines pub(crate) const BASE64_ENGINE: base64::engine::GeneralPurpose = consts::BASE64_ENGINE; pub(crate) const API_KEY_LENGTH: usize = 64; // OID (Object Identifier) for the merchant ID field extension. pub(crate) const MERCHANT_ID_FIELD_EXTENSION_ID: &str = "1.2.840.113635.100.6.32"; pub const MAX_ROUTING_CONFIGS_PER_MERCHANT: usize = 100; pub const ROUTING_CONFIG_ID_LENGTH: usize = 10; pub const LOCKER_REDIS_PREFIX: &str = "LOCKER_PM_TOKEN"; pub const LOCKER_REDIS_EXPIRY_SECONDS: u32 = 60 * 15; // 15 minutes pub const JWT_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days // This should be one day, but it is causing issue while checking token in blacklist. // TODO: This should be fixed in future. pub const SINGLE_PURPOSE_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days pub const JWT_TOKEN_COOKIE_NAME: &str = "login_token"; pub const USER_BLACKLIST_PREFIX: &str = "BU_"; pub const ROLE_BLACKLIST_PREFIX: &str = "BR_"; #[cfg(feature = "email")] pub const EMAIL_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day #[cfg(feature = "email")] pub const EMAIL_TOKEN_BLACKLIST_PREFIX: &str = "BET_"; pub const EMAIL_SUBJECT_API_KEY_EXPIRY: &str = "API Key Expiry Notice"; pub const EMAIL_SUBJECT_DASHBOARD_FEATURE_REQUEST: &str = "Dashboard Pro Feature Request by"; pub const EMAIL_SUBJECT_APPROVAL_RECON_REQUEST: &str = "Approval of Recon Request - Access Granted to Recon Dashboard"; pub const ROLE_INFO_CACHE_PREFIX: &str = "CR_INFO_"; pub const CARD_IP_BLOCKING_CACHE_KEY_PREFIX: &str = "CARD_IP_BLOCKING"; pub const GUEST_USER_CARD_BLOCKING_CACHE_KEY_PREFIX: &str = "GUEST_USER_CARD_BLOCKING"; pub const CUSTOMER_ID_BLOCKING_PREFIX: &str = "CUSTOMER_ID_BLOCKING"; #[cfg(feature = "olap")] pub const VERIFY_CONNECTOR_ID_PREFIX: &str = "conn_verify"; #[cfg(feature = "olap")] pub const VERIFY_CONNECTOR_MERCHANT_ID: &str = "test_merchant"; #[cfg(feature = "olap")] pub const CONNECTOR_ONBOARDING_CONFIG_PREFIX: &str = "onboarding"; /// Max payment session expiry pub const MAX_SESSION_EXPIRY: u32 = 7890000; /// Min payment session expiry pub const MIN_SESSION_EXPIRY: u32 = 60; /// Max payment intent fulfillment expiry pub const MAX_INTENT_FULFILLMENT_EXPIRY: u32 = 1800; /// Min payment intent fulfillment expiry pub const MIN_INTENT_FULFILLMENT_EXPIRY: u32 = 60; pub const LOCKER_HEALTH_CALL_PATH: &str = "/health"; pub const AUTHENTICATION_ID_PREFIX: &str = "authn"; // URL for checking the outgoing call pub const OUTGOING_CALL_URL: &str = "https://api.stripe.com/healthcheck"; // 15 minutes = 900 seconds pub const POLL_ID_TTL: i64 = 900; // Default Poll Config pub const DEFAULT_POLL_DELAY_IN_SECS: i8 = 2; pub const DEFAULT_POLL_FREQUENCY: i8 = 5; // Number of seconds to subtract from access token expiry pub(crate) const REDUCE_ACCESS_TOKEN_EXPIRY_TIME: u8 = 15; pub const CONNECTOR_CREDS_TOKEN_TTL: i64 = 900; //max_amount allowed is 999999999 in minor units pub const MAX_ALLOWED_AMOUNT: i64 = 999999999; //payment attempt default unified error code and unified error message pub const DEFAULT_UNIFIED_ERROR_CODE: &str = "UE_9000"; pub const DEFAULT_UNIFIED_ERROR_MESSAGE: &str = "Something went wrong"; // Recon's feature tag pub const RECON_FEATURE_TAG: &str = "RECONCILIATION AND SETTLEMENT"; /// Default allowed domains for payment links pub const DEFAULT_ALLOWED_DOMAINS: Option<HashSet<String>> = None; /// Default hide card nickname field pub const DEFAULT_HIDE_CARD_NICKNAME_FIELD: bool = false; /// Show card form by default for payment links pub const DEFAULT_SHOW_CARD_FORM: bool = true; /// Default bool for Display sdk only pub const DEFAULT_DISPLAY_SDK_ONLY: bool = false; /// Default bool to enable saved payment method pub const DEFAULT_ENABLE_SAVED_PAYMENT_METHOD: bool = false; /// [PaymentLink] Default bool for enabling button only when form is ready pub const DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY: bool = false; /// Default Merchant Logo Link pub const DEFAULT_MERCHANT_LOGO: &str = "https://live.hyperswitch.io/payment-link-assets/Merchant_placeholder.png"; /// Default Payment Link Background color pub const DEFAULT_BACKGROUND_COLOR: &str = "#212E46"; /// Default product Img Link pub const DEFAULT_PRODUCT_IMG: &str = "https://live.hyperswitch.io/payment-link-assets/cart_placeholder.png"; /// Default SDK Layout pub const DEFAULT_SDK_LAYOUT: &str = "tabs"; /// Vault Add request url #[cfg(feature = "v2")] pub const ADD_VAULT_REQUEST_URL: &str = "/api/v2/vault/add"; /// Vault Get Fingerprint request url #[cfg(feature = "v2")] pub const VAULT_FINGERPRINT_REQUEST_URL: &str = "/api/v2/vault/fingerprint"; /// Vault Retrieve request url #[cfg(feature = "v2")] pub const VAULT_RETRIEVE_REQUEST_URL: &str = "/api/v2/vault/retrieve"; /// Vault Delete request url #[cfg(feature = "v2")] pub const VAULT_DELETE_REQUEST_URL: &str = "/api/v2/vault/delete"; /// Vault Header content type #[cfg(feature = "v2")] pub const VAULT_HEADER_CONTENT_TYPE: &str = "application/json"; /// Vault Add flow type #[cfg(feature = "v2")] pub const VAULT_ADD_FLOW_TYPE: &str = "add_to_vault"; /// Vault Retrieve flow type #[cfg(feature = "v2")] pub const VAULT_RETRIEVE_FLOW_TYPE: &str = "retrieve_from_vault"; /// Vault Delete flow type #[cfg(feature = "v2")] pub const VAULT_DELETE_FLOW_TYPE: &str = "delete_from_vault"; /// Vault Fingerprint fetch flow type #[cfg(feature = "v2")] pub const VAULT_GET_FINGERPRINT_FLOW_TYPE: &str = "get_fingerprint_vault"; /// Max volume split for Dynamic routing pub const DYNAMIC_ROUTING_MAX_VOLUME: u8 = 100; /// Click To Pay pub const CLICK_TO_PAY: &str = "click_to_pay"; /// Merchant eligible for authentication service config pub const AUTHENTICATION_SERVICE_ELIGIBLE_CONFIG: &str = "merchants_eligible_for_authentication_service"; /// Refund flow identifier used for performing GSM operations pub const REFUND_FLOW_STR: &str = "refund_flow"; /// Minimum IBAN length (country-dependent), as per ISO 13616 standard pub const IBAN_MIN_LENGTH: usize = 15; /// Maximum IBAN length defined by the ISO 13616 standard (standard max) pub const IBAN_MAX_LENGTH: usize = 34; /// Minimum UK BACS account number length in digits pub const BACS_MIN_ACCOUNT_NUMBER_LENGTH: usize = 6; /// Maximum UK BACS account number length in digits pub const BACS_MAX_ACCOUNT_NUMBER_LENGTH: usize = 8; /// Fixed length of UK BACS sort code in digits (always 6) pub const BACS_SORT_CODE_LENGTH: usize = 6; /// Exact length of Polish Elixir system domestic account number (NRB) in digits pub const ELIXIR_ACCOUNT_NUMBER_LENGTH: usize = 26; /// Total length of Polish IBAN including country code and checksum (28 characters) pub const ELIXIR_IBAN_LENGTH: usize = 28; /// Minimum length of Swedish Bankgiro number in digits pub const BANKGIRO_MIN_LENGTH: usize = 7; /// Maximum length of Swedish Bankgiro number in digits pub const BANKGIRO_MAX_LENGTH: usize = 8; /// Minimum length of Swedish Plusgiro number in digits pub const PLUSGIRO_MIN_LENGTH: usize = 2; /// Maximum length of Swedish Plusgiro number in digits pub const PLUSGIRO_MAX_LENGTH: usize = 8; /// Default payment method session expiry pub const DEFAULT_PAYMENT_METHOD_SESSION_EXPIRY: u32 = 15 * 60; // 15 minutes /// Authorize flow identifier used for performing GSM operations pub const AUTHORIZE_FLOW_STR: &str = "Authorize"; /// Protocol Version for encrypted Google Pay Token pub(crate) const PROTOCOL: &str = "ECv2"; /// Sender ID for Google Pay Decryption pub(crate) const SENDER_ID: &[u8] = b"Google"; /// Default value for the number of attempts to retry fetching forex rates pub const DEFAULT_ANALYTICS_FOREX_RETRY_ATTEMPTS: u64 = 3; /// Default payment intent id pub const IRRELEVANT_PAYMENT_INTENT_ID: &str = "irrelevant_payment_intent_id"; /// Default payment attempt id pub const IRRELEVANT_PAYMENT_ATTEMPT_ID: &str = "irrelevant_payment_attempt_id"; pub static PROFILE_ID_UNAVAILABLE: sync::LazyLock<id_type::ProfileId> = sync::LazyLock::new(|| { #[allow(clippy::expect_used)] id_type::ProfileId::from_str("PROFILE_ID_UNAVAIABLE") .expect("Failed to parse PROFILE_ID_UNAVAIABLE") }); /// Default payment attempt id pub const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID: &str = "irrelevant_connector_request_reference_id"; // Default payment method storing TTL in redis in seconds pub const DEFAULT_PAYMENT_METHOD_STORE_TTL: i64 = 86400; // 1 day // List of countries that are part of the PSD2 region pub const PSD2_COUNTRIES: [Country; 27] = [ Country::Austria, Country::Belgium, Country::Bulgaria, Country::Croatia, Country::Cyprus, Country::Czechia, Country::Denmark, Country::Estonia, Country::Finland, Country::France, Country::Germany, Country::Greece, Country::Hungary, Country::Ireland, Country::Italy, Country::Latvia, Country::Lithuania, Country::Luxembourg, Country::Malta, Country::Netherlands, Country::Poland, Country::Portugal, Country::Romania, Country::Slovakia, Country::Slovenia, Country::Spain, Country::Sweden, ]; // Rollout percentage config prefix pub const UCS_ROLLOUT_PERCENT_CONFIG_PREFIX: &str = "ucs_rollout_config"; // UCS feature enabled config pub const UCS_ENABLED: &str = "ucs_enabled"; /// Header value indicating that signature-key-based authentication is used. pub const UCS_AUTH_SIGNATURE_KEY: &str = "signature-key"; /// Header value indicating that body-key-based authentication is used. pub const UCS_AUTH_BODY_KEY: &str = "body-key"; /// Header value indicating that header-key-based authentication is used. pub const UCS_AUTH_HEADER_KEY: &str = "header-key"; /// Header value indicating that currency-auth-key-based authentication is used. pub const UCS_AUTH_CURRENCY_AUTH_KEY: &str = "currency-auth-key"; /// Form field name for challenge request during creq submission pub const CREQ_CHALLENGE_REQUEST_KEY: &str = "creq"; /// Superposition configuration keys pub mod superposition { /// CVV requirement configuration key pub const REQUIRES_CVV: &str = "requires_cvv"; } #[cfg(test)] mod tests { #![allow(clippy::expect_used)] #[test] fn test_profile_id_unavailable_initialization() { // Just access the lazy static to ensure it doesn't panic during initialization let _profile_id = super::PROFILE_ID_UNAVAILABLE.clone(); // If we get here without panicking, the test passes } } </file>
{ "crate": "router", "file": "crates/router/src/consts.rs", "files": null, "module": null, "num_files": null, "token_count": 3337 }
large_file_-568610301289139756
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/types.rs </path> <file> // 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 }) } } </file>
{ "crate": "router", "file": "crates/router/src/types.rs", "files": null, "module": null, "num_files": null, "token_count": 11880 }
large_file_895620588679390804
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/lib.rs </path> <file> #[cfg(all(feature = "stripe", feature = "v1"))] pub mod compatibility; pub mod configs; pub mod connection; pub mod connector; pub mod consts; pub mod core; pub mod cors; pub mod db; pub mod env; pub mod locale; pub(crate) mod macros; pub mod routes; pub mod workflows; #[cfg(feature = "olap")] pub mod analytics; pub mod analytics_validator; pub mod events; pub mod middleware; pub mod services; pub mod types; pub mod utils; use actix_web::{ body::MessageBody, dev::{Server, ServerHandle, ServiceFactory, ServiceRequest}, middleware::ErrorHandlers, }; use http::StatusCode; use hyperswitch_interfaces::secrets_interface::secret_state::SecuredSecret; use router_env::tracing::Instrument; use routes::{AppState, SessionState}; use storage_impl::errors::ApplicationResult; use tokio::sync::{mpsc, oneshot}; pub use self::env::logger; pub(crate) use self::macros::*; use crate::{configs::settings, core::errors}; #[cfg(feature = "mimalloc")] #[global_allocator] static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc; // Import translate fn in root use crate::locale::{_rust_i18n_t, _rust_i18n_try_translate}; /// Header Constants pub mod headers { pub const ACCEPT: &str = "Accept"; pub const ACCEPT_LANGUAGE: &str = "Accept-Language"; pub const KEY: &str = "key"; pub const API_KEY: &str = "API-KEY"; pub const APIKEY: &str = "apikey"; pub const X_CC_API_KEY: &str = "X-CC-Api-Key"; pub const API_TOKEN: &str = "Api-Token"; pub const AUTHORIZATION: &str = "Authorization"; pub const CONTENT_TYPE: &str = "Content-Type"; pub const DATE: &str = "Date"; pub const IDEMPOTENCY_KEY: &str = "Idempotency-Key"; pub const NONCE: &str = "nonce"; pub const TIMESTAMP: &str = "Timestamp"; pub const TOKEN: &str = "token"; pub const USER_AGENT: &str = "User-Agent"; pub const X_API_KEY: &str = "X-API-KEY"; pub const X_API_VERSION: &str = "X-ApiVersion"; pub const X_FORWARDED_FOR: &str = "X-Forwarded-For"; pub const X_MERCHANT_ID: &str = "X-Merchant-Id"; pub const X_INTERNAL_API_KEY: &str = "X-Internal-Api-Key"; pub const X_ORGANIZATION_ID: &str = "X-Organization-Id"; pub const X_LOGIN: &str = "X-Login"; pub const X_TRANS_KEY: &str = "X-Trans-Key"; pub const X_VERSION: &str = "X-Version"; pub const X_CC_VERSION: &str = "X-CC-Version"; pub const X_ACCEPT_VERSION: &str = "X-Accept-Version"; pub const X_DATE: &str = "X-Date"; pub const X_WEBHOOK_SIGNATURE: &str = "X-Webhook-Signature-512"; pub const X_REQUEST_ID: &str = "X-Request-Id"; pub const X_PROFILE_ID: &str = "X-Profile-Id"; pub const STRIPE_COMPATIBLE_WEBHOOK_SIGNATURE: &str = "Stripe-Signature"; pub const STRIPE_COMPATIBLE_CONNECT_ACCOUNT: &str = "Stripe-Account"; pub const X_CLIENT_VERSION: &str = "X-Client-Version"; pub const X_CLIENT_SOURCE: &str = "X-Client-Source"; pub const X_PAYMENT_CONFIRM_SOURCE: &str = "X-Payment-Confirm-Source"; pub const CONTENT_LENGTH: &str = "Content-Length"; pub const BROWSER_NAME: &str = "x-browser-name"; pub const X_CLIENT_PLATFORM: &str = "x-client-platform"; pub const X_MERCHANT_DOMAIN: &str = "x-merchant-domain"; pub const X_APP_ID: &str = "x-app-id"; pub const X_REDIRECT_URI: &str = "x-redirect-uri"; pub const X_TENANT_ID: &str = "x-tenant-id"; pub const X_CLIENT_SECRET: &str = "X-Client-Secret"; pub const X_CUSTOMER_ID: &str = "X-Customer-Id"; pub const X_CONNECTED_MERCHANT_ID: &str = "x-connected-merchant-id"; // Header value for X_CONNECTOR_HTTP_STATUS_CODE differs by version. // Constant name is kept the same for consistency across versions. #[cfg(feature = "v1")] pub const X_CONNECTOR_HTTP_STATUS_CODE: &str = "connector_http_status_code"; #[cfg(feature = "v2")] pub const X_CONNECTOR_HTTP_STATUS_CODE: &str = "x-connector-http-status-code"; pub const X_REFERENCE_ID: &str = "X-Reference-Id"; } pub mod pii { //! Personal Identifiable Information protection. pub(crate) use common_utils::pii::Email; #[doc(inline)] pub use masking::*; } pub fn mk_app( state: AppState, request_body_limit: usize, ) -> actix_web::App< impl ServiceFactory< ServiceRequest, Config = (), Response = actix_web::dev::ServiceResponse<impl MessageBody>, Error = actix_web::Error, InitError = (), >, > { let mut server_app = get_application_builder(request_body_limit, state.conf.cors.clone()); #[cfg(feature = "dummy_connector")] { use routes::DummyConnector; server_app = server_app.service(DummyConnector::server(state.clone())); } #[cfg(any(feature = "olap", feature = "oltp"))] { #[cfg(feature = "olap")] { // This is a more specific route as compared to `MerchantConnectorAccount` // so it is registered before `MerchantConnectorAccount`. #[cfg(feature = "v1")] { server_app = server_app .service(routes::ProfileNew::server(state.clone())) .service(routes::Forex::server(state.clone())) .service(routes::ProfileAcquirer::server(state.clone())); } server_app = server_app.service(routes::Profile::server(state.clone())); } server_app = server_app .service(routes::Payments::server(state.clone())) .service(routes::Customers::server(state.clone())) .service(routes::Configs::server(state.clone())) .service(routes::MerchantConnectorAccount::server(state.clone())) .service(routes::RelayWebhooks::server(state.clone())) .service(routes::Webhooks::server(state.clone())) .service(routes::Hypersense::server(state.clone())) .service(routes::Relay::server(state.clone())) .service(routes::ThreeDsDecisionRule::server(state.clone())); #[cfg(feature = "oltp")] { server_app = server_app.service(routes::PaymentMethods::server(state.clone())); } #[cfg(all(feature = "v2", feature = "oltp"))] { server_app = server_app .service(routes::PaymentMethodSession::server(state.clone())) .service(routes::Refunds::server(state.clone())); } #[cfg(all(feature = "v2", feature = "oltp", feature = "tokenization_v2"))] { server_app = server_app.service(routes::Tokenization::server(state.clone())); } #[cfg(feature = "v1")] { server_app = server_app .service(routes::Refunds::server(state.clone())) .service(routes::Mandates::server(state.clone())) .service(routes::Authentication::server(state.clone())); } } #[cfg(all(feature = "oltp", any(feature = "v1", feature = "v2"),))] { server_app = server_app.service(routes::EphemeralKey::server(state.clone())) } #[cfg(all(feature = "oltp", feature = "v1"))] { server_app = server_app.service(routes::Poll::server(state.clone())) } #[cfg(feature = "olap")] { server_app = server_app .service(routes::Organization::server(state.clone())) .service(routes::MerchantAccount::server(state.clone())) .service(routes::User::server(state.clone())) .service(routes::ApiKeys::server(state.clone())) .service(routes::Routing::server(state.clone())) .service(routes::Chat::server(state.clone())); #[cfg(all(feature = "olap", any(feature = "v1", feature = "v2")))] { server_app = server_app.service(routes::Verify::server(state.clone())); } #[cfg(feature = "v1")] { server_app = server_app .service(routes::Files::server(state.clone())) .service(routes::Disputes::server(state.clone())) .service(routes::Blocklist::server(state.clone())) .service(routes::Subscription::server(state.clone())) .service(routes::Gsm::server(state.clone())) .service(routes::ApplePayCertificatesMigration::server(state.clone())) .service(routes::PaymentLink::server(state.clone())) .service(routes::ConnectorOnboarding::server(state.clone())) .service(routes::Analytics::server(state.clone())) .service(routes::WebhookEvents::server(state.clone())) .service(routes::FeatureMatrix::server(state.clone())); } #[cfg(feature = "v2")] { server_app = server_app .service(routes::UserDeprecated::server(state.clone())) .service(routes::ProcessTrackerDeprecated::server(state.clone())) .service(routes::ProcessTracker::server(state.clone())) .service(routes::Gsm::server(state.clone())) .service(routes::RecoveryDataBackfill::server(state.clone())); } } #[cfg(all(feature = "payouts", feature = "v1"))] { server_app = server_app .service(routes::Payouts::server(state.clone())) .service(routes::PayoutLink::server(state.clone())); } #[cfg(all(feature = "stripe", feature = "v1"))] { server_app = server_app .service(routes::StripeApis::server(state.clone())) .service(routes::Cards::server(state.clone())); } #[cfg(all(feature = "oltp", feature = "v2"))] { server_app = server_app.service(routes::Proxy::server(state.clone())); } #[cfg(all(feature = "recon", feature = "v1"))] { server_app = server_app.service(routes::Recon::server(state.clone())); } server_app = server_app.service(routes::Cache::server(state.clone())); server_app = server_app.service(routes::Health::server(state.clone())); server_app } /// Starts the server /// /// # Panics /// /// Unwrap used because without the value we can't start the server #[allow(clippy::expect_used, clippy::unwrap_used)] pub async fn start_server(conf: settings::Settings<SecuredSecret>) -> ApplicationResult<Server> { logger::debug!(startup_config=?conf); let server = conf.server.clone(); let (tx, rx) = oneshot::channel(); let api_client = Box::new(services::ProxyClient::new(&conf.proxy).map_err(|error| { errors::ApplicationError::ApiClientError(error.current_context().clone()) })?); let state = Box::pin(AppState::new(conf, tx, api_client)).await; let request_body_limit = server.request_body_limit; let server_builder = actix_web::HttpServer::new(move || mk_app(state.clone(), request_body_limit)) .bind((server.host.as_str(), server.port))? .workers(server.workers) .shutdown_timeout(server.shutdown_timeout); #[cfg(feature = "tls")] let server = match server.tls { None => server_builder.run(), Some(tls_conf) => { let cert_file = &mut std::io::BufReader::new(std::fs::File::open(tls_conf.certificate).map_err( |err| errors::ApplicationError::InvalidConfigurationValueError(err.to_string()), )?); let key_file = &mut std::io::BufReader::new(std::fs::File::open(tls_conf.private_key).map_err( |err| errors::ApplicationError::InvalidConfigurationValueError(err.to_string()), )?); let cert_chain = rustls_pemfile::certs(cert_file) .collect::<Result<Vec<_>, _>>() .map_err(|err| { errors::ApplicationError::InvalidConfigurationValueError(err.to_string()) })?; let mut keys = rustls_pemfile::pkcs8_private_keys(key_file) .map(|key| key.map(rustls::pki_types::PrivateKeyDer::Pkcs8)) .collect::<Result<Vec<_>, _>>() .map_err(|err| { errors::ApplicationError::InvalidConfigurationValueError(err.to_string()) })?; // exit if no keys could be parsed if keys.is_empty() { return Err(errors::ApplicationError::InvalidConfigurationValueError( "Could not locate PKCS8 private keys.".into(), )); } let config_builder = rustls::ServerConfig::builder().with_no_client_auth(); let config = config_builder .with_single_cert(cert_chain, keys.remove(0)) .map_err(|err| { errors::ApplicationError::InvalidConfigurationValueError(err.to_string()) })?; server_builder .bind_rustls_0_22( (tls_conf.host.unwrap_or(server.host).as_str(), tls_conf.port), config, )? .run() } }; #[cfg(not(feature = "tls"))] let server = server_builder.run(); let _task_handle = tokio::spawn(receiver_for_error(rx, server.handle()).in_current_span()); Ok(server) } pub async fn receiver_for_error(rx: oneshot::Receiver<()>, mut server: impl Stop) { match rx.await { Ok(_) => { logger::error!("The redis server failed "); server.stop_server().await; } Err(err) => { logger::error!("Channel receiver error: {err}"); } } } #[async_trait::async_trait] pub trait Stop { async fn stop_server(&mut self); } #[async_trait::async_trait] impl Stop for ServerHandle { async fn stop_server(&mut self) { let _ = self.stop(true).await; } } #[async_trait::async_trait] impl Stop for mpsc::Sender<()> { async fn stop_server(&mut self) { let _ = self.send(()).await.map_err(|err| logger::error!("{err}")); } } pub fn get_application_builder( request_body_limit: usize, cors: settings::CorsSettings, ) -> actix_web::App< impl ServiceFactory< ServiceRequest, Config = (), Response = actix_web::dev::ServiceResponse<impl MessageBody>, Error = actix_web::Error, InitError = (), >, > { let json_cfg = actix_web::web::JsonConfig::default() .limit(request_body_limit) .content_type_required(true) .error_handler(utils::error_parser::custom_json_error_handler); actix_web::App::new() .app_data(json_cfg) .wrap(ErrorHandlers::new().handler( StatusCode::NOT_FOUND, errors::error_handlers::custom_error_handlers, )) .wrap(ErrorHandlers::new().handler( StatusCode::METHOD_NOT_ALLOWED, errors::error_handlers::custom_error_handlers, )) .wrap(middleware::default_response_headers()) .wrap(middleware::RequestId) .wrap(cors::cors(cors)) // this middleware works only for Http1.1 requests .wrap(middleware::Http400RequestDetailsLogger) .wrap(middleware::AddAcceptLanguageHeader) .wrap(middleware::RequestResponseMetrics) .wrap(middleware::LogSpanInitializer) .wrap(router_env::tracing_actix_web::TracingLogger::default()) } </file>
{ "crate": "router", "file": "crates/router/src/lib.rs", "files": null, "module": null, "num_files": null, "token_count": 3537 }
large_file_4951172994926190936
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/db.rs </path> <file> pub mod address; pub mod api_keys; pub mod authentication; pub mod authorization; pub mod blocklist; pub mod blocklist_fingerprint; pub mod blocklist_lookup; pub mod business_profile; pub mod callback_mapper; pub mod capture; pub mod configs; pub mod customers; pub mod dashboard_metadata; pub mod dispute; pub mod dynamic_routing_stats; pub mod ephemeral_key; pub mod events; pub mod file; pub mod fraud_check; pub mod generic_link; pub mod gsm; pub mod health_check; pub mod hyperswitch_ai_interaction; pub mod kafka_store; pub mod locker_mock_up; pub mod mandate; pub mod merchant_account; pub mod merchant_connector_account; pub mod merchant_key_store; pub mod organization; pub mod payment_link; pub mod payment_method_session; pub mod refund; pub mod relay; pub mod reverse_lookup; pub mod role; pub mod routing_algorithm; pub mod unified_translations; pub mod user; pub mod user_authentication_method; pub mod user_key_store; pub mod user_role; use ::payment_methods::state::PaymentMethodsStorageInterface; use common_utils::id_type; use diesel_models::{ fraud_check::{FraudCheck, FraudCheckUpdate}, organization::{Organization, OrganizationNew, OrganizationUpdate}, }; use error_stack::ResultExt; #[cfg(feature = "payouts")] use hyperswitch_domain_models::payouts::{ payout_attempt::PayoutAttemptInterface, payouts::PayoutsInterface, }; use hyperswitch_domain_models::{ cards_info::CardsInfoInterface, master_key::MasterKeyInterface, payment_methods::PaymentMethodInterface, payments::{payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface}, }; #[cfg(not(feature = "payouts"))] use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; use redis_interface::errors::RedisError; use router_env::logger; use storage_impl::{ errors::StorageError, redis::kv_store::RedisConnInterface, tokenization, MockDb, }; pub use self::kafka_store::KafkaStore; use self::{fraud_check::FraudCheckInterface, organization::OrganizationInterface}; pub use crate::{ core::errors::{self, ProcessTrackerError}, errors::CustomResult, services::{ kafka::{KafkaError, KafkaProducer, MQResult}, Store, }, types::{ domain, storage::{self}, AccessToken, }, }; #[derive(PartialEq, Eq)] pub enum StorageImpl { Postgresql, PostgresqlTest, Mock, } #[async_trait::async_trait] pub trait StorageInterface: Send + Sync + dyn_clone::DynClone + address::AddressInterface + api_keys::ApiKeyInterface + blocklist_lookup::BlocklistLookupInterface + configs::ConfigInterface<Error = StorageError> + capture::CaptureInterface + customers::CustomerInterface<Error = StorageError> + dashboard_metadata::DashboardMetadataInterface + dispute::DisputeInterface + ephemeral_key::EphemeralKeyInterface + ephemeral_key::ClientSecretInterface + events::EventInterface + file::FileMetadataInterface + FraudCheckInterface + locker_mock_up::LockerMockUpInterface + mandate::MandateInterface + merchant_account::MerchantAccountInterface<Error = StorageError> + merchant_connector_account::ConnectorAccessToken + merchant_connector_account::MerchantConnectorAccountInterface<Error = StorageError> + PaymentAttemptInterface<Error = StorageError> + PaymentIntentInterface<Error = StorageError> + PaymentMethodInterface<Error = StorageError> + blocklist::BlocklistInterface + blocklist_fingerprint::BlocklistFingerprintInterface + dynamic_routing_stats::DynamicRoutingStatsInterface + scheduler::SchedulerInterface + PayoutAttemptInterface<Error = StorageError> + PayoutsInterface<Error = StorageError> + refund::RefundInterface + reverse_lookup::ReverseLookupInterface + CardsInfoInterface<Error = StorageError> + merchant_key_store::MerchantKeyStoreInterface<Error = StorageError> + MasterKeyInterface + payment_link::PaymentLinkInterface + RedisConnInterface + RequestIdStore + business_profile::ProfileInterface<Error = StorageError> + routing_algorithm::RoutingAlgorithmInterface + gsm::GsmInterface + unified_translations::UnifiedTranslationsInterface + authorization::AuthorizationInterface + user::sample_data::BatchSampleDataInterface + health_check::HealthCheckDbInterface + user_authentication_method::UserAuthenticationMethodInterface + hyperswitch_ai_interaction::HyperswitchAiInteractionInterface + authentication::AuthenticationInterface + generic_link::GenericLinkInterface + relay::RelayInterface + user::theme::ThemeInterface + payment_method_session::PaymentMethodsSessionInterface + tokenization::TokenizationInterface + callback_mapper::CallbackMapperInterface + storage_impl::subscription::SubscriptionInterface<Error = StorageError> + storage_impl::invoice::InvoiceInterface<Error = StorageError> + 'static { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>; fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface>; fn get_subscription_store(&self) -> Box<dyn subscriptions::state::SubscriptionStorageInterface>; fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static>; } #[async_trait::async_trait] pub trait GlobalStorageInterface: Send + Sync + dyn_clone::DynClone + user::UserInterface + user_role::UserRoleInterface + user_key_store::UserKeyStoreInterface + role::RoleInterface + RedisConnInterface + 'static { fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static>; } #[async_trait::async_trait] pub trait AccountsStorageInterface: Send + Sync + dyn_clone::DynClone + OrganizationInterface + merchant_account::MerchantAccountInterface<Error = StorageError> + business_profile::ProfileInterface<Error = StorageError> + merchant_connector_account::MerchantConnectorAccountInterface<Error = StorageError> + merchant_key_store::MerchantKeyStoreInterface<Error = StorageError> + dashboard_metadata::DashboardMetadataInterface + 'static { } pub trait CommonStorageInterface: StorageInterface + GlobalStorageInterface + AccountsStorageInterface + PaymentMethodsStorageInterface { fn get_storage_interface(&self) -> Box<dyn StorageInterface>; fn get_global_storage_interface(&self) -> Box<dyn GlobalStorageInterface>; fn get_accounts_storage_interface(&self) -> Box<dyn AccountsStorageInterface>; } #[async_trait::async_trait] impl StorageInterface for Store { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface> { Box::new(self.clone()) } fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface> { Box::new(self.clone()) } fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> { Box::new(self.clone()) } fn get_subscription_store( &self, ) -> Box<dyn subscriptions::state::SubscriptionStorageInterface> { Box::new(self.clone()) } } #[async_trait::async_trait] impl GlobalStorageInterface for Store { fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> { Box::new(self.clone()) } } impl AccountsStorageInterface for Store {} #[async_trait::async_trait] impl StorageInterface for MockDb { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface> { Box::new(self.clone()) } fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface> { Box::new(self.clone()) } fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> { Box::new(self.clone()) } fn get_subscription_store( &self, ) -> Box<dyn subscriptions::state::SubscriptionStorageInterface> { Box::new(self.clone()) } } #[async_trait::async_trait] impl GlobalStorageInterface for MockDb { fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> { Box::new(self.clone()) } } impl AccountsStorageInterface for MockDb {} impl CommonStorageInterface for MockDb { fn get_global_storage_interface(&self) -> Box<dyn GlobalStorageInterface> { Box::new(self.clone()) } fn get_storage_interface(&self) -> Box<dyn StorageInterface> { Box::new(self.clone()) } fn get_accounts_storage_interface(&self) -> Box<dyn AccountsStorageInterface> { Box::new(self.clone()) } } impl CommonStorageInterface for Store { fn get_global_storage_interface(&self) -> Box<dyn GlobalStorageInterface> { Box::new(self.clone()) } fn get_storage_interface(&self) -> Box<dyn StorageInterface> { Box::new(self.clone()) } fn get_accounts_storage_interface(&self) -> Box<dyn AccountsStorageInterface> { Box::new(self.clone()) } } pub trait RequestIdStore { fn add_request_id(&mut self, _request_id: String) {} fn get_request_id(&self) -> Option<String> { None } } impl RequestIdStore for MockDb {} impl RequestIdStore for Store { fn add_request_id(&mut self, request_id: String) { self.request_id = Some(request_id) } fn get_request_id(&self) -> Option<String> { self.request_id.clone() } } pub async fn get_and_deserialize_key<T>( db: &dyn StorageInterface, key: &str, type_name: &'static str, ) -> CustomResult<T, RedisError> where T: serde::de::DeserializeOwned, { use common_utils::ext_traits::ByteSliceExt; let bytes = db.get_key(key).await?; bytes .parse_struct(type_name) .change_context(RedisError::JsonDeserializationFailed) } dyn_clone::clone_trait_object!(StorageInterface); dyn_clone::clone_trait_object!(GlobalStorageInterface); dyn_clone::clone_trait_object!(AccountsStorageInterface); impl RequestIdStore for KafkaStore { fn add_request_id(&mut self, request_id: String) { self.diesel_store.add_request_id(request_id) } } #[async_trait::async_trait] impl FraudCheckInterface for KafkaStore { async fn insert_fraud_check_response( &self, new: storage::FraudCheckNew, ) -> CustomResult<FraudCheck, StorageError> { let frm = self.diesel_store.insert_fraud_check_response(new).await?; if let Err(er) = self .kafka_producer .log_fraud_check(&frm, None, self.tenant_id.clone()) .await { logger::error!(message = "Failed to log analytics event for fraud check", error_message = ?er); } Ok(frm) } async fn update_fraud_check_response_with_attempt_id( &self, this: FraudCheck, fraud_check: FraudCheckUpdate, ) -> CustomResult<FraudCheck, StorageError> { let frm = self .diesel_store .update_fraud_check_response_with_attempt_id(this, fraud_check) .await?; if let Err(er) = self .kafka_producer .log_fraud_check(&frm, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for fraud check {frm:?}", error_message=?er) } Ok(frm) } async fn find_fraud_check_by_payment_id( &self, payment_id: id_type::PaymentId, merchant_id: id_type::MerchantId, ) -> CustomResult<FraudCheck, StorageError> { let frm = self .diesel_store .find_fraud_check_by_payment_id(payment_id, merchant_id) .await?; if let Err(er) = self .kafka_producer .log_fraud_check(&frm, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for fraud check {frm:?}", error_message=?er) } Ok(frm) } async fn find_fraud_check_by_payment_id_if_present( &self, payment_id: id_type::PaymentId, merchant_id: id_type::MerchantId, ) -> CustomResult<Option<FraudCheck>, StorageError> { let frm = self .diesel_store .find_fraud_check_by_payment_id_if_present(payment_id, merchant_id) .await?; if let Some(fraud_check) = frm.clone() { if let Err(er) = self .kafka_producer .log_fraud_check(&fraud_check, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for frm {frm:?}", error_message=?er); } } Ok(frm) } } #[async_trait::async_trait] impl OrganizationInterface for KafkaStore { async fn insert_organization( &self, organization: OrganizationNew, ) -> CustomResult<Organization, StorageError> { self.diesel_store.insert_organization(organization).await } async fn find_organization_by_org_id( &self, org_id: &id_type::OrganizationId, ) -> CustomResult<Organization, StorageError> { self.diesel_store.find_organization_by_org_id(org_id).await } async fn update_organization_by_org_id( &self, org_id: &id_type::OrganizationId, update: OrganizationUpdate, ) -> CustomResult<Organization, StorageError> { self.diesel_store .update_organization_by_org_id(org_id, update) .await } } </file>
{ "crate": "router", "file": "crates/router/src/db.rs", "files": null, "module": null, "num_files": null, "token_count": 3054 }
large_file_2907201790094902359
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/middleware.rs </path> <file> 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) }) } } </file>
{ "crate": "router", "file": "crates/router/src/middleware.rs", "files": null, "module": null, "num_files": null, "token_count": 4044 }
large_file_-8097468785422873186
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/utils.rs </path> <file> 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!() } </file>
{ "crate": "router", "file": "crates/router/src/utils.rs", "files": null, "module": null, "num_files": null, "token_count": 10574 }
large_file_8705514386007787813
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/compatibility/stripe/payment_intents.rs </path> <file> pub mod types; use actix_web::{web, HttpRequest, HttpResponse}; use api_models::payments as payment_types; #[cfg(feature = "v1")] use error_stack::report; #[cfg(feature = "v1")] use router_env::Tag; use router_env::{instrument, tracing, Flow}; use crate::{ compatibility::{stripe::errors, wrap}, core::payments, routes::{self}, services::{api, authentication as auth}, }; #[cfg(feature = "v1")] use crate::{ core::api_locking::GetLockingInput, logger, routes::payments::get_or_generate_payment_id, types::{api as api_types, domain}, }; #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCreate, payment_id))] pub async fn payment_intents_create( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, ) -> HttpResponse { let payload: types::StripePaymentIntentRequest = match qs_config .deserialize_bytes(&form_payload) .map_err(|err| report!(errors::StripeErrorCode::from(err))) { Ok(p) => p, Err(err) => return api::log_and_return_error_response(err), }; tracing::Span::current().record( "payment_id", payload .id .as_ref() .map(|payment_id| payment_id.get_string_repr()) .unwrap_or_default(), ); logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?payload); let mut create_payment_req: payment_types::PaymentsRequest = match payload.try_into() { Ok(req) => req, Err(err) => return api::log_and_return_error_response(err), }; if let Err(err) = get_or_generate_payment_id(&mut create_payment_req) { return api::log_and_return_error_response(err); } let flow = Flow::PaymentsCreate; let locking_action = create_payment_req.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, create_payment_req, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); let eligible_connectors = req.connector.clone(); payments::payments_core::< api_types::Authorize, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Authorize>, >( state, req_state, merchant_context, None, payments::PaymentCreate, req, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, eligible_connectors, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieveForceSync))] pub async fn payment_intents_retrieve( state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::PaymentId>, query_payload: web::Query<types::StripePaymentRetrieveBody>, ) -> HttpResponse { let payload = payment_types::PaymentsRetrieveRequest { resource_id: api_types::PaymentIdType::PaymentIntentId(path.into_inner()), merchant_id: None, force_sync: true, connector: None, param: None, merchant_connector_details: None, client_secret: query_payload.client_secret.clone(), expand_attempts: None, expand_captures: None, all_keys_required: None, }; let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }; let (auth_type, auth_flow) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; let flow = Flow::PaymentsRetrieveForceSync; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, payload, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::PSync, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::PSync>, >( state, req_state, merchant_context, None, payments::PaymentStatus, payload, auth_flow, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &*auth_type, locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow))] pub async fn payment_intents_retrieve_with_gateway_creds( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, ) -> HttpResponse { let json_payload: payment_types::PaymentRetrieveBodyWithCredentials = match qs_config .deserialize_bytes(&form_payload) .map_err(|err| report!(errors::StripeErrorCode::from(err))) { Ok(p) => p, Err(err) => return api::log_and_return_error_response(err), }; let payload = payment_types::PaymentsRetrieveRequest { resource_id: payment_types::PaymentIdType::PaymentIntentId(json_payload.payment_id), merchant_id: json_payload.merchant_id.clone(), force_sync: json_payload.force_sync.unwrap_or(false), merchant_connector_details: json_payload.merchant_connector_details.clone(), ..Default::default() }; let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }; let (auth_type, _auth_flow) = match auth::get_auth_type_and_flow(req.headers(), api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; let flow = match json_payload.force_sync { Some(true) => Flow::PaymentsRetrieveForceSync, _ => Flow::PaymentsRetrieve, }; tracing::Span::current().record("flow", flow.to_string()); let locking_action = payload.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::PSync, payment_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::PSync>, >( state, req_state, merchant_context, None, payments::PaymentStatus, req, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &*auth_type, locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdate))] pub async fn payment_intents_update( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, path: web::Path<common_utils::id_type::PaymentId>, ) -> HttpResponse { let payment_id = path.into_inner(); let stripe_payload: types::StripePaymentIntentRequest = match qs_config .deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; let mut payload: payment_types::PaymentsRequest = match stripe_payload.try_into() { Ok(req) => req, Err(err) => return api::log_and_return_error_response(err), }; payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(payment_id)); let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }; let (auth_type, auth_flow) = match auth::get_auth_type_and_flow(req.headers(), api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; let flow = Flow::PaymentsUpdate; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); let eligible_connectors = req.connector.clone(); payments::payments_core::< api_types::Authorize, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Authorize>, >( state, req_state, merchant_context, None, payments::PaymentUpdate, req, auth_flow, payments::CallConnectorAction::Trigger, eligible_connectors, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &*auth_type, locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsConfirm, payment_id))] pub async fn payment_intents_confirm( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, path: web::Path<common_utils::id_type::PaymentId>, ) -> HttpResponse { let payment_id = path.into_inner(); let stripe_payload: types::StripePaymentIntentRequest = match qs_config .deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; tracing::Span::current().record( "payment_id", stripe_payload.id.as_ref().map(|id| id.get_string_repr()), ); logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?stripe_payload); let mut payload: payment_types::PaymentsRequest = match stripe_payload.try_into() { Ok(req) => req, Err(err) => return api::log_and_return_error_response(err), }; payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(payment_id)); payload.confirm = Some(true); let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }; let (auth_type, auth_flow) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; let flow = Flow::PaymentsConfirm; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); let eligible_connectors = req.connector.clone(); payments::payments_core::< api_types::Authorize, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Authorize>, >( state, req_state, merchant_context, None, payments::PaymentConfirm, req, auth_flow, payments::CallConnectorAction::Trigger, eligible_connectors, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &*auth_type, locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCapture, payment_id))] pub async fn payment_intents_capture( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, path: web::Path<common_utils::id_type::PaymentId>, ) -> HttpResponse { let stripe_payload: payment_types::PaymentsCaptureRequest = match qs_config .deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; tracing::Span::current().record("payment_id", stripe_payload.payment_id.get_string_repr()); logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?stripe_payload); let payload = payment_types::PaymentsCaptureRequest { payment_id: path.into_inner(), ..stripe_payload }; let flow = Flow::PaymentsCapture; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth: auth::AuthenticationData, payload, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::Capture, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Capture>, >( state, req_state, merchant_context, None, payments::PaymentCapture, payload, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCancel, payment_id))] pub async fn payment_intents_cancel( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, path: web::Path<common_utils::id_type::PaymentId>, ) -> HttpResponse { let payment_id = path.into_inner(); let stripe_payload: types::StripePaymentCancelRequest = match qs_config .deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; tracing::Span::current().record("payment_id", payment_id.get_string_repr()); logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?stripe_payload); let mut payload: payment_types::PaymentsCancelRequest = stripe_payload.into(); payload.payment_id = payment_id; let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }; let (auth_type, auth_flow) = match auth::get_auth_type_and_flow(req.headers(), api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; let flow = Flow::PaymentsCancel; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::Void, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Void>, >( state, req_state, merchant_context, None, payments::PaymentCancel, req, auth_flow, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &*auth_type, locking_action, )) .await } #[instrument(skip_all, fields(flow = ?Flow::PaymentsList))] #[cfg(feature = "olap")] pub async fn payment_intent_list( state: web::Data<routes::AppState>, req: HttpRequest, payload: web::Query<types::StripePaymentListConstraints>, ) -> HttpResponse { let payload = match payment_types::PaymentListConstraints::try_from(payload.into_inner()) { Ok(p) => p, Err(err) => return api::log_and_return_error_response(err), }; use crate::core::api_locking; let flow = Flow::PaymentsList; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentListResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::list_payments(state, merchant_context, None, req) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } </file>
{ "crate": "router", "file": "crates/router/src/compatibility/stripe/payment_intents.rs", "files": null, "module": null, "num_files": null, "token_count": 4299 }
large_file_601770339860134712
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/compatibility/stripe/webhooks.rs </path> <file> #[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()), } } } </file>
{ "crate": "router", "file": "crates/router/src/compatibility/stripe/webhooks.rs", "files": null, "module": null, "num_files": null, "token_count": 2994 }
large_file_2320155707751558251
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/compatibility/stripe/errors.rs </path> <file> use common_utils::{errors::ErrorSwitch, id_type}; use hyperswitch_domain_models::errors::api_error_response as errors; use crate::core::errors::CustomersErrorResponse; #[derive(Debug, router_derive::ApiError, Clone)] #[error(error_type_enum = StripeErrorType)] pub enum StripeErrorCode { /* "error": { "message": "Invalid API Key provided: sk_jkjgs****nlgs", "type": "invalid_request_error" } */ #[error( error_type = StripeErrorType::InvalidRequestError, code = "IR_01", message = "Invalid API Key provided" )] Unauthorized, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_02", message = "Unrecognized request URL.")] InvalidRequestUrl, #[error(error_type = StripeErrorType::InvalidRequestError, code = "parameter_missing", message = "Missing required param: {field_name}.")] ParameterMissing { field_name: String, param: String }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "parameter_unknown", message = "{field_name} contains invalid data. Expected format is {expected_format}." )] ParameterUnknown { field_name: String, expected_format: String, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_06", message = "The refund amount exceeds the amount captured.")] RefundAmountExceedsPaymentAmount { param: String }, #[error(error_type = StripeErrorType::ApiError, code = "payment_intent_authentication_failure", message = "Payment failed while processing with connector. Retry payment.")] PaymentIntentAuthenticationFailure { data: Option<serde_json::Value> }, #[error(error_type = StripeErrorType::ApiError, code = "payment_intent_payment_attempt_failed", message = "Capture attempt failed while processing with connector.")] PaymentIntentPaymentAttemptFailed { data: Option<serde_json::Value> }, #[error(error_type = StripeErrorType::ApiError, code = "dispute_failure", message = "Dispute failed while processing with connector. Retry operation.")] DisputeFailed { data: Option<serde_json::Value> }, #[error(error_type = StripeErrorType::CardError, code = "expired_card", message = "Card Expired. Please use another card")] ExpiredCard, #[error(error_type = StripeErrorType::CardError, code = "invalid_card_type", message = "Card data is invalid")] InvalidCardType, #[error( error_type = StripeErrorType::ConnectorError, code = "invalid_wallet_token", message = "Invalid {wallet_name} wallet token" )] InvalidWalletToken { wallet_name: String }, #[error(error_type = StripeErrorType::ApiError, code = "refund_failed", message = "refund has failed")] RefundFailed, // stripe error code #[error(error_type = StripeErrorType::ApiError, code = "payout_failed", message = "payout has failed")] PayoutFailed, #[error(error_type = StripeErrorType::ApiError, code = "external_vault_failed", message = "external vault has failed")] ExternalVaultFailed, #[error(error_type = StripeErrorType::ApiError, code = "internal_server_error", message = "Server is down")] InternalServerError, #[error(error_type = StripeErrorType::ApiError, code = "internal_server_error", message = "Server is down")] DuplicateRefundRequest, #[error(error_type = StripeErrorType::InvalidRequestError, code = "active_mandate", message = "Customer has active mandate")] MandateActive, #[error(error_type = StripeErrorType::InvalidRequestError, code = "customer_redacted", message = "Customer has redacted")] CustomerRedacted, #[error(error_type = StripeErrorType::InvalidRequestError, code = "customer_already_exists", message = "Customer with the given customer_id already exists")] DuplicateCustomer, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such refund")] RefundNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "client_secret_invalid", message = "Expected client secret to be included in the request")] ClientSecretNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such customer")] CustomerNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such config")] ConfigNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "duplicate_resource", message = "Duplicate config")] DuplicateConfig, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payment")] PaymentNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payment method")] PaymentMethodNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "{message}")] GenericNotFoundError { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "duplicate_resource", message = "{message}")] GenericDuplicateError { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such merchant account")] MerchantAccountNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such resource ID")] ResourceIdNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "Merchant connector account does not exist in our records")] MerchantConnectorAccountNotFound { id: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "invalid_request", message = "The merchant connector account is disabled")] MerchantConnectorAccountDisabled, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such mandate")] MandateNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such API key")] ApiKeyNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payout")] PayoutNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such event")] EventNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "Duplicate payout request")] DuplicatePayout { payout_id: id_type::PayoutId }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "parameter_missing", message = "Return url is not available")] ReturnUrlUnavailable, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate merchant account")] DuplicateMerchantAccount, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_label}' already exists in our records")] DuplicateMerchantConnectorAccount { profile_id: String, connector_label: String, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate payment method")] DuplicatePaymentMethod, #[error(error_type = StripeErrorType::InvalidRequestError, code = "" , message = "deserialization failed: {error_message}")] SerdeQsError { error_message: String, param: Option<String>, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "payment_intent_invalid_parameter" , message = "The client_secret provided does not match the client_secret associated with the PaymentIntent.")] PaymentIntentInvalidParameter { param: String }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "IR_05", message = "{message}" )] InvalidRequestData { message: String }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "IR_10", message = "{message}" )] PreconditionFailed { message: String }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "", message = "The payment has not succeeded yet" )] PaymentFailed, #[error( error_type = StripeErrorType::InvalidRequestError, code = "", message = "The verification did not succeeded" )] VerificationFailed { data: Option<serde_json::Value> }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "", message = "Reached maximum refund attempts" )] MaximumRefundCount, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Duplicate mandate request. Mandate already attempted with the Mandate ID.")] DuplicateMandate, #[error(error_type= StripeErrorType::InvalidRequestError, code = "", message = "Successful payment not found for the given payment id")] SuccessfulPaymentNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Address does not exist in our records.")] AddressNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "This PaymentIntent could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}.")] PaymentIntentUnexpectedState { current_flow: String, field_name: String, current_value: String, states: String, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "The mandate information is invalid. {message}")] PaymentIntentMandateInvalid { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "The payment with the specified payment_id already exists in our records.")] DuplicatePayment { payment_id: id_type::PaymentId }, #[error(error_type = StripeErrorType::ConnectorError, code = "", message = "{code}: {message}")] ExternalConnectorError { code: String, message: String, connector: String, status_code: u16, }, #[error(error_type = StripeErrorType::CardError, code = "", message = "{code}: {message}")] PaymentBlockedError { code: u16, message: String, status: String, reason: String, }, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "The connector provided in the request is incorrect or not available")] IncorrectConnectorNameGiven, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "No such {object}: '{id}'")] ResourceMissing { object: String, id: String }, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File validation failed")] FileValidationFailed, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File not found in the request")] MissingFile, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File puropse not found in the request")] MissingFilePurpose, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File content type not found")] MissingFileContentType, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Dispute id not found in the request")] MissingDisputeId, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File does not exists in our records")] FileNotFound, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File not available")] FileNotAvailable, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Not Supported because provider is not Router")] FileProviderNotSupported, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "There was an issue with processing webhooks")] WebhookProcessingError, #[error(error_type = StripeErrorType::InvalidRequestError, code = "payment_method_unactivated", message = "The operation cannot be performed as the payment method used has not been activated. Activate the payment method in the Dashboard, then try again.")] PaymentMethodUnactivated, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "{message}")] HyperswitchUnprocessableEntity { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "{message}")] CurrencyNotSupported { message: String }, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Payment Link does not exist in our records")] PaymentLinkNotFound, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Resource Busy. Please try again later")] LockTimeout, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Merchant connector account is configured with invalid {config}")] InvalidConnectorConfiguration { config: String }, #[error(error_type = StripeErrorType::HyperswitchError, code = "HE_01", message = "Failed to convert currency to minor unit")] CurrencyConversionFailed, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")] PaymentMethodDeleteFailed, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Extended card info does not exist")] ExtendedCardInfoNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "not_configured", message = "{message}")] LinkConfigurationError { message: String }, #[error(error_type = StripeErrorType::ConnectorError, code = "CE", message = "{reason} as data mismatched for {field_names}")] IntegrityCheckFailed { reason: String, field_names: String, connector_transaction_id: Option<String>, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_28", message = "Invalid tenant")] InvalidTenant, #[error(error_type = StripeErrorType::HyperswitchError, code = "HE_01", message = "Failed to convert amount to {amount_type} type")] AmountConversionFailed { amount_type: &'static str }, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Platform Bad Request")] PlatformBadRequest, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Platform Unauthorized Request")] PlatformUnauthorizedRequest, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Profile Acquirer not found")] ProfileAcquirerNotFound, #[error(error_type = StripeErrorType::HyperswitchError, code = "Subscription Error", message = "Subscription operation: {operation} failed with connector")] SubscriptionError { operation: String }, // [#216]: https://github.com/juspay/hyperswitch/issues/216 // Implement the remaining stripe error codes /* AccountCountryInvalidAddress, AccountErrorCountryChangeRequiresAdditionalSteps, AccountInformationMismatch, AccountInvalid, AccountNumberInvalid, AcssDebitSessionIncomplete, AlipayUpgradeRequired, AmountTooLarge, AmountTooSmall, ApiKeyExpired, AuthenticationRequired, BalanceInsufficient, BankAccountBadRoutingNumbers, BankAccountDeclined, BankAccountExists, BankAccountUnusable, BankAccountUnverified, BankAccountVerificationFailed, BillingInvalidMandate, BitcoinUpgradeRequired, CardDeclineRateLimitExceeded, CardDeclined, CardholderPhoneNumberRequired, ChargeAlreadyCaptured, ChargeAlreadyRefunded, ChargeDisputed, ChargeExceedsSourceLimit, ChargeExpiredForCapture, ChargeInvalidParameter, ClearingCodeUnsupported, CountryCodeInvalid, CountryUnsupported, CouponExpired, CustomerMaxPaymentMethods, CustomerMaxSubscriptions, DebitNotAuthorized, EmailInvalid, ExpiredCard, IdempotencyKeyInUse, IncorrectAddress, IncorrectCvc, IncorrectNumber, IncorrectZip, InstantPayoutsConfigDisabled, InstantPayoutsCurrencyDisabled, InstantPayoutsLimitExceeded, InstantPayoutsUnsupported, InsufficientFunds, IntentInvalidState, IntentVerificationMethodMissing, InvalidCardType, InvalidCharacters, InvalidChargeAmount, InvalidCvc, InvalidExpiryMonth, InvalidExpiryYear, InvalidNumber, InvalidSourceUsage, InvoiceNoCustomerLineItems, InvoiceNoPaymentMethodTypes, InvoiceNoSubscriptionLineItems, InvoiceNotEditable, InvoiceOnBehalfOfNotEditable, InvoicePaymentIntentRequiresAction, InvoiceUpcomingNone, LivemodeMismatch, LockTimeout, Missing, NoAccount, NotAllowedOnStandardAccount, OutOfInventory, ParameterInvalidEmpty, ParameterInvalidInteger, ParameterInvalidStringBlank, ParameterInvalidStringEmpty, ParametersExclusive, PaymentIntentActionRequired, PaymentIntentIncompatiblePaymentMethod, PaymentIntentInvalidParameter, PaymentIntentKonbiniRejectedConfirmationNumber, PaymentIntentPaymentAttemptExpired, PaymentIntentUnexpectedState, PaymentMethodBankAccountAlreadyVerified, PaymentMethodBankAccountBlocked, PaymentMethodBillingDetailsAddressMissing, PaymentMethodCurrencyMismatch, PaymentMethodInvalidParameter, PaymentMethodInvalidParameterTestmode, PaymentMethodMicrodepositFailed, PaymentMethodMicrodepositVerificationAmountsInvalid, PaymentMethodMicrodepositVerificationAmountsMismatch, PaymentMethodMicrodepositVerificationAttemptsExceeded, PaymentMethodMicrodepositVerificationDescriptorCodeMismatch, PaymentMethodMicrodepositVerificationTimeout, PaymentMethodProviderDecline, PaymentMethodProviderTimeout, PaymentMethodUnexpectedState, PaymentMethodUnsupportedType, PayoutsNotAllowed, PlatformAccountRequired, PlatformApiKeyExpired, PostalCodeInvalid, ProcessingError, ProductInactive, RateLimit, ReferToCustomer, RefundDisputedPayment, ResourceAlreadyExists, ResourceMissing, ReturnIntentAlreadyProcessed, RoutingNumberInvalid, SecretKeyRequired, SepaUnsupportedAccount, SetupAttemptFailed, SetupIntentAuthenticationFailure, SetupIntentInvalidParameter, SetupIntentSetupAttemptExpired, SetupIntentUnexpectedState, ShippingCalculationFailed, SkuInactive, StateUnsupported, StatusTransitionInvalid, TaxIdInvalid, TaxesCalculationFailed, TerminalLocationCountryUnsupported, TestmodeChargesOnly, TlsVersionUnsupported, TokenInUse, TransferSourceBalanceParametersMismatch, TransfersNotAllowed, */ } impl ::core::fmt::Display for StripeErrorCode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{{\"error\": {}}}", serde_json::to_string(self).unwrap_or_else(|_| "API error response".to_string()) ) } } #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] #[allow(clippy::enum_variant_names)] pub enum StripeErrorType { ApiError, CardError, InvalidRequestError, ConnectorError, HyperswitchError, } impl From<errors::ApiErrorResponse> for StripeErrorCode { fn from(value: errors::ApiErrorResponse) -> Self { match value { errors::ApiErrorResponse::Unauthorized | errors::ApiErrorResponse::InvalidJwtToken | errors::ApiErrorResponse::GenericUnauthorized { .. } | errors::ApiErrorResponse::AccessForbidden { .. } | errors::ApiErrorResponse::InvalidCookie | errors::ApiErrorResponse::InvalidEphemeralKey | errors::ApiErrorResponse::CookieNotFound => Self::Unauthorized, errors::ApiErrorResponse::InvalidRequestUrl | errors::ApiErrorResponse::InvalidHttpMethod | errors::ApiErrorResponse::InvalidCardIin | errors::ApiErrorResponse::InvalidCardIinLength => Self::InvalidRequestUrl, errors::ApiErrorResponse::MissingRequiredField { field_name } => { Self::ParameterMissing { field_name: field_name.to_string(), param: field_name.to_string(), } } errors::ApiErrorResponse::UnprocessableEntity { message } => { Self::HyperswitchUnprocessableEntity { message } } errors::ApiErrorResponse::MissingRequiredFields { field_names } => { // Instead of creating a new error variant in StripeErrorCode for MissingRequiredFields, converted vec<&str> to String Self::ParameterMissing { field_name: field_names.clone().join(", "), param: field_names.clone().join(", "), } } errors::ApiErrorResponse::GenericNotFoundError { message } => { Self::GenericNotFoundError { message } } errors::ApiErrorResponse::GenericDuplicateError { message } => { Self::GenericDuplicateError { message } } // parameter unknown, invalid request error // actually if we type wrong values in address we get this error. Stripe throws parameter unknown. I don't know if stripe is validating email and stuff errors::ApiErrorResponse::InvalidDataFormat { field_name, expected_format, } => Self::ParameterUnknown { field_name, expected_format, }, errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount => { Self::RefundAmountExceedsPaymentAmount { param: "amount".to_owned(), } } errors::ApiErrorResponse::PaymentAuthorizationFailed { data } | errors::ApiErrorResponse::PaymentAuthenticationFailed { data } => { Self::PaymentIntentAuthenticationFailure { data } } errors::ApiErrorResponse::VerificationFailed { data } => { Self::VerificationFailed { data } } errors::ApiErrorResponse::PaymentCaptureFailed { data } => { Self::PaymentIntentPaymentAttemptFailed { data } } errors::ApiErrorResponse::DisputeFailed { data } => Self::DisputeFailed { data }, errors::ApiErrorResponse::InvalidCardData { data: _ } => Self::InvalidCardType, // Maybe it is better to de generalize this router error errors::ApiErrorResponse::CardExpired { data: _ } => Self::ExpiredCard, errors::ApiErrorResponse::RefundNotPossible { connector: _ } => Self::RefundFailed, errors::ApiErrorResponse::RefundFailed { data: _ } => Self::RefundFailed, // Nothing at stripe to map errors::ApiErrorResponse::PayoutFailed { data: _ } => Self::PayoutFailed, errors::ApiErrorResponse::ExternalVaultFailed => Self::ExternalVaultFailed, errors::ApiErrorResponse::MandateUpdateFailed | errors::ApiErrorResponse::MandateSerializationFailed | errors::ApiErrorResponse::MandateDeserializationFailed | errors::ApiErrorResponse::InternalServerError | errors::ApiErrorResponse::HealthCheckError { .. } => Self::InternalServerError, // not a stripe code errors::ApiErrorResponse::ExternalConnectorError { code, message, connector, status_code, .. } => Self::ExternalConnectorError { code, message, connector, status_code, }, errors::ApiErrorResponse::IncorrectConnectorNameGiven => { Self::IncorrectConnectorNameGiven } errors::ApiErrorResponse::MandateActive => Self::MandateActive, //not a stripe code errors::ApiErrorResponse::CustomerRedacted => Self::CustomerRedacted, //not a stripe code errors::ApiErrorResponse::ConfigNotFound => Self::ConfigNotFound, // not a stripe code errors::ApiErrorResponse::DuplicateConfig => Self::DuplicateConfig, // not a stripe code errors::ApiErrorResponse::DuplicateRefundRequest => Self::DuplicateRefundRequest, errors::ApiErrorResponse::DuplicatePayout { payout_id } => { Self::DuplicatePayout { payout_id } } errors::ApiErrorResponse::RefundNotFound => Self::RefundNotFound, errors::ApiErrorResponse::CustomerNotFound => Self::CustomerNotFound, errors::ApiErrorResponse::PaymentNotFound => Self::PaymentNotFound, errors::ApiErrorResponse::PaymentMethodNotFound => Self::PaymentMethodNotFound, errors::ApiErrorResponse::ClientSecretNotGiven | errors::ApiErrorResponse::ClientSecretExpired => Self::ClientSecretNotFound, errors::ApiErrorResponse::MerchantAccountNotFound => Self::MerchantAccountNotFound, errors::ApiErrorResponse::PaymentLinkNotFound => Self::PaymentLinkNotFound, errors::ApiErrorResponse::ResourceIdNotFound => Self::ResourceIdNotFound, errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id } => { Self::MerchantConnectorAccountNotFound { id } } errors::ApiErrorResponse::MandateNotFound => Self::MandateNotFound, errors::ApiErrorResponse::ApiKeyNotFound => Self::ApiKeyNotFound, errors::ApiErrorResponse::PayoutNotFound => Self::PayoutNotFound, errors::ApiErrorResponse::EventNotFound => Self::EventNotFound, errors::ApiErrorResponse::MandateValidationFailed { reason } => { Self::PaymentIntentMandateInvalid { message: reason } } errors::ApiErrorResponse::ReturnUrlUnavailable => Self::ReturnUrlUnavailable, errors::ApiErrorResponse::DuplicateMerchantAccount => Self::DuplicateMerchantAccount, errors::ApiErrorResponse::DuplicateMerchantConnectorAccount { profile_id, connector_label, } => Self::DuplicateMerchantConnectorAccount { profile_id, connector_label, }, errors::ApiErrorResponse::DuplicatePaymentMethod => Self::DuplicatePaymentMethod, errors::ApiErrorResponse::PaymentBlockedError { code, message, status, reason, } => Self::PaymentBlockedError { code, message, status, reason, }, errors::ApiErrorResponse::ClientSecretInvalid => Self::PaymentIntentInvalidParameter { param: "client_secret".to_owned(), }, errors::ApiErrorResponse::InvalidRequestData { message } => { Self::InvalidRequestData { message } } errors::ApiErrorResponse::PreconditionFailed { message } => { Self::PreconditionFailed { message } } errors::ApiErrorResponse::InvalidDataValue { field_name } => Self::ParameterMissing { field_name: field_name.to_string(), param: field_name.to_string(), }, errors::ApiErrorResponse::MaximumRefundCount => Self::MaximumRefundCount, errors::ApiErrorResponse::PaymentNotSucceeded => Self::PaymentFailed, errors::ApiErrorResponse::DuplicateMandate => Self::DuplicateMandate, errors::ApiErrorResponse::SuccessfulPaymentNotFound => Self::SuccessfulPaymentNotFound, errors::ApiErrorResponse::AddressNotFound => Self::AddressNotFound, errors::ApiErrorResponse::NotImplemented { .. } => Self::Unauthorized, errors::ApiErrorResponse::FlowNotSupported { .. } => Self::InternalServerError, errors::ApiErrorResponse::MandatePaymentDataMismatch { .. } => Self::PlatformBadRequest, errors::ApiErrorResponse::MaxFieldLengthViolated { .. } => Self::PlatformBadRequest, errors::ApiErrorResponse::PaymentUnexpectedState { current_flow, field_name, current_value, states, } => Self::PaymentIntentUnexpectedState { current_flow, field_name, current_value, states, }, errors::ApiErrorResponse::DuplicatePayment { payment_id } => { Self::DuplicatePayment { payment_id } } errors::ApiErrorResponse::DisputeNotFound { dispute_id } => Self::ResourceMissing { object: "dispute".to_owned(), id: dispute_id, }, errors::ApiErrorResponse::AuthenticationNotFound { id } => Self::ResourceMissing { object: "authentication".to_owned(), id, }, errors::ApiErrorResponse::ProfileNotFound { id } => Self::ResourceMissing { object: "business_profile".to_owned(), id, }, errors::ApiErrorResponse::PollNotFound { id } => Self::ResourceMissing { object: "poll".to_owned(), id, }, errors::ApiErrorResponse::DisputeStatusValidationFailed { reason: _ } => { Self::InternalServerError } errors::ApiErrorResponse::FileValidationFailed { .. } => Self::FileValidationFailed, errors::ApiErrorResponse::MissingFile => Self::MissingFile, errors::ApiErrorResponse::MissingFilePurpose => Self::MissingFilePurpose, errors::ApiErrorResponse::MissingFileContentType => Self::MissingFileContentType, errors::ApiErrorResponse::MissingDisputeId => Self::MissingDisputeId, errors::ApiErrorResponse::FileNotFound => Self::FileNotFound, errors::ApiErrorResponse::FileNotAvailable => Self::FileNotAvailable, errors::ApiErrorResponse::MerchantConnectorAccountDisabled => { Self::MerchantConnectorAccountDisabled } errors::ApiErrorResponse::NotSupported { .. } => Self::InternalServerError, errors::ApiErrorResponse::CurrencyNotSupported { message } => { Self::CurrencyNotSupported { message } } errors::ApiErrorResponse::FileProviderNotSupported { .. } => { Self::FileProviderNotSupported } errors::ApiErrorResponse::WebhookBadRequest | errors::ApiErrorResponse::WebhookResourceNotFound | errors::ApiErrorResponse::WebhookProcessingFailure | errors::ApiErrorResponse::WebhookAuthenticationFailed | errors::ApiErrorResponse::WebhookUnprocessableEntity | errors::ApiErrorResponse::WebhookInvalidMerchantSecret => { Self::WebhookProcessingError } errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration => { Self::PaymentMethodUnactivated } errors::ApiErrorResponse::ResourceBusy => Self::PaymentMethodUnactivated, errors::ApiErrorResponse::InvalidConnectorConfiguration { config } => { Self::InvalidConnectorConfiguration { config } } errors::ApiErrorResponse::CurrencyConversionFailed => Self::CurrencyConversionFailed, errors::ApiErrorResponse::PaymentMethodDeleteFailed => Self::PaymentMethodDeleteFailed, errors::ApiErrorResponse::InvalidWalletToken { wallet_name } => { Self::InvalidWalletToken { wallet_name } } errors::ApiErrorResponse::ExtendedCardInfoNotFound => Self::ExtendedCardInfoNotFound, errors::ApiErrorResponse::LinkConfigurationError { message } => { Self::LinkConfigurationError { message } } errors::ApiErrorResponse::IntegrityCheckFailed { reason, field_names, connector_transaction_id, } => Self::IntegrityCheckFailed { reason, field_names, connector_transaction_id, }, errors::ApiErrorResponse::InvalidTenant { tenant_id: _ } | errors::ApiErrorResponse::MissingTenantId => Self::InvalidTenant, errors::ApiErrorResponse::AmountConversionFailed { amount_type } => { Self::AmountConversionFailed { amount_type } } errors::ApiErrorResponse::PlatformAccountAuthNotSupported => Self::PlatformBadRequest, errors::ApiErrorResponse::InvalidPlatformOperation => Self::PlatformUnauthorizedRequest, errors::ApiErrorResponse::ProfileAcquirerNotFound { .. } => { Self::ProfileAcquirerNotFound } errors::ApiErrorResponse::TokenizationRecordNotFound { id } => Self::ResourceMissing { object: "tokenization record".to_owned(), id, }, errors::ApiErrorResponse::SubscriptionError { operation } => { Self::SubscriptionError { operation } } } } } impl actix_web::ResponseError for StripeErrorCode { fn status_code(&self) -> reqwest::StatusCode { use reqwest::StatusCode; match self { Self::Unauthorized | Self::PlatformUnauthorizedRequest => StatusCode::UNAUTHORIZED, Self::InvalidRequestUrl | Self::GenericNotFoundError { .. } => StatusCode::NOT_FOUND, Self::ParameterUnknown { .. } | Self::HyperswitchUnprocessableEntity { .. } => { StatusCode::UNPROCESSABLE_ENTITY } Self::ParameterMissing { .. } | Self::RefundAmountExceedsPaymentAmount { .. } | Self::PaymentIntentAuthenticationFailure { .. } | Self::PaymentIntentPaymentAttemptFailed { .. } | Self::ExpiredCard | Self::InvalidCardType | Self::DuplicateRefundRequest | Self::DuplicatePayout { .. } | Self::RefundNotFound | Self::CustomerNotFound | Self::ConfigNotFound | Self::DuplicateConfig | Self::ClientSecretNotFound | Self::PaymentNotFound | Self::PaymentMethodNotFound | Self::MerchantAccountNotFound | Self::MerchantConnectorAccountNotFound { .. } | Self::MerchantConnectorAccountDisabled | Self::MandateNotFound | Self::ApiKeyNotFound | Self::PayoutNotFound | Self::EventNotFound | Self::DuplicateMerchantAccount | Self::DuplicateMerchantConnectorAccount { .. } | Self::DuplicatePaymentMethod | Self::PaymentFailed | Self::VerificationFailed { .. } | Self::DisputeFailed { .. } | Self::MaximumRefundCount | Self::PaymentIntentInvalidParameter { .. } | Self::SerdeQsError { .. } | Self::InvalidRequestData { .. } | Self::InvalidWalletToken { .. } | Self::PreconditionFailed { .. } | Self::DuplicateMandate | Self::SuccessfulPaymentNotFound | Self::AddressNotFound | Self::ResourceIdNotFound | Self::PaymentIntentMandateInvalid { .. } | Self::PaymentIntentUnexpectedState { .. } | Self::DuplicatePayment { .. } | Self::GenericDuplicateError { .. } | Self::IncorrectConnectorNameGiven | Self::ResourceMissing { .. } | Self::FileValidationFailed | Self::MissingFile | Self::MissingFileContentType | Self::MissingFilePurpose | Self::MissingDisputeId | Self::FileNotFound | Self::FileNotAvailable | Self::FileProviderNotSupported | Self::CurrencyNotSupported { .. } | Self::DuplicateCustomer | Self::PaymentMethodUnactivated | Self::InvalidConnectorConfiguration { .. } | Self::CurrencyConversionFailed | Self::PaymentMethodDeleteFailed | Self::ExtendedCardInfoNotFound | Self::PlatformBadRequest | Self::LinkConfigurationError { .. } => StatusCode::BAD_REQUEST, Self::RefundFailed | Self::PayoutFailed | Self::PaymentLinkNotFound | Self::InternalServerError | Self::MandateActive | Self::CustomerRedacted | Self::WebhookProcessingError | Self::InvalidTenant | Self::ExternalVaultFailed | Self::AmountConversionFailed { .. } | Self::SubscriptionError { .. } => StatusCode::INTERNAL_SERVER_ERROR, Self::ReturnUrlUnavailable => StatusCode::SERVICE_UNAVAILABLE, Self::ExternalConnectorError { status_code, .. } => { StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR) } Self::IntegrityCheckFailed { .. } => StatusCode::INTERNAL_SERVER_ERROR, Self::PaymentBlockedError { code, .. } => { StatusCode::from_u16(*code).unwrap_or(StatusCode::OK) } Self::LockTimeout => StatusCode::LOCKED, Self::ProfileAcquirerNotFound => StatusCode::NOT_FOUND, } } fn error_response(&self) -> actix_web::HttpResponse { use actix_web::http::header; actix_web::HttpResponseBuilder::new(self.status_code()) .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)) .body(self.to_string()) } } impl From<serde_qs::Error> for StripeErrorCode { fn from(item: serde_qs::Error) -> Self { match item { serde_qs::Error::Custom(s) => Self::SerdeQsError { error_message: s, param: None, }, serde_qs::Error::Parse(param, position) => Self::SerdeQsError { error_message: format!( "parsing failed with error: '{param}' at position: {position}" ), param: Some(param), }, serde_qs::Error::Unsupported => Self::SerdeQsError { error_message: "Given request format is not supported".to_owned(), param: None, }, serde_qs::Error::FromUtf8(_) => Self::SerdeQsError { error_message: "Failed to parse request to from utf-8".to_owned(), param: None, }, serde_qs::Error::Io(_) => Self::SerdeQsError { error_message: "Failed to parse request".to_owned(), param: None, }, serde_qs::Error::ParseInt(_) => Self::SerdeQsError { error_message: "Failed to parse integer in request".to_owned(), param: None, }, serde_qs::Error::Utf8(_) => Self::SerdeQsError { error_message: "Failed to convert utf8 to string".to_owned(), param: None, }, } } } impl ErrorSwitch<StripeErrorCode> for errors::ApiErrorResponse { fn switch(&self) -> StripeErrorCode { self.clone().into() } } impl crate::services::EmbedError for error_stack::Report<StripeErrorCode> {} impl ErrorSwitch<StripeErrorCode> for CustomersErrorResponse { fn switch(&self) -> StripeErrorCode { use StripeErrorCode as SC; match self { Self::CustomerRedacted => SC::CustomerRedacted, Self::InternalServerError => SC::InternalServerError, Self::InvalidRequestData { message } => SC::InvalidRequestData { message: message.clone(), }, Self::MandateActive => SC::MandateActive, Self::CustomerNotFound => SC::CustomerNotFound, Self::CustomerAlreadyExists => SC::DuplicateCustomer, } } } </file>
{ "crate": "router", "file": "crates/router/src/compatibility/stripe/errors.rs", "files": null, "module": null, "num_files": null, "token_count": 8305 }
large_file_-3021453667205671751
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/compatibility/stripe/setup_intents.rs </path> <file> pub mod types; #[cfg(feature = "v1")] use actix_web::{web, HttpRequest, HttpResponse}; #[cfg(feature = "v1")] use api_models::payments as payment_types; #[cfg(feature = "v1")] use error_stack::report; #[cfg(feature = "v1")] use router_env::{instrument, tracing, Flow}; #[cfg(feature = "v1")] use crate::{ compatibility::{ stripe::{errors, payment_intents::types as stripe_payment_types}, wrap, }, core::{api_locking, payments}, routes, services::{api, authentication as auth}, types::{api as api_types, domain}, }; #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCreate))] pub async fn setup_intents_create( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, ) -> HttpResponse { let payload: types::StripeSetupIntentRequest = match qs_config.deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; let create_payment_req: payment_types::PaymentsRequest = match payment_types::PaymentsRequest::try_from(payload) { Ok(req) => req, Err(err) => return api::log_and_return_error_response(err), }; let flow = Flow::PaymentsCreate; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripeSetupIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, create_payment_req, |state, auth: auth::AuthenticationData, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::SetupMandate, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::SetupMandate>, >( state, req_state, merchant_context, None, payments::PaymentCreate, req, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieveForceSync))] pub async fn setup_intents_retrieve( state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::PaymentId>, query_payload: web::Query<stripe_payment_types::StripePaymentRetrieveBody>, ) -> HttpResponse { let payload = payment_types::PaymentsRetrieveRequest { resource_id: api_types::PaymentIdType::PaymentIntentId(path.into_inner()), merchant_id: None, force_sync: true, connector: None, param: None, merchant_connector_details: None, client_secret: query_payload.client_secret.clone(), expand_attempts: None, expand_captures: None, all_keys_required: None, }; let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }; let (auth_type, auth_flow) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; let flow = Flow::PaymentsRetrieveForceSync; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripeSetupIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, payload, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::PSync, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::PSync>, >( state, req_state, merchant_context, None, payments::PaymentStatus, payload, auth_flow, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &*auth_type, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdate))] pub async fn setup_intents_update( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, path: web::Path<common_utils::id_type::PaymentId>, ) -> HttpResponse { let setup_id = path.into_inner(); let stripe_payload: types::StripeSetupIntentRequest = match qs_config .deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; let mut payload: payment_types::PaymentsRequest = match payment_types::PaymentsRequest::try_from(stripe_payload) { Ok(req) => req, Err(err) => return api::log_and_return_error_response(err), }; payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(setup_id)); let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }; let (auth_type, auth_flow) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; let flow = Flow::PaymentsUpdate; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripeSetupIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::SetupMandate, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::SetupMandate>, >( state, req_state, merchant_context, None, payments::PaymentUpdate, req, auth_flow, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &*auth_type, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsConfirm))] pub async fn setup_intents_confirm( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, path: web::Path<common_utils::id_type::PaymentId>, ) -> HttpResponse { let setup_id = path.into_inner(); let stripe_payload: types::StripeSetupIntentRequest = match qs_config .deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; let mut payload: payment_types::PaymentsRequest = match payment_types::PaymentsRequest::try_from(stripe_payload) { Ok(req) => req, Err(err) => return api::log_and_return_error_response(err), }; payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(setup_id)); payload.confirm = Some(true); let api_auth = auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }; let (auth_type, auth_flow) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; let flow = Flow::PaymentsConfirm; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripeSetupIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, req, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payments::payments_core::< api_types::SetupMandate, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::SetupMandate>, >( state, req_state, merchant_context, None, payments::PaymentConfirm, req, auth_flow, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), ) }, &*auth_type, api_locking::LockAction::NotApplicable, )) .await } </file>
{ "crate": "router", "file": "crates/router/src/compatibility/stripe/setup_intents.rs", "files": null, "module": null, "num_files": null, "token_count": 2208 }
large_file_-4599581718418989109
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/compatibility/stripe/payment_intents/types.rs </path> <file> 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, } } </file>
{ "crate": "router", "file": "crates/router/src/compatibility/stripe/payment_intents/types.rs", "files": null, "module": null, "num_files": null, "token_count": 7820 }
large_file_-8575247248809157492
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/compatibility/stripe/setup_intents/types.rs </path> <file> 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) } } </file>
{ "crate": "router", "file": "crates/router/src/compatibility/stripe/setup_intents/types.rs", "files": null, "module": null, "num_files": null, "token_count": 4751 }
large_file_8775481779298278810
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/types/payment_methods.rs </path> <file> 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, } </file>
{ "crate": "router", "file": "crates/router/src/types/payment_methods.rs", "files": null, "module": null, "num_files": null, "token_count": 2588 }
large_file_-4964326109489996641
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/types/connector_transformers.rs </path> <file> use api_models::enums as api_enums; use super::ForeignTryFrom; impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { type Error = error_stack::Report<common_utils::errors::ValidationError>; fn foreign_try_from(from: api_enums::Connector) -> Result<Self, Self::Error> { Ok(match from { api_enums::Connector::Aci => Self::Aci, api_enums::Connector::Adyen => Self::Adyen, api_enums::Connector::Affirm => Self::Affirm, api_enums::Connector::Adyenplatform => Self::Adyenplatform, api_enums::Connector::Airwallex => Self::Airwallex, api_enums::Connector::Amazonpay => Self::Amazonpay, api_enums::Connector::Archipel => Self::Archipel, api_enums::Connector::Authipay => Self::Authipay, api_enums::Connector::Authorizedotnet => Self::Authorizedotnet, api_enums::Connector::Bambora => Self::Bambora, api_enums::Connector::Bamboraapac => Self::Bamboraapac, api_enums::Connector::Bankofamerica => Self::Bankofamerica, api_enums::Connector::Barclaycard => Self::Barclaycard, api_enums::Connector::Billwerk => Self::Billwerk, api_enums::Connector::Bitpay => Self::Bitpay, api_enums::Connector::Bluesnap => Self::Bluesnap, api_enums::Connector::Blackhawknetwork => Self::Blackhawknetwork, api_enums::Connector::Calida => Self::Calida, api_enums::Connector::Boku => Self::Boku, api_enums::Connector::Braintree => Self::Braintree, api_enums::Connector::Breadpay => Self::Breadpay, api_enums::Connector::Cardinal => { Err(common_utils::errors::ValidationError::InvalidValue { message: "cardinal is not a routable connector".to_string(), })? } api_enums::Connector::Cashtocode => Self::Cashtocode, api_enums::Connector::Celero => Self::Celero, api_enums::Connector::Chargebee => Self::Chargebee, api_enums::Connector::Checkbook => Self::Checkbook, api_enums::Connector::Checkout => Self::Checkout, api_enums::Connector::Coinbase => Self::Coinbase, api_enums::Connector::Coingate => Self::Coingate, api_enums::Connector::Cryptopay => Self::Cryptopay, api_enums::Connector::Custombilling => Self::Custombilling, api_enums::Connector::CtpVisa => { Err(common_utils::errors::ValidationError::InvalidValue { message: "ctp visa is not a routable connector".to_string(), })? } api_enums::Connector::CtpMastercard => { Err(common_utils::errors::ValidationError::InvalidValue { message: "ctp mastercard is not a routable connector".to_string(), })? } api_enums::Connector::Cybersource => Self::Cybersource, api_enums::Connector::Datatrans => Self::Datatrans, api_enums::Connector::Deutschebank => Self::Deutschebank, api_enums::Connector::Digitalvirgo => Self::Digitalvirgo, api_enums::Connector::Dlocal => Self::Dlocal, api_enums::Connector::Dwolla => Self::Dwolla, api_enums::Connector::Ebanx => Self::Ebanx, api_enums::Connector::Elavon => Self::Elavon, api_enums::Connector::Facilitapay => Self::Facilitapay, api_enums::Connector::Finix => Self::Finix, api_enums::Connector::Fiserv => Self::Fiserv, api_enums::Connector::Fiservemea => Self::Fiservemea, api_enums::Connector::Fiuu => Self::Fiuu, api_enums::Connector::Flexiti => Self::Flexiti, api_enums::Connector::Forte => Self::Forte, api_enums::Connector::Getnet => Self::Getnet, api_enums::Connector::Gigadat => Self::Gigadat, api_enums::Connector::Globalpay => Self::Globalpay, api_enums::Connector::Globepay => Self::Globepay, api_enums::Connector::Gocardless => Self::Gocardless, api_enums::Connector::Gpayments => { Err(common_utils::errors::ValidationError::InvalidValue { message: "gpayments is not a routable connector".to_string(), })? } api_enums::Connector::Hipay => Self::Hipay, api_enums::Connector::Helcim => Self::Helcim, api_enums::Connector::HyperswitchVault => { Err(common_utils::errors::ValidationError::InvalidValue { message: "Hyperswitch Vault is not a routable connector".to_string(), })? } api_enums::Connector::Iatapay => Self::Iatapay, api_enums::Connector::Inespay => Self::Inespay, api_enums::Connector::Itaubank => Self::Itaubank, api_enums::Connector::Jpmorgan => Self::Jpmorgan, api_enums::Connector::Juspaythreedsserver => { Err(common_utils::errors::ValidationError::InvalidValue { message: "juspaythreedsserver is not a routable connector".to_string(), })? } api_enums::Connector::Klarna => Self::Klarna, api_enums::Connector::Loonio => Self::Loonio, api_enums::Connector::Mifinity => Self::Mifinity, api_enums::Connector::Mollie => Self::Mollie, api_enums::Connector::Moneris => Self::Moneris, api_enums::Connector::Multisafepay => Self::Multisafepay, api_enums::Connector::Netcetera => { Err(common_utils::errors::ValidationError::InvalidValue { message: "netcetera is not a routable connector".to_string(), })? } api_enums::Connector::Nexinets => Self::Nexinets, api_enums::Connector::Nexixpay => Self::Nexixpay, api_enums::Connector::Nmi => Self::Nmi, api_enums::Connector::Nomupay => Self::Nomupay, api_enums::Connector::Noon => Self::Noon, api_enums::Connector::Nordea => Self::Nordea, api_enums::Connector::Novalnet => Self::Novalnet, api_enums::Connector::Nuvei => Self::Nuvei, api_enums::Connector::Opennode => Self::Opennode, api_enums::Connector::Paybox => Self::Paybox, api_enums::Connector::Payload => Self::Payload, api_enums::Connector::Payme => Self::Payme, api_enums::Connector::Payone => Self::Payone, api_enums::Connector::Paypal => Self::Paypal, api_enums::Connector::Paysafe => Self::Paysafe, api_enums::Connector::Paystack => Self::Paystack, api_enums::Connector::Payu => Self::Payu, api_enums::Connector::Peachpayments => Self::Peachpayments, api_models::enums::Connector::Placetopay => Self::Placetopay, api_enums::Connector::Plaid => Self::Plaid, api_enums::Connector::Powertranz => Self::Powertranz, api_enums::Connector::Prophetpay => Self::Prophetpay, api_enums::Connector::Rapyd => Self::Rapyd, api_enums::Connector::Razorpay => Self::Razorpay, api_enums::Connector::Recurly => Self::Recurly, api_enums::Connector::Redsys => Self::Redsys, api_enums::Connector::Santander => Self::Santander, api_enums::Connector::Shift4 => Self::Shift4, api_enums::Connector::Silverflow => Self::Silverflow, api_enums::Connector::Signifyd => { Err(common_utils::errors::ValidationError::InvalidValue { message: "signifyd is not a routable connector".to_string(), })? } api_enums::Connector::Riskified => { Err(common_utils::errors::ValidationError::InvalidValue { message: "riskified is not a routable connector".to_string(), })? } api_enums::Connector::Square => Self::Square, api_enums::Connector::Stax => Self::Stax, api_enums::Connector::Stripe => Self::Stripe, api_enums::Connector::Stripebilling => Self::Stripebilling, // api_enums::Connector::Thunes => Self::Thunes, api_enums::Connector::Tesouro => Self::Tesouro, api_enums::Connector::Tokenex => { Err(common_utils::errors::ValidationError::InvalidValue { message: "Tokenex is not a routable connector".to_string(), })? } api_enums::Connector::Tokenio => Self::Tokenio, api_enums::Connector::Trustpay => Self::Trustpay, api_enums::Connector::Trustpayments => Self::Trustpayments, api_enums::Connector::Tsys => Self::Tsys, // api_enums::Connector::UnifiedAuthenticationService => { // Self::UnifiedAuthenticationService // } api_enums::Connector::Vgs => { Err(common_utils::errors::ValidationError::InvalidValue { message: "Vgs is not a routable connector".to_string(), })? } api_enums::Connector::Volt => Self::Volt, api_enums::Connector::Wellsfargo => Self::Wellsfargo, // api_enums::Connector::Wellsfargopayout => Self::Wellsfargopayout, api_enums::Connector::Wise => Self::Wise, api_enums::Connector::Worldline => Self::Worldline, api_enums::Connector::Worldpay => Self::Worldpay, api_enums::Connector::Worldpayvantiv => Self::Worldpayvantiv, api_enums::Connector::Worldpayxml => Self::Worldpayxml, api_enums::Connector::Xendit => Self::Xendit, api_enums::Connector::Zen => Self::Zen, api_enums::Connector::Zsl => Self::Zsl, #[cfg(feature = "dummy_connector")] api_enums::Connector::DummyBillingConnector => { Err(common_utils::errors::ValidationError::InvalidValue { message: "stripe_billing_test is not a routable connector".to_string(), })? } #[cfg(feature = "dummy_connector")] api_enums::Connector::DummyConnector1 => Self::DummyConnector1, #[cfg(feature = "dummy_connector")] api_enums::Connector::DummyConnector2 => Self::DummyConnector2, #[cfg(feature = "dummy_connector")] api_enums::Connector::DummyConnector3 => Self::DummyConnector3, #[cfg(feature = "dummy_connector")] api_enums::Connector::DummyConnector4 => Self::DummyConnector4, #[cfg(feature = "dummy_connector")] api_enums::Connector::DummyConnector5 => Self::DummyConnector5, #[cfg(feature = "dummy_connector")] api_enums::Connector::DummyConnector6 => Self::DummyConnector6, #[cfg(feature = "dummy_connector")] api_enums::Connector::DummyConnector7 => Self::DummyConnector7, api_enums::Connector::Threedsecureio => { Err(common_utils::errors::ValidationError::InvalidValue { message: "threedsecureio is not a routable connector".to_string(), })? } api_enums::Connector::Taxjar => { Err(common_utils::errors::ValidationError::InvalidValue { message: "Taxjar is not a routable connector".to_string(), })? } api_enums::Connector::Phonepe => Self::Phonepe, api_enums::Connector::Paytm => Self::Paytm, }) } } </file>
{ "crate": "router", "file": "crates/router/src/types/connector_transformers.rs", "files": null, "module": null, "num_files": null, "token_count": 2809 }
large_file_-8655937265857621588
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/types/api.rs </path> <file> 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()))) } } } } </file>
{ "crate": "router", "file": "crates/router/src/types/api.rs", "files": null, "module": null, "num_files": null, "token_count": 2204 }
large_file_217500831929413500
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/types/storage/payment_attempt.rs </path> <file> use common_utils::types::MinorUnit; use diesel_models::{capture::CaptureNew, enums}; use error_stack::ResultExt; pub use hyperswitch_domain_models::payments::payment_attempt::{ PaymentAttempt, PaymentAttemptUpdate, }; use crate::{ core::errors, errors::RouterResult, types::transformers::ForeignFrom, utils::OptionExt, }; pub trait PaymentAttemptExt { fn make_new_capture( &self, capture_amount: MinorUnit, capture_status: enums::CaptureStatus, ) -> RouterResult<CaptureNew>; fn get_next_capture_id(&self) -> String; fn get_total_amount(&self) -> MinorUnit; fn get_surcharge_details(&self) -> Option<api_models::payments::RequestSurchargeDetails>; } impl PaymentAttemptExt for PaymentAttempt { #[cfg(feature = "v2")] fn make_new_capture( &self, capture_amount: MinorUnit, capture_status: enums::CaptureStatus, ) -> RouterResult<CaptureNew> { todo!() } #[cfg(feature = "v1")] fn make_new_capture( &self, capture_amount: MinorUnit, capture_status: enums::CaptureStatus, ) -> RouterResult<CaptureNew> { let capture_sequence = self.multiple_capture_count.unwrap_or_default() + 1; let now = common_utils::date_time::now(); Ok(CaptureNew { payment_id: self.payment_id.clone(), merchant_id: self.merchant_id.clone(), capture_id: self.get_next_capture_id(), status: capture_status, amount: capture_amount, currency: self.currency, connector: self .connector .clone() .get_required_value("connector") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "connector field is required in payment_attempt to create a capture", )?, error_message: None, tax_amount: None, created_at: now, modified_at: now, error_code: None, error_reason: None, authorized_attempt_id: self.attempt_id.clone(), capture_sequence, connector_capture_id: None, connector_response_reference_id: None, processor_capture_data: None, // Below fields are deprecated. Please add any new fields above this line. connector_capture_data: None, }) } #[cfg(feature = "v1")] fn get_next_capture_id(&self) -> String { let next_sequence_number = self.multiple_capture_count.unwrap_or_default() + 1; format!("{}_{}", self.attempt_id.clone(), next_sequence_number) } #[cfg(feature = "v2")] fn get_next_capture_id(&self) -> String { todo!() } #[cfg(feature = "v1")] fn get_surcharge_details(&self) -> Option<api_models::payments::RequestSurchargeDetails> { self.net_amount .get_surcharge_amount() .map( |surcharge_amount| api_models::payments::RequestSurchargeDetails { surcharge_amount, tax_amount: self.net_amount.get_tax_on_surcharge(), }, ) } #[cfg(feature = "v2")] fn get_surcharge_details(&self) -> Option<api_models::payments::RequestSurchargeDetails> { todo!() } #[cfg(feature = "v1")] fn get_total_amount(&self) -> MinorUnit { self.net_amount.get_total_amount() } #[cfg(feature = "v2")] fn get_total_amount(&self) -> MinorUnit { todo!() } } pub trait AttemptStatusExt { fn maps_to_intent_status(self, intent_status: enums::IntentStatus) -> bool; } impl AttemptStatusExt for enums::AttemptStatus { fn maps_to_intent_status(self, intent_status: enums::IntentStatus) -> bool { enums::IntentStatus::foreign_from(self) == intent_status } } #[cfg(test)] #[cfg(all( feature = "v1", // Ignoring tests for v2 since they aren't actively running feature = "dummy_connector" ))] mod tests { #![allow(clippy::expect_used, clippy::unwrap_used, clippy::print_stderr)] use hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptNew; use tokio::sync::oneshot; use uuid::Uuid; use crate::{ configs::settings::Settings, db::StorageImpl, routes, services, types::{self, storage::enums}, }; async fn create_single_connection_test_transaction_pool() -> routes::AppState { // Set pool size to 1 and minimum idle connection size to 0 std::env::set_var("ROUTER__MASTER_DATABASE__POOL_SIZE", "1"); std::env::set_var("ROUTER__MASTER_DATABASE__MIN_IDLE", "0"); std::env::set_var("ROUTER__REPLICA_DATABASE__POOL_SIZE", "1"); std::env::set_var("ROUTER__REPLICA_DATABASE__MIN_IDLE", "0"); let conf = Settings::new().expect("invalid settings"); let tx: oneshot::Sender<()> = oneshot::channel().0; let api_client = Box::new(services::MockApiClient); Box::pin(routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, tx, api_client, )) .await } #[tokio::test] async fn test_payment_attempt_insert() { let state = create_single_connection_test_transaction_pool().await; let payment_id = common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data(); let current_time = common_utils::date_time::now(); let connector = types::Connector::DummyConnector1.to_string(); let payment_attempt = PaymentAttemptNew { payment_id: payment_id.clone(), connector: Some(connector), created_at: current_time.into(), modified_at: current_time.into(), merchant_id: Default::default(), attempt_id: Default::default(), status: Default::default(), net_amount: Default::default(), currency: Default::default(), save_to_locker: Default::default(), error_message: Default::default(), offer_amount: Default::default(), payment_method_id: Default::default(), payment_method: Default::default(), capture_method: Default::default(), capture_on: Default::default(), confirm: Default::default(), authentication_type: Default::default(), last_synced: Default::default(), cancellation_reason: Default::default(), amount_to_capture: Default::default(), mandate_id: Default::default(), browser_info: Default::default(), payment_token: Default::default(), error_code: Default::default(), connector_metadata: Default::default(), payment_experience: Default::default(), payment_method_type: Default::default(), payment_method_data: Default::default(), business_sub_label: Default::default(), straight_through_algorithm: Default::default(), preprocessing_step_id: Default::default(), mandate_details: Default::default(), error_reason: Default::default(), connector_response_reference_id: Default::default(), multiple_capture_count: Default::default(), amount_capturable: Default::default(), updated_by: Default::default(), authentication_data: Default::default(), encoded_data: Default::default(), merchant_connector_id: Default::default(), unified_code: Default::default(), unified_message: Default::default(), external_three_ds_authentication_attempted: Default::default(), authentication_connector: Default::default(), authentication_id: Default::default(), mandate_data: Default::default(), payment_method_billing_address_id: Default::default(), fingerprint_id: Default::default(), client_source: Default::default(), client_version: Default::default(), customer_acceptance: Default::default(), profile_id: common_utils::generate_profile_id_of_default_length(), organization_id: Default::default(), connector_mandate_detail: Default::default(), request_extended_authorization: Default::default(), extended_authorization_applied: Default::default(), capture_before: Default::default(), card_discovery: Default::default(), processor_merchant_id: Default::default(), created_by: None, setup_future_usage_applied: Default::default(), routing_approach: Default::default(), connector_request_reference_id: Default::default(), network_transaction_id: Default::default(), network_details: Default::default(), is_stored_credential: None, authorized_amount: Default::default(), }; let store = state .stores .get(state.conf.multitenancy.get_tenant_ids().first().unwrap()) .unwrap(); let response = store .insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly) .await .unwrap(); eprintln!("{response:?}"); assert_eq!(response.payment_id, payment_id.clone()); } #[tokio::test] /// Example of unit test /// Kind of test: state-based testing async fn test_find_payment_attempt() { let state = create_single_connection_test_transaction_pool().await; let current_time = common_utils::date_time::now(); let payment_id = common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data(); let attempt_id = Uuid::new_v4().to_string(); let merchant_id = common_utils::id_type::MerchantId::new_from_unix_timestamp(); let connector = types::Connector::DummyConnector1.to_string(); let payment_attempt = PaymentAttemptNew { payment_id: payment_id.clone(), merchant_id: merchant_id.clone(), connector: Some(connector), created_at: current_time.into(), modified_at: current_time.into(), attempt_id: attempt_id.clone(), status: Default::default(), net_amount: Default::default(), currency: Default::default(), save_to_locker: Default::default(), error_message: Default::default(), offer_amount: Default::default(), payment_method_id: Default::default(), payment_method: Default::default(), capture_method: Default::default(), capture_on: Default::default(), confirm: Default::default(), authentication_type: Default::default(), last_synced: Default::default(), cancellation_reason: Default::default(), amount_to_capture: Default::default(), mandate_id: Default::default(), browser_info: Default::default(), payment_token: Default::default(), error_code: Default::default(), connector_metadata: Default::default(), payment_experience: Default::default(), payment_method_type: Default::default(), payment_method_data: Default::default(), business_sub_label: Default::default(), straight_through_algorithm: Default::default(), preprocessing_step_id: Default::default(), mandate_details: Default::default(), error_reason: Default::default(), connector_response_reference_id: Default::default(), multiple_capture_count: Default::default(), amount_capturable: Default::default(), updated_by: Default::default(), authentication_data: Default::default(), encoded_data: Default::default(), merchant_connector_id: Default::default(), unified_code: Default::default(), unified_message: Default::default(), external_three_ds_authentication_attempted: Default::default(), authentication_connector: Default::default(), authentication_id: Default::default(), mandate_data: Default::default(), payment_method_billing_address_id: Default::default(), fingerprint_id: Default::default(), client_source: Default::default(), client_version: Default::default(), customer_acceptance: Default::default(), profile_id: common_utils::generate_profile_id_of_default_length(), organization_id: Default::default(), connector_mandate_detail: Default::default(), request_extended_authorization: Default::default(), extended_authorization_applied: Default::default(), capture_before: Default::default(), card_discovery: Default::default(), processor_merchant_id: Default::default(), created_by: None, setup_future_usage_applied: Default::default(), routing_approach: Default::default(), connector_request_reference_id: Default::default(), network_transaction_id: Default::default(), network_details: Default::default(), is_stored_credential: Default::default(), authorized_amount: Default::default(), }; let store = state .stores .get(state.conf.multitenancy.get_tenant_ids().first().unwrap()) .unwrap(); store .insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly) .await .unwrap(); let response = store .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_id, &merchant_id, &attempt_id, enums::MerchantStorageScheme::PostgresOnly, ) .await .unwrap(); eprintln!("{response:?}"); assert_eq!(response.payment_id, payment_id); } #[tokio::test] /// Example of unit test /// Kind of test: state-based testing async fn test_payment_attempt_mandate_field() { let state = create_single_connection_test_transaction_pool().await; let uuid = Uuid::new_v4().to_string(); let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("merchant1")) .unwrap(); let payment_id = common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data(); let current_time = common_utils::date_time::now(); let connector = types::Connector::DummyConnector1.to_string(); let payment_attempt = PaymentAttemptNew { payment_id: payment_id.clone(), merchant_id: merchant_id.clone(), connector: Some(connector), created_at: current_time.into(), modified_at: current_time.into(), mandate_id: Some("man_121212".to_string()), attempt_id: uuid.clone(), status: Default::default(), net_amount: Default::default(), currency: Default::default(), save_to_locker: Default::default(), error_message: Default::default(), offer_amount: Default::default(), payment_method_id: Default::default(), payment_method: Default::default(), capture_method: Default::default(), capture_on: Default::default(), confirm: Default::default(), authentication_type: Default::default(), last_synced: Default::default(), cancellation_reason: Default::default(), amount_to_capture: Default::default(), browser_info: Default::default(), payment_token: Default::default(), error_code: Default::default(), connector_metadata: Default::default(), payment_experience: Default::default(), payment_method_type: Default::default(), payment_method_data: Default::default(), business_sub_label: Default::default(), straight_through_algorithm: Default::default(), preprocessing_step_id: Default::default(), mandate_details: Default::default(), error_reason: Default::default(), connector_response_reference_id: Default::default(), multiple_capture_count: Default::default(), amount_capturable: Default::default(), updated_by: Default::default(), authentication_data: Default::default(), encoded_data: Default::default(), merchant_connector_id: Default::default(), unified_code: Default::default(), unified_message: Default::default(), external_three_ds_authentication_attempted: Default::default(), authentication_connector: Default::default(), authentication_id: Default::default(), mandate_data: Default::default(), payment_method_billing_address_id: Default::default(), fingerprint_id: Default::default(), client_source: Default::default(), client_version: Default::default(), customer_acceptance: Default::default(), profile_id: common_utils::generate_profile_id_of_default_length(), organization_id: Default::default(), connector_mandate_detail: Default::default(), request_extended_authorization: Default::default(), extended_authorization_applied: Default::default(), capture_before: Default::default(), card_discovery: Default::default(), processor_merchant_id: Default::default(), created_by: None, setup_future_usage_applied: Default::default(), routing_approach: Default::default(), connector_request_reference_id: Default::default(), network_transaction_id: Default::default(), network_details: Default::default(), is_stored_credential: Default::default(), authorized_amount: Default::default(), }; let store = state .stores .get(state.conf.multitenancy.get_tenant_ids().first().unwrap()) .unwrap(); store .insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly) .await .unwrap(); let response = store .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_id, &merchant_id, &uuid, enums::MerchantStorageScheme::PostgresOnly, ) .await .unwrap(); // checking it after fetch assert_eq!(response.mandate_id, Some("man_121212".to_string())); } } </file>
{ "crate": "router", "file": "crates/router/src/types/storage/payment_attempt.rs", "files": null, "module": null, "num_files": null, "token_count": 3702 }
large_file_-3430232713539700087
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/types/storage/revenue_recovery_redis_operation.rs </path> <file> 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(()) } } </file>
{ "crate": "router", "file": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs", "files": null, "module": null, "num_files": null, "token_count": 6512 }
large_file_768627762917996792
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/types/storage/refund.rs </path> <file> use api_models::payments::AmountFilter; use async_bb8_diesel::AsyncRunQueryDsl; use common_utils::errors::CustomResult; use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, QueryDsl}; #[cfg(feature = "v1")] use diesel_models::schema::refund::dsl; #[cfg(feature = "v2")] use diesel_models::schema_v2::refund::dsl; use diesel_models::{ enums::{Currency, RefundStatus}, errors, query::generics::db_metrics, refund::Refund, }; use error_stack::ResultExt; use hyperswitch_domain_models::refunds; use crate::{connection::PgPooledConn, logger}; #[async_trait::async_trait] pub trait RefundDbExt: Sized { #[cfg(feature = "v1")] async fn filter_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_list_details: &refunds::RefundListConstraints, limit: i64, offset: i64, ) -> CustomResult<Vec<Self>, errors::DatabaseError>; #[cfg(feature = "v2")] async fn filter_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_list_details: refunds::RefundListConstraints, limit: i64, offset: i64, ) -> CustomResult<Vec<Self>, errors::DatabaseError>; #[cfg(feature = "v1")] async fn filter_by_meta_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_list_details: &common_utils::types::TimeRange, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError>; #[cfg(feature = "v1")] async fn get_refunds_count( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_list_details: &refunds::RefundListConstraints, ) -> CustomResult<i64, errors::DatabaseError>; #[cfg(feature = "v1")] async fn get_refund_status_with_count( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(RefundStatus, i64)>, errors::DatabaseError>; #[cfg(feature = "v2")] async fn get_refunds_count( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_list_details: refunds::RefundListConstraints, ) -> CustomResult<i64, errors::DatabaseError>; } #[async_trait::async_trait] impl RefundDbExt for Refund { #[cfg(feature = "v1")] async fn filter_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_list_details: &refunds::RefundListConstraints, limit: i64, offset: i64, ) -> CustomResult<Vec<Self>, errors::DatabaseError> { let mut filter = <Self as HasTable>::table() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .order(dsl::modified_at.desc()) .into_boxed(); let mut search_by_pay_or_ref_id = false; if let (Some(pid), Some(ref_id)) = ( &refund_list_details.payment_id, &refund_list_details.refund_id, ) { search_by_pay_or_ref_id = true; filter = filter .filter( dsl::payment_id .eq(pid.to_owned()) .or(dsl::refund_id.eq(ref_id.to_owned())), ) .limit(limit) .offset(offset); }; if !search_by_pay_or_ref_id { match &refund_list_details.payment_id { Some(pid) => { filter = filter.filter(dsl::payment_id.eq(pid.to_owned())); } None => { filter = filter.limit(limit).offset(offset); } }; } if !search_by_pay_or_ref_id { match &refund_list_details.refund_id { Some(ref_id) => { filter = filter.filter(dsl::refund_id.eq(ref_id.to_owned())); } None => { filter = filter.limit(limit).offset(offset); } }; } match &refund_list_details.profile_id { Some(profile_id) => { filter = filter .filter(dsl::profile_id.eq_any(profile_id.to_owned())) .limit(limit) .offset(offset); } None => { filter = filter.limit(limit).offset(offset); } }; if let Some(time_range) = refund_list_details.time_range { filter = filter.filter(dsl::created_at.ge(time_range.start_time)); if let Some(end_time) = time_range.end_time { filter = filter.filter(dsl::created_at.le(end_time)); } } filter = match refund_list_details.amount_filter { Some(AmountFilter { start_amount: Some(start), end_amount: Some(end), }) => filter.filter(dsl::refund_amount.between(start, end)), Some(AmountFilter { start_amount: Some(start), end_amount: None, }) => filter.filter(dsl::refund_amount.ge(start)), Some(AmountFilter { start_amount: None, end_amount: Some(end), }) => filter.filter(dsl::refund_amount.le(end)), _ => filter, }; if let Some(connector) = refund_list_details.connector.clone() { filter = filter.filter(dsl::connector.eq_any(connector)); } if let Some(merchant_connector_id) = refund_list_details.merchant_connector_id.clone() { filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id)); } if let Some(filter_currency) = &refund_list_details.currency { filter = filter.filter(dsl::currency.eq_any(filter_currency.clone())); } if let Some(filter_refund_status) = &refund_list_details.refund_status { filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status.clone())); } logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string()); db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( filter.get_results_async(conn), db_metrics::DatabaseOperation::Filter, ) .await .change_context(errors::DatabaseError::NotFound) .attach_printable_lazy(|| "Error filtering records by predicate") } #[cfg(feature = "v2")] async fn filter_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_list_details: refunds::RefundListConstraints, limit: i64, offset: i64, ) -> CustomResult<Vec<Self>, errors::DatabaseError> { let mut filter = <Self as HasTable>::table() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .order(dsl::modified_at.desc()) .into_boxed(); if let Some(payment_id) = &refund_list_details.payment_id { filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned())); } if let Some(refund_id) = &refund_list_details.refund_id { filter = filter.filter(dsl::id.eq(refund_id.to_owned())); } if let Some(time_range) = &refund_list_details.time_range { filter = filter.filter(dsl::created_at.ge(time_range.start_time)); if let Some(end_time) = time_range.end_time { filter = filter.filter(dsl::created_at.le(end_time)); } } filter = match refund_list_details.amount_filter { Some(AmountFilter { start_amount: Some(start), end_amount: Some(end), }) => filter.filter(dsl::refund_amount.between(start, end)), Some(AmountFilter { start_amount: Some(start), end_amount: None, }) => filter.filter(dsl::refund_amount.ge(start)), Some(AmountFilter { start_amount: None, end_amount: Some(end), }) => filter.filter(dsl::refund_amount.le(end)), _ => filter, }; if let Some(connector) = refund_list_details.connector { filter = filter.filter(dsl::connector.eq_any(connector)); } if let Some(connector_id_list) = refund_list_details.connector_id_list { filter = filter.filter(dsl::connector_id.eq_any(connector_id_list)); } if let Some(filter_currency) = refund_list_details.currency { filter = filter.filter(dsl::currency.eq_any(filter_currency)); } if let Some(filter_refund_status) = refund_list_details.refund_status { filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status)); } filter = filter.limit(limit).offset(offset); logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string()); db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( filter.get_results_async(conn), db_metrics::DatabaseOperation::Filter, ) .await .change_context(errors::DatabaseError::NotFound) .attach_printable_lazy(|| "Error filtering records by predicate") // todo!() } #[cfg(feature = "v1")] async fn filter_by_meta_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_list_details: &common_utils::types::TimeRange, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError> { let start_time = refund_list_details.start_time; let end_time = refund_list_details .end_time .unwrap_or_else(common_utils::date_time::now); let filter = <Self as HasTable>::table() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .order(dsl::modified_at.desc()) .filter(dsl::created_at.ge(start_time)) .filter(dsl::created_at.le(end_time)); let filter_connector: Vec<String> = filter .clone() .select(dsl::connector) .distinct() .order_by(dsl::connector.asc()) .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error filtering records by connector")?; let filter_currency: Vec<Currency> = filter .clone() .select(dsl::currency) .distinct() .order_by(dsl::currency.asc()) .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error filtering records by currency")?; let filter_status: Vec<RefundStatus> = filter .select(dsl::refund_status) .distinct() .order_by(dsl::refund_status.asc()) .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error filtering records by refund status")?; let meta = api_models::refunds::RefundListMetaData { connector: filter_connector, currency: filter_currency, refund_status: filter_status, }; Ok(meta) } #[cfg(feature = "v1")] async fn get_refunds_count( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_list_details: &refunds::RefundListConstraints, ) -> CustomResult<i64, errors::DatabaseError> { let mut filter = <Self as HasTable>::table() .count() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .into_boxed(); let mut search_by_pay_or_ref_id = false; if let (Some(pid), Some(ref_id)) = ( &refund_list_details.payment_id, &refund_list_details.refund_id, ) { search_by_pay_or_ref_id = true; filter = filter.filter( dsl::payment_id .eq(pid.to_owned()) .or(dsl::refund_id.eq(ref_id.to_owned())), ); }; if !search_by_pay_or_ref_id { if let Some(pay_id) = &refund_list_details.payment_id { filter = filter.filter(dsl::payment_id.eq(pay_id.to_owned())); } } if !search_by_pay_or_ref_id { if let Some(ref_id) = &refund_list_details.refund_id { filter = filter.filter(dsl::refund_id.eq(ref_id.to_owned())); } } if let Some(profile_id) = &refund_list_details.profile_id { filter = filter.filter(dsl::profile_id.eq_any(profile_id.to_owned())); } if let Some(time_range) = refund_list_details.time_range { filter = filter.filter(dsl::created_at.ge(time_range.start_time)); if let Some(end_time) = time_range.end_time { filter = filter.filter(dsl::created_at.le(end_time)); } } filter = match refund_list_details.amount_filter { Some(AmountFilter { start_amount: Some(start), end_amount: Some(end), }) => filter.filter(dsl::refund_amount.between(start, end)), Some(AmountFilter { start_amount: Some(start), end_amount: None, }) => filter.filter(dsl::refund_amount.ge(start)), Some(AmountFilter { start_amount: None, end_amount: Some(end), }) => filter.filter(dsl::refund_amount.le(end)), _ => filter, }; if let Some(connector) = refund_list_details.connector.clone() { filter = filter.filter(dsl::connector.eq_any(connector)); } if let Some(merchant_connector_id) = refund_list_details.merchant_connector_id.clone() { filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id)) } if let Some(filter_currency) = &refund_list_details.currency { filter = filter.filter(dsl::currency.eq_any(filter_currency.clone())); } if let Some(filter_refund_status) = &refund_list_details.refund_status { filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status.clone())); } logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string()); filter .get_result_async::<i64>(conn) .await .change_context(errors::DatabaseError::NotFound) .attach_printable_lazy(|| "Error filtering count of refunds") } #[cfg(feature = "v2")] async fn get_refunds_count( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_list_details: refunds::RefundListConstraints, ) -> CustomResult<i64, errors::DatabaseError> { let mut filter = <Self as HasTable>::table() .count() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .into_boxed(); if let Some(payment_id) = &refund_list_details.payment_id { filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned())); } if let Some(refund_id) = &refund_list_details.refund_id { filter = filter.filter(dsl::id.eq(refund_id.to_owned())); } if let Some(time_range) = refund_list_details.time_range { filter = filter.filter(dsl::created_at.ge(time_range.start_time)); if let Some(end_time) = time_range.end_time { filter = filter.filter(dsl::created_at.le(end_time)); } } filter = match refund_list_details.amount_filter { Some(AmountFilter { start_amount: Some(start), end_amount: Some(end), }) => filter.filter(dsl::refund_amount.between(start, end)), Some(AmountFilter { start_amount: Some(start), end_amount: None, }) => filter.filter(dsl::refund_amount.ge(start)), Some(AmountFilter { start_amount: None, end_amount: Some(end), }) => filter.filter(dsl::refund_amount.le(end)), _ => filter, }; if let Some(connector) = refund_list_details.connector { filter = filter.filter(dsl::connector.eq_any(connector)); } if let Some(connector_id_list) = refund_list_details.connector_id_list { filter = filter.filter(dsl::connector_id.eq_any(connector_id_list)); } if let Some(filter_currency) = refund_list_details.currency { filter = filter.filter(dsl::currency.eq_any(filter_currency)); } if let Some(filter_refund_status) = refund_list_details.refund_status { filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status)); } logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string()); filter .get_result_async::<i64>(conn) .await .change_context(errors::DatabaseError::NotFound) .attach_printable_lazy(|| "Error filtering count of refunds") } #[cfg(feature = "v1")] async fn get_refund_status_with_count( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(RefundStatus, i64)>, errors::DatabaseError> { let mut query = <Self as HasTable>::table() .group_by(dsl::refund_status) .select((dsl::refund_status, diesel::dsl::count_star())) .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .into_boxed(); if let Some(profile_id) = profile_id_list { query = query.filter(dsl::profile_id.eq_any(profile_id)); } query = query.filter(dsl::created_at.ge(time_range.start_time)); query = match time_range.end_time { Some(ending_at) => query.filter(dsl::created_at.le(ending_at)), None => query, }; logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( query.get_results_async::<(RefundStatus, i64)>(conn), db_metrics::DatabaseOperation::Count, ) .await .change_context(errors::DatabaseError::NotFound) .attach_printable_lazy(|| "Error filtering status count of refunds") } } </file>
{ "crate": "router", "file": "crates/router/src/types/storage/refund.rs", "files": null, "module": null, "num_files": null, "token_count": 4141 }
large_file_-8751494965272267630
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/types/api/connector_mapping.rs </path> <file> 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), } } } </file>
{ "crate": "router", "file": "crates/router/src/types/api/connector_mapping.rs", "files": null, "module": null, "num_files": null, "token_count": 5086 }
large_file_7472453009038255325
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/types/api/feature_matrix.rs </path> <file> 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), } } } </file>
{ "crate": "router", "file": "crates/router/src/types/api/feature_matrix.rs", "files": null, "module": null, "num_files": null, "token_count": 4467 }
large_file_5020703688563498006
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/types/api/admin.rs </path> <file> 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), })) } </file>
{ "crate": "router", "file": "crates/router/src/types/api/admin.rs", "files": null, "module": null, "num_files": null, "token_count": 4687 }
large_file_6552240619275852791
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/types/domain/address.rs </path> <file> 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), }, } } } </file>
{ "crate": "router", "file": "crates/router/src/types/domain/address.rs", "files": null, "module": null, "num_files": null, "token_count": 2595 }
large_file_5224941223547534506
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/types/domain/user.rs </path> <file> 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) } } </file>
{ "crate": "router", "file": "crates/router/src/types/domain/user.rs", "files": null, "module": null, "num_files": null, "token_count": 10581 }
large_file_406113982938191263
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/types/domain/user/decision_manager.rs </path> <file> use common_enums::TokenPurpose; use common_utils::{id_type, types::user::LineageContext}; use diesel_models::{ enums::{UserRoleVersion, UserStatus}, user_role::UserRole, }; use error_stack::ResultExt; use masking::Secret; use router_env::logger; use super::UserFromStorage; use crate::{ core::errors::{UserErrors, UserResult}, db::user_role::ListUserRolesByUserIdPayload, routes::SessionState, services::authentication as auth, utils, }; #[derive(Eq, PartialEq, Clone, Copy)] pub enum UserFlow { SPTFlow(SPTFlow), JWTFlow(JWTFlow), } impl UserFlow { async fn is_required( &self, user: &UserFromStorage, path: &[TokenPurpose], state: &SessionState, user_tenant_id: &id_type::TenantId, ) -> UserResult<bool> { match self { Self::SPTFlow(flow) => flow.is_required(user, path, state, user_tenant_id).await, Self::JWTFlow(flow) => flow.is_required(user, state).await, } } } #[derive(Eq, PartialEq, Clone, Copy)] pub enum SPTFlow { AuthSelect, SSO, TOTP, VerifyEmail, AcceptInvitationFromEmail, ForceSetPassword, MerchantSelect, ResetPassword, } impl SPTFlow { async fn is_required( &self, user: &UserFromStorage, path: &[TokenPurpose], state: &SessionState, user_tenant_id: &id_type::TenantId, ) -> UserResult<bool> { match self { // Auth Self::AuthSelect => Ok(true), Self::SSO => Ok(true), // TOTP Self::TOTP => Ok(!path.contains(&TokenPurpose::SSO)), // Main email APIs Self::AcceptInvitationFromEmail | Self::ResetPassword => Ok(true), Self::VerifyEmail => Ok(true), // Final Checks Self::ForceSetPassword => user .is_password_rotate_required(state) .map(|rotate_required| rotate_required && !path.contains(&TokenPurpose::SSO)), Self::MerchantSelect => Ok(state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: user.get_user_id(), tenant_id: user_tenant_id, org_id: None, merchant_id: None, profile_id: None, entity_id: None, version: None, status: Some(UserStatus::Active), limit: Some(1), }) .await .change_context(UserErrors::InternalServerError)? .is_empty()), } } pub async fn generate_spt( self, state: &SessionState, next_flow: &NextFlow, ) -> UserResult<Secret<String>> { auth::SinglePurposeToken::new_token( next_flow.user.get_user_id().to_string(), self.into(), next_flow.origin.clone(), &state.conf, next_flow.path.to_vec(), Some(state.tenant.tenant_id.clone()), ) .await .map(|token| token.into()) } } #[derive(Eq, PartialEq, Clone, Copy)] pub enum JWTFlow { UserInfo, } impl JWTFlow { async fn is_required( &self, _user: &UserFromStorage, _state: &SessionState, ) -> UserResult<bool> { Ok(true) } pub async fn generate_jwt( self, state: &SessionState, next_flow: &NextFlow, user_role: &UserRole, ) -> UserResult<Secret<String>> { let user_id = next_flow.user.get_user_id(); // Fetch lineage context from DB let lineage_context_from_db = state .global_store .find_user_by_id(user_id) .await .inspect_err(|e| { logger::error!( "Failed to fetch lineage context from DB for user {}: {:?}", user_id, e ) }) .ok() .and_then(|user| user.lineage_context); let new_lineage_context = match lineage_context_from_db { Some(ctx) => { let tenant_id = ctx.tenant_id.clone(); let user_role_match_v2 = state .global_store .find_user_role_by_user_id_and_lineage( &ctx.user_id, &tenant_id, &ctx.org_id, &ctx.merchant_id, &ctx.profile_id, UserRoleVersion::V2, ) .await .inspect_err(|e| { logger::error!("Failed to validate V2 role: {e:?}"); }) .map(|role| role.role_id == ctx.role_id) .unwrap_or_default(); if user_role_match_v2 { ctx } else { let user_role_match_v1 = state .global_store .find_user_role_by_user_id_and_lineage( &ctx.user_id, &tenant_id, &ctx.org_id, &ctx.merchant_id, &ctx.profile_id, UserRoleVersion::V1, ) .await .inspect_err(|e| { logger::error!("Failed to validate V1 role: {e:?}"); }) .map(|role| role.role_id == ctx.role_id) .unwrap_or_default(); if user_role_match_v1 { ctx } else { // fallback to default lineage if cached context is invalid Self::resolve_lineage_from_user_role(state, user_role, user_id).await? } } } None => // no cached context found { Self::resolve_lineage_from_user_role(state, user_role, user_id).await? } }; utils::user::spawn_async_lineage_context_update_to_db( state, user_id, new_lineage_context.clone(), ); auth::AuthToken::new_token( new_lineage_context.user_id, new_lineage_context.merchant_id, new_lineage_context.role_id, &state.conf, new_lineage_context.org_id, new_lineage_context.profile_id, Some(new_lineage_context.tenant_id), ) .await .map(|token| token.into()) } pub async fn resolve_lineage_from_user_role( state: &SessionState, user_role: &UserRole, user_id: &str, ) -> UserResult<LineageContext> { let org_id = utils::user_role::get_single_org_id(state, user_role).await?; let merchant_id = utils::user_role::get_single_merchant_id(state, user_role, &org_id).await?; let profile_id = utils::user_role::get_single_profile_id(state, user_role, &merchant_id).await?; Ok(LineageContext { user_id: user_id.to_string(), org_id, merchant_id, profile_id, role_id: user_role.role_id.clone(), tenant_id: user_role.tenant_id.clone(), }) } } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] #[serde(rename_all = "snake_case")] pub enum Origin { #[serde(rename = "sign_in_with_sso")] SignInWithSSO, SignIn, SignUp, MagicLink, VerifyEmail, AcceptInvitationFromEmail, ResetPassword, } impl Origin { fn get_flows(&self) -> &'static [UserFlow] { match self { Self::SignInWithSSO => &SIGNIN_WITH_SSO_FLOW, Self::SignIn => &SIGNIN_FLOW, Self::SignUp => &SIGNUP_FLOW, Self::VerifyEmail => &VERIFY_EMAIL_FLOW, Self::MagicLink => &MAGIC_LINK_FLOW, Self::AcceptInvitationFromEmail => &ACCEPT_INVITATION_FROM_EMAIL_FLOW, Self::ResetPassword => &RESET_PASSWORD_FLOW, } } } const SIGNIN_WITH_SSO_FLOW: [UserFlow; 2] = [ UserFlow::SPTFlow(SPTFlow::MerchantSelect), UserFlow::JWTFlow(JWTFlow::UserInfo), ]; const SIGNIN_FLOW: [UserFlow; 4] = [ UserFlow::SPTFlow(SPTFlow::TOTP), UserFlow::SPTFlow(SPTFlow::ForceSetPassword), UserFlow::SPTFlow(SPTFlow::MerchantSelect), UserFlow::JWTFlow(JWTFlow::UserInfo), ]; const SIGNUP_FLOW: [UserFlow; 4] = [ UserFlow::SPTFlow(SPTFlow::TOTP), UserFlow::SPTFlow(SPTFlow::ForceSetPassword), UserFlow::SPTFlow(SPTFlow::MerchantSelect), UserFlow::JWTFlow(JWTFlow::UserInfo), ]; const MAGIC_LINK_FLOW: [UserFlow; 5] = [ UserFlow::SPTFlow(SPTFlow::TOTP), UserFlow::SPTFlow(SPTFlow::VerifyEmail), UserFlow::SPTFlow(SPTFlow::ForceSetPassword), UserFlow::SPTFlow(SPTFlow::MerchantSelect), UserFlow::JWTFlow(JWTFlow::UserInfo), ]; const VERIFY_EMAIL_FLOW: [UserFlow; 5] = [ UserFlow::SPTFlow(SPTFlow::TOTP), UserFlow::SPTFlow(SPTFlow::VerifyEmail), UserFlow::SPTFlow(SPTFlow::ForceSetPassword), UserFlow::SPTFlow(SPTFlow::MerchantSelect), UserFlow::JWTFlow(JWTFlow::UserInfo), ]; const ACCEPT_INVITATION_FROM_EMAIL_FLOW: [UserFlow; 6] = [ UserFlow::SPTFlow(SPTFlow::AuthSelect), UserFlow::SPTFlow(SPTFlow::SSO), UserFlow::SPTFlow(SPTFlow::TOTP), UserFlow::SPTFlow(SPTFlow::AcceptInvitationFromEmail), UserFlow::SPTFlow(SPTFlow::ForceSetPassword), UserFlow::JWTFlow(JWTFlow::UserInfo), ]; const RESET_PASSWORD_FLOW: [UserFlow; 2] = [ UserFlow::SPTFlow(SPTFlow::TOTP), UserFlow::SPTFlow(SPTFlow::ResetPassword), ]; pub struct CurrentFlow { origin: Origin, current_flow_index: usize, path: Vec<TokenPurpose>, tenant_id: Option<id_type::TenantId>, } impl CurrentFlow { pub fn new( token: auth::UserFromSinglePurposeToken, current_flow: UserFlow, ) -> UserResult<Self> { let flows = token.origin.get_flows(); let index = flows .iter() .position(|flow| flow == &current_flow) .ok_or(UserErrors::InternalServerError)?; let mut path = token.path; path.push(current_flow.into()); Ok(Self { origin: token.origin, current_flow_index: index, path, tenant_id: token.tenant_id, }) } pub async fn next(self, user: UserFromStorage, state: &SessionState) -> UserResult<NextFlow> { let flows = self.origin.get_flows(); let remaining_flows = flows.iter().skip(self.current_flow_index + 1); for flow in remaining_flows { if flow .is_required( &user, &self.path, state, self.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), ) .await? { return Ok(NextFlow { origin: self.origin.clone(), next_flow: *flow, user, path: self.path, tenant_id: self.tenant_id, }); } } Err(UserErrors::InternalServerError.into()) } } pub struct NextFlow { origin: Origin, next_flow: UserFlow, user: UserFromStorage, path: Vec<TokenPurpose>, tenant_id: Option<id_type::TenantId>, } impl NextFlow { pub async fn from_origin( origin: Origin, user: UserFromStorage, state: &SessionState, ) -> UserResult<Self> { let flows = origin.get_flows(); let path = vec![]; for flow in flows { if flow .is_required(&user, &path, state, &state.tenant.tenant_id) .await? { return Ok(Self { origin, next_flow: *flow, user, path, tenant_id: Some(state.tenant.tenant_id.clone()), }); } } Err(UserErrors::InternalServerError.into()) } pub fn get_flow(&self) -> UserFlow { self.next_flow } pub async fn get_token(&self, state: &SessionState) -> UserResult<Secret<String>> { match self.next_flow { UserFlow::SPTFlow(spt_flow) => spt_flow.generate_spt(state, self).await, UserFlow::JWTFlow(jwt_flow) => { #[cfg(feature = "email")] { self.user.get_verification_days_left(state)?; } let user_role = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: self.user.get_user_id(), tenant_id: self.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), org_id: None, merchant_id: None, profile_id: None, entity_id: None, version: None, status: Some(UserStatus::Active), limit: Some(1), }) .await .change_context(UserErrors::InternalServerError)? .pop() .ok_or(UserErrors::InternalServerError)?; utils::user_role::set_role_info_in_cache_by_user_role(state, &user_role).await; jwt_flow.generate_jwt(state, self, &user_role).await } } } pub async fn get_token_with_user_role( &self, state: &SessionState, user_role: &UserRole, ) -> UserResult<Secret<String>> { match self.next_flow { UserFlow::SPTFlow(spt_flow) => spt_flow.generate_spt(state, self).await, UserFlow::JWTFlow(jwt_flow) => { #[cfg(feature = "email")] { self.user.get_verification_days_left(state)?; } utils::user_role::set_role_info_in_cache_by_user_role(state, user_role).await; jwt_flow.generate_jwt(state, self, user_role).await } } } pub async fn skip(self, user: UserFromStorage, state: &SessionState) -> UserResult<Self> { let flows = self.origin.get_flows(); let index = flows .iter() .position(|flow| flow == &self.get_flow()) .ok_or(UserErrors::InternalServerError)?; let remaining_flows = flows.iter().skip(index + 1); for flow in remaining_flows { if flow .is_required(&user, &self.path, state, &state.tenant.tenant_id) .await? { return Ok(Self { origin: self.origin.clone(), next_flow: *flow, user, path: self.path, tenant_id: Some(state.tenant.tenant_id.clone()), }); } } Err(UserErrors::InternalServerError.into()) } } impl From<UserFlow> for TokenPurpose { fn from(value: UserFlow) -> Self { match value { UserFlow::SPTFlow(flow) => flow.into(), UserFlow::JWTFlow(flow) => flow.into(), } } } impl From<SPTFlow> for TokenPurpose { fn from(value: SPTFlow) -> Self { match value { SPTFlow::AuthSelect => Self::AuthSelect, SPTFlow::SSO => Self::SSO, SPTFlow::TOTP => Self::TOTP, SPTFlow::VerifyEmail => Self::VerifyEmail, SPTFlow::AcceptInvitationFromEmail => Self::AcceptInvitationFromEmail, SPTFlow::MerchantSelect => Self::AcceptInvite, SPTFlow::ResetPassword => Self::ResetPassword, SPTFlow::ForceSetPassword => Self::ForceSetPassword, } } } impl From<JWTFlow> for TokenPurpose { fn from(value: JWTFlow) -> Self { match value { JWTFlow::UserInfo => Self::UserInfo, } } } impl From<SPTFlow> for UserFlow { fn from(value: SPTFlow) -> Self { Self::SPTFlow(value) } } impl From<JWTFlow> for UserFlow { fn from(value: JWTFlow) -> Self { Self::JWTFlow(value) } } </file>
{ "crate": "router", "file": "crates/router/src/types/domain/user/decision_manager.rs", "files": null, "module": null, "num_files": null, "token_count": 3663 }
large_file_-2556535287726567
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/refunds.rs </path> <file> #[cfg(feature = "olap")] use std::collections::HashMap; #[cfg(feature = "olap")] use api_models::admin::MerchantConnectorInfo; use common_utils::{ ext_traits::{AsyncExt, StringExt}, types::{ConnectorTransactionId, MinorUnit}, }; use diesel_models::{process_tracker::business_status, refund as diesel_refund}; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ router_data::ErrorResponse, router_request_types::SplitRefundsRequest, }; use hyperswitch_interfaces::integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject}; use router_env::{instrument, tracing}; use scheduler::{ consumer::types::process_data, errors as sch_errors, utils as process_tracker_utils, }; #[cfg(feature = "olap")] use strum::IntoEnumIterator; use crate::{ consts, core::{ errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt}, payments::{self, access_token, helpers}, refunds::transformers::SplitRefundInput, utils::{ self as core_utils, refunds_transformers as transformers, refunds_validator as validator, }, }, db, logger, routes::{metrics, SessionState}, services, types::{ self, api::{self, refunds}, domain, storage::{self, enums}, transformers::{ForeignFrom, ForeignInto}, }, utils::{self, OptionExt}, }; // ********************************************** REFUND EXECUTE ********************************************** #[instrument(skip_all)] pub async fn refund_create_core( state: SessionState, merchant_context: domain::MerchantContext, _profile_id: Option<common_utils::id_type::ProfileId>, req: refunds::RefundRequest, ) -> RouterResponse<refunds::RefundResponse> { let db = &*state.store; let (merchant_id, payment_intent, payment_attempt, amount); merchant_id = merchant_context.get_merchant_account().get_id(); payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), &req.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)?; utils::when( !(payment_intent.status == enums::IntentStatus::Succeeded || payment_intent.status == enums::IntentStatus::PartiallyCaptured), || { Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState { current_flow: "refund".into(), field_name: "status".into(), current_value: payment_intent.status.to_string(), states: "succeeded, partially_captured".to_string() }) .attach_printable("unable to refund for a unsuccessful payment intent")) }, )?; // Amount is not passed in request refer from payment intent. amount = req .amount .or(payment_intent.amount_captured) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("amount captured is none in a successful payment")?; //[#299]: Can we change the flow based on some workflow idea utils::when(amount <= MinorUnit::new(0), || { Err(report!(errors::ApiErrorResponse::InvalidDataFormat { field_name: "amount".to_string(), expected_format: "positive integer".to_string() }) .attach_printable("amount less than or equal to zero")) })?; payment_attempt = db .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &req.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::SuccessfulPaymentNotFound)?; let creds_identifier = req .merchant_connector_details .as_ref() .map(|mcd| mcd.creds_identifier.to_owned()); req.merchant_connector_details .to_owned() .async_map(|mcd| async { helpers::insert_merchant_connector_creds_to_config(db, merchant_id, mcd).await }) .await .transpose()?; Box::pin(validate_and_create_refund( &state, &merchant_context, &payment_attempt, &payment_intent, amount, req, creds_identifier, )) .await .map(services::ApplicationResponse::Json) } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn trigger_refund_to_gateway( state: &SessionState, refund: &diesel_refund::Refund, merchant_context: &domain::MerchantContext, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, creds_identifier: Option<String>, split_refunds: Option<SplitRefundsRequest>, ) -> RouterResult<diesel_refund::Refund> { let routed_through = payment_attempt .connector .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve connector from payment attempt")?; let storage_scheme = merchant_context.get_merchant_account().storage_scheme; metrics::REFUND_COUNT.add( 1, router_env::metric_attributes!(("connector", routed_through.clone())), ); let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &routed_through, api::GetToken::Connector, payment_attempt.merchant_connector_id.clone(), )?; let currency = payment_attempt.currency.ok_or_else(|| { report!(errors::ApiErrorResponse::InternalServerError).attach_printable( "Transaction in invalid. Missing field \"currency\" in payment_attempt.", ) })?; validator::validate_for_valid_refunds(payment_attempt, connector.connector_name)?; let mut router_data = core_utils::construct_refund_router_data( state, &routed_through, merchant_context, (payment_attempt.get_total_amount(), currency), payment_intent, payment_attempt, refund, creds_identifier.clone(), split_refunds, ) .await?; let add_access_token_result = Box::pin(access_token::add_access_token( state, &connector, merchant_context, &router_data, creds_identifier.as_deref(), )) .await?; logger::debug!(refund_router_data=?router_data); access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &payments::CallConnectorAction::Trigger, ); let router_data_res = if !(add_access_token_result.connector_supports_access_token && router_data.access_token.is_none()) { let connector_integration: services::BoxedRefundConnectorIntegrationInterface< api::Execute, types::RefundsData, types::RefundsResponseData, > = connector.connector.get_connector_integration(); let router_data_res = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await; let option_refund_error_update = router_data_res .as_ref() .err() .and_then(|error| match error.current_context() { errors::ConnectorError::NotImplemented(message) => { Some(diesel_refund::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::Failure), refund_error_message: Some( errors::ConnectorError::NotImplemented(message.to_owned()) .to_string(), ), refund_error_code: Some("NOT_IMPLEMENTED".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: None, processor_refund_data: None, unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, }) } errors::ConnectorError::NotSupported { message, connector } => { Some(diesel_refund::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::Failure), refund_error_message: Some(format!( "{message} is not supported by {connector}" )), refund_error_code: Some("NOT_SUPPORTED".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: None, processor_refund_data: None, unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, }) } _ => None, }); // Update the refund status as failure if connector_error is NotImplemented if let Some(refund_error_update) = option_refund_error_update { state .store .update_refund( refund.to_owned(), refund_error_update, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while updating refund: refund_id: {}", refund.refund_id ) })?; } let mut refund_router_data_res = router_data_res.to_refund_failed_response()?; // Initiating Integrity check let integrity_result = check_refund_integrity( &refund_router_data_res.request, &refund_router_data_res.response, ); refund_router_data_res.integrity_check = integrity_result; refund_router_data_res } else { router_data }; let refund_update = match router_data_res.response { Err(err) => { let option_gsm = helpers::get_gsm_record( state, Some(err.code.clone()), Some(err.message.clone()), connector.connector_name.to_string(), consts::REFUND_FLOW_STR.to_string(), ) .await; // Note: Some connectors do not have a separate list of refund errors // In such cases, the error codes and messages are stored under "Authorize" flow in GSM table // So we will have to fetch the GSM using Authorize flow in case GSM is not found using "refund_flow" let option_gsm = if option_gsm.is_none() { helpers::get_gsm_record( state, Some(err.code.clone()), Some(err.message.clone()), connector.connector_name.to_string(), consts::AUTHORIZE_FLOW_STR.to_string(), ) .await } else { option_gsm }; let gsm_unified_code = option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone()); let gsm_unified_message = option_gsm.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(), ) }; diesel_refund::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::Failure), refund_error_message: err.reason.or(Some(err.message)), refund_error_code: Some(err.code), updated_by: storage_scheme.to_string(), connector_refund_id: None, processor_refund_data: None, unified_code: Some(unified_code), unified_message: Some(unified_message), issuer_error_code: err.network_decline_code, issuer_error_message: err.network_error_message, } } Ok(response) => { // match on connector integrity checks match router_data_res.integrity_check.clone() { Err(err) => { let (refund_connector_transaction_id, processor_refund_data) = err.connector_transaction_id.map_or((None, None), |txn_id| { let (refund_id, refund_data) = ConnectorTransactionId::form_id_and_data(txn_id); (Some(refund_id), refund_data) }); metrics::INTEGRITY_CHECK_FAILED.add( 1, router_env::metric_attributes!( ("connector", connector.connector_name.to_string()), ( "merchant_id", merchant_context.get_merchant_account().get_id().clone() ), ), ); diesel_refund::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::ManualReview), refund_error_message: Some(format!( "Integrity Check Failed! as data mismatched for fields {}", err.field_names )), refund_error_code: Some("IE".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: refund_connector_transaction_id, processor_refund_data, unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, } } Ok(()) => { if response.refund_status == diesel_models::enums::RefundStatus::Success { metrics::SUCCESSFUL_REFUND.add( 1, router_env::metric_attributes!(( "connector", connector.connector_name.to_string(), )), ) } let (connector_refund_id, processor_refund_data) = ConnectorTransactionId::form_id_and_data(response.connector_refund_id); diesel_refund::RefundUpdate::Update { connector_refund_id, refund_status: response.refund_status, sent_to_gateway: true, refund_error_message: None, refund_arn: "".to_string(), updated_by: storage_scheme.to_string(), processor_refund_data, } } } } }; let response = state .store .update_refund( refund.to_owned(), refund_update, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while updating refund: refund_id: {}", refund.refund_id ) })?; utils::trigger_refund_outgoing_webhook( state, merchant_context, &response, payment_attempt.profile_id.clone(), ) .await .map_err(|error| logger::warn!(refunds_outgoing_webhook_error=?error)) .ok(); Ok(response) } pub fn check_refund_integrity<T, Request>( request: &Request, refund_response_data: &Result<types::RefundsResponseData, ErrorResponse>, ) -> Result<(), common_utils::errors::IntegrityCheckError> where T: FlowIntegrity, Request: GetIntegrityObject<T> + CheckIntegrity<Request, T>, { let connector_refund_id = refund_response_data .as_ref() .map(|resp_data| resp_data.connector_refund_id.clone()) .ok(); request.check_integrity(request, connector_refund_id.to_owned()) } // ********************************************** REFUND SYNC ********************************************** pub async fn refund_response_wrapper<F, Fut, T, Req>( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, request: Req, f: F, ) -> RouterResponse<refunds::RefundResponse> where F: Fn( SessionState, domain::MerchantContext, Option<common_utils::id_type::ProfileId>, Req, ) -> Fut, Fut: futures::Future<Output = RouterResult<T>>, T: ForeignInto<refunds::RefundResponse>, { Ok(services::ApplicationResponse::Json( f(state, merchant_context, profile_id, request) .await? .foreign_into(), )) } #[instrument(skip_all)] pub async fn refund_retrieve_core( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, request: refunds::RefundsRetrieveRequest, refund: diesel_refund::Refund, ) -> RouterResult<diesel_refund::Refund> { let db = &*state.store; let merchant_id = merchant_context.get_merchant_account().get_id(); core_utils::validate_profile_id_from_auth_layer(profile_id, &refund)?; let payment_id = &refund.payment_id; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), 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 = db .find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &refund.connector_transaction_id, payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; 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_id, mcd).await }) .await .transpose()?; let split_refunds_req = core_utils::get_split_refunds(SplitRefundInput { split_payment_request: payment_intent.split_payments.clone(), payment_charges: payment_attempt.charges.clone(), charge_id: payment_attempt.charge_id.clone(), refund_request: refund.split_refunds.clone(), })?; let unified_translated_message = if let (Some(unified_code), Some(unified_message)) = (refund.unified_code.clone(), refund.unified_message.clone()) { helpers::get_unified_translation( &state, unified_code, unified_message.clone(), state.locale.to_string(), ) .await .or(Some(unified_message)) } else { refund.unified_message }; let refund = diesel_refund::Refund { unified_message: unified_translated_message, ..refund }; let response = if should_call_refund(&refund, request.force_sync.unwrap_or(false)) { Box::pin(sync_refund_with_gateway( &state, &merchant_context, &payment_attempt, &payment_intent, &refund, creds_identifier, split_refunds_req, )) .await } else { Ok(refund) }?; Ok(response) } fn should_call_refund(refund: &diesel_models::refund::Refund, force_sync: bool) -> bool { // This implies, we cannot perform a refund sync & `the connector_refund_id` // doesn't exist let predicate1 = refund.connector_refund_id.is_some(); // This allows refund sync at connector level if force_sync is enabled, or // checks if the refund has failed let predicate2 = force_sync || !matches!( refund.refund_status, diesel_models::enums::RefundStatus::Failure | diesel_models::enums::RefundStatus::Success ); predicate1 && predicate2 } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn sync_refund_with_gateway( state: &SessionState, merchant_context: &domain::MerchantContext, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, refund: &diesel_refund::Refund, creds_identifier: Option<String>, split_refunds: Option<SplitRefundsRequest>, ) -> RouterResult<diesel_refund::Refund> { let connector_id = refund.connector.to_string(); let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_id, api::GetToken::Connector, payment_attempt.merchant_connector_id.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector")?; let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let currency = payment_attempt.currency.get_required_value("currency")?; let mut router_data = core_utils::construct_refund_router_data::<api::RSync>( state, &connector_id, merchant_context, (payment_attempt.get_total_amount(), currency), payment_intent, payment_attempt, refund, creds_identifier.clone(), split_refunds, ) .await?; let add_access_token_result = Box::pin(access_token::add_access_token( state, &connector, merchant_context, &router_data, creds_identifier.as_deref(), )) .await?; logger::debug!(refund_retrieve_router_data=?router_data); access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &payments::CallConnectorAction::Trigger, ); let router_data_res = if !(add_access_token_result.connector_supports_access_token && router_data.access_token.is_none()) { let connector_integration: services::BoxedRefundConnectorIntegrationInterface< api::RSync, types::RefundsData, types::RefundsResponseData, > = connector.connector.get_connector_integration(); let mut refund_sync_router_data = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_refund_failed_response()?; // Initiating connector integrity checks let integrity_result = check_refund_integrity( &refund_sync_router_data.request, &refund_sync_router_data.response, ); refund_sync_router_data.integrity_check = integrity_result; refund_sync_router_data } else { router_data }; let refund_update = match router_data_res.response { Err(error_message) => { let refund_status = match error_message.status_code { // marking failure for 2xx because this is genuine refund failure 200..=299 => Some(enums::RefundStatus::Failure), _ => None, }; diesel_refund::RefundUpdate::ErrorUpdate { refund_status, refund_error_message: error_message.reason.or(Some(error_message.message)), refund_error_code: Some(error_message.code), updated_by: storage_scheme.to_string(), connector_refund_id: None, processor_refund_data: None, unified_code: None, unified_message: None, issuer_error_code: error_message.network_decline_code, issuer_error_message: error_message.network_error_message, } } Ok(response) => match router_data_res.integrity_check.clone() { Err(err) => { metrics::INTEGRITY_CHECK_FAILED.add( 1, router_env::metric_attributes!( ("connector", connector.connector_name.to_string()), ( "merchant_id", merchant_context.get_merchant_account().get_id().clone() ), ), ); let (refund_connector_transaction_id, processor_refund_data) = err .connector_transaction_id .map_or((None, None), |refund_id| { let (refund_id, refund_data) = ConnectorTransactionId::form_id_and_data(refund_id); (Some(refund_id), refund_data) }); diesel_refund::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::ManualReview), refund_error_message: Some(format!( "Integrity Check Failed! as data mismatched for fields {}", err.field_names )), refund_error_code: Some("IE".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: refund_connector_transaction_id, processor_refund_data, unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, } } Ok(()) => { let (connector_refund_id, processor_refund_data) = ConnectorTransactionId::form_id_and_data(response.connector_refund_id); diesel_refund::RefundUpdate::Update { connector_refund_id, refund_status: response.refund_status, sent_to_gateway: true, refund_error_message: None, refund_arn: "".to_string(), updated_by: storage_scheme.to_string(), processor_refund_data, } } }, }; let response = state .store .update_refund( refund.to_owned(), refund_update, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound) .attach_printable_lazy(|| { format!( "Unable to update refund with refund_id: {}", refund.refund_id ) })?; utils::trigger_refund_outgoing_webhook( state, merchant_context, &response, payment_attempt.profile_id.clone(), ) .await .map_err(|error| logger::warn!(refunds_outgoing_webhook_error=?error)) .ok(); Ok(response) } // ********************************************** REFUND UPDATE ********************************************** pub async fn refund_update_core( state: SessionState, merchant_context: domain::MerchantContext, req: refunds::RefundUpdateRequest, ) -> RouterResponse<refunds::RefundResponse> { let db = state.store.as_ref(); let refund = db .find_refund_by_merchant_id_refund_id( merchant_context.get_merchant_account().get_id(), &req.refund_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let response = db .update_refund( refund, diesel_refund::RefundUpdate::MetadataAndReasonUpdate { metadata: req.metadata, reason: req.reason, updated_by: merchant_context .get_merchant_account() .storage_scheme .to_string(), }, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("Unable to update refund with refund_id: {}", req.refund_id) })?; Ok(services::ApplicationResponse::Json(response.foreign_into())) } // ********************************************** VALIDATIONS ********************************************** #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn validate_and_create_refund( state: &SessionState, merchant_context: &domain::MerchantContext, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, refund_amount: MinorUnit, req: refunds::RefundRequest, creds_identifier: Option<String>, ) -> RouterResult<refunds::RefundResponse> { let db = &*state.store; let split_refunds = core_utils::get_split_refunds(SplitRefundInput { split_payment_request: payment_intent.split_payments.clone(), payment_charges: payment_attempt.charges.clone(), charge_id: payment_attempt.charge_id.clone(), refund_request: req.split_refunds.clone(), })?; // Only for initial dev and testing let refund_type = req.refund_type.unwrap_or_default(); // If Refund Id not passed in request Generate one. let refund_id = core_utils::get_or_generate_id("refund_id", &req.refund_id, "ref")?; let predicate = req .merchant_id .as_ref() .map(|merchant_id| merchant_id != merchant_context.get_merchant_account().get_id()); utils::when(predicate.unwrap_or(false), || { Err(report!(errors::ApiErrorResponse::InvalidDataFormat { field_name: "merchant_id".to_string(), expected_format: "merchant_id from merchant account".to_string() }) .attach_printable("invalid merchant_id in request")) })?; let connector_transaction_id = payment_attempt.clone().connector_transaction_id.ok_or_else(|| { report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Transaction in invalid. Missing field \"connector_transaction_id\" in payment_attempt.") })?; let all_refunds = db .find_refund_by_merchant_id_connector_transaction_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::RefundNotFound)?; let currency = payment_attempt.currency.get_required_value("currency")?; //[#249]: Add Connector Based Validation here. validator::validate_payment_order_age(&payment_intent.created_at, state.conf.refund.max_age) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "created_at".to_string(), expected_format: format!( "created_at not older than {} days", state.conf.refund.max_age, ), })?; let total_amount_captured = payment_intent .amount_captured .unwrap_or(payment_attempt.get_total_amount()); validator::validate_refund_amount( total_amount_captured.get_amount_as_i64(), &all_refunds, refund_amount.get_amount_as_i64(), ) .change_context(errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount)?; validator::validate_maximum_refund_against_payment_attempt( &all_refunds, state.conf.refund.max_attempts, ) .change_context(errors::ApiErrorResponse::MaximumRefundCount)?; let connector = payment_attempt .connector .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("No connector populated in payment attempt")?; let (connector_transaction_id, processor_transaction_data) = ConnectorTransactionId::form_id_and_data(connector_transaction_id); let refund_create_req = diesel_refund::RefundNew { refund_id: refund_id.to_string(), internal_reference_id: utils::generate_id(consts::ID_LENGTH, "refid"), external_reference_id: Some(refund_id.clone()), payment_id: req.payment_id, merchant_id: merchant_context.get_merchant_account().get_id().clone(), connector_transaction_id, connector, refund_type: req.refund_type.unwrap_or_default().foreign_into(), total_amount: payment_attempt.get_total_amount(), refund_amount, currency, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), refund_status: enums::RefundStatus::Pending, metadata: req.metadata, description: req.reason.clone(), attempt_id: payment_attempt.attempt_id.clone(), refund_reason: req.reason, profile_id: payment_intent.profile_id.clone(), merchant_connector_id: payment_attempt.merchant_connector_id.clone(), charges: None, split_refunds: req.split_refunds, connector_refund_id: None, sent_to_gateway: Default::default(), refund_arn: None, updated_by: Default::default(), organization_id: merchant_context .get_merchant_account() .organization_id .clone(), processor_transaction_data, processor_refund_data: None, }; let refund = match db .insert_refund( refund_create_req, merchant_context.get_merchant_account().storage_scheme, ) .await { Ok(refund) => { Box::pin(schedule_refund_execution( state, refund.clone(), refund_type, merchant_context, payment_attempt, payment_intent, creds_identifier, split_refunds, )) .await? } Err(err) => { if err.current_context().is_db_unique_violation() { Err(errors::ApiErrorResponse::DuplicateRefundRequest)? } else { return Err(err) .change_context(errors::ApiErrorResponse::RefundNotFound) .attach_printable("Inserting Refund failed"); } } }; let unified_translated_message = if let (Some(unified_code), Some(unified_message)) = (refund.unified_code.clone(), refund.unified_message.clone()) { helpers::get_unified_translation( state, unified_code, unified_message.clone(), state.locale.to_string(), ) .await .or(Some(unified_message)) } else { refund.unified_message }; let refund = diesel_refund::Refund { unified_message: unified_translated_message, ..refund }; Ok(refund.foreign_into()) } // ********************************************** Refund list ********************************************** /// If payment-id is provided, lists all the refunds associated with that particular payment-id /// If payment-id is not provided, lists the refunds associated with that particular merchant - to the limit specified,if no limits given, it is 10 by default #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn refund_list( state: SessionState, merchant_context: domain::MerchantContext, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, req: api_models::refunds::RefundListRequest, ) -> RouterResponse<api_models::refunds::RefundListResponse> { let db = state.store; let limit = validator::validate_refund_list(req.limit)?; let offset = req.offset.unwrap_or_default(); let refund_list = db .filter_refund_by_constraints( merchant_context.get_merchant_account().get_id(), &(req.clone(), profile_id_list.clone()).try_into()?, merchant_context.get_merchant_account().storage_scheme, limit, offset, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let data: Vec<refunds::RefundResponse> = refund_list .into_iter() .map(ForeignInto::foreign_into) .collect(); let total_count = db .get_total_count_of_refunds( merchant_context.get_merchant_account().get_id(), &(req, profile_id_list).try_into()?, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; Ok(services::ApplicationResponse::Json( api_models::refunds::RefundListResponse { count: data.len(), total_count, data, }, )) } #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn refund_filter_list( state: SessionState, merchant_context: domain::MerchantContext, req: common_utils::types::TimeRange, ) -> RouterResponse<api_models::refunds::RefundListMetaData> { let db = state.store; let filter_list = db .filter_refund_by_meta_constraints( merchant_context.get_merchant_account().get_id(), &req, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; Ok(services::ApplicationResponse::Json(filter_list)) } #[instrument(skip_all)] pub async fn refund_retrieve_core_with_internal_reference_id( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, refund_internal_request_id: String, force_sync: Option<bool>, ) -> RouterResult<diesel_refund::Refund> { let db = &*state.store; let merchant_id = merchant_context.get_merchant_account().get_id(); let refund = db .find_refund_by_internal_reference_id_merchant_id( &refund_internal_request_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let request = refunds::RefundsRetrieveRequest { refund_id: refund.refund_id.clone(), force_sync, merchant_connector_details: None, }; Box::pin(refund_retrieve_core( state.clone(), merchant_context, profile_id, request, refund, )) .await } #[instrument(skip_all)] pub async fn refund_retrieve_core_with_refund_id( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, request: refunds::RefundsRetrieveRequest, ) -> RouterResult<diesel_refund::Refund> { let refund_id = request.refund_id.clone(); let db = &*state.store; let merchant_id = merchant_context.get_merchant_account().get_id(); let refund = db .find_refund_by_merchant_id_refund_id( merchant_id, refund_id.as_str(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; Box::pin(refund_retrieve_core( state.clone(), merchant_context, profile_id, request, refund, )) .await } #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn refund_manual_update( state: SessionState, req: api_models::refunds::RefundManualUpdateRequest, ) -> RouterResponse<serde_json::Value> { let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &req.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, &req.merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) .attach_printable("Error while fetching the merchant_account by merchant_id")?; let refund = state .store .find_refund_by_merchant_id_refund_id( merchant_account.get_id(), &req.refund_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let refund_update = diesel_refund::RefundUpdate::ManualUpdate { refund_status: req.status.map(common_enums::RefundStatus::from), refund_error_message: req.error_message, refund_error_code: req.error_code, updated_by: merchant_account.storage_scheme.to_string(), }; state .store .update_refund( refund.to_owned(), refund_update, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while updating refund: refund_id: {}", refund.refund_id ) })?; Ok(services::ApplicationResponse::StatusOk) } #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn get_filters_for_refunds( state: SessionState, merchant_context: domain::MerchantContext, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, ) -> RouterResponse<api_models::refunds::RefundListFilters> { 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 connector_map = merchant_connector_accounts .into_iter() .filter_map(|merchant_connector_account| { merchant_connector_account .connector_label .clone() .map(|label| { let info = merchant_connector_account.to_merchant_connector_info(&label); (merchant_connector_account.connector_name, info) }) }) .fold( HashMap::new(), |mut map: HashMap<String, Vec<MerchantConnectorInfo>>, (connector_name, info)| { map.entry(connector_name).or_default().push(info); map }, ); Ok(services::ApplicationResponse::Json( api_models::refunds::RefundListFilters { connector: connector_map, currency: enums::Currency::iter().collect(), refund_status: enums::RefundStatus::iter().collect(), }, )) } #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn get_aggregates_for_refunds( state: SessionState, merchant_context: domain::MerchantContext, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: common_utils::types::TimeRange, ) -> RouterResponse<api_models::refunds::RefundAggregateResponse> { let db = state.store.as_ref(); let refund_status_with_count = db .get_refund_status_with_count( merchant_context.get_merchant_account().get_id(), profile_id_list, &time_range, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to find status count")?; let mut status_map: HashMap<enums::RefundStatus, i64> = refund_status_with_count.into_iter().collect(); for status in enums::RefundStatus::iter() { status_map.entry(status).or_default(); } Ok(services::ApplicationResponse::Json( api_models::refunds::RefundAggregateResponse { status_with_count: status_map, }, )) } impl ForeignFrom<diesel_refund::Refund> for api::RefundResponse { fn foreign_from(refund: diesel_refund::Refund) -> Self { let refund = refund; Self { payment_id: refund.payment_id, refund_id: refund.refund_id, amount: refund.refund_amount, currency: refund.currency.to_string(), reason: refund.refund_reason, status: refund.refund_status.foreign_into(), profile_id: refund.profile_id, metadata: refund.metadata, error_message: refund.refund_error_message, error_code: refund.refund_error_code, created_at: Some(refund.created_at), updated_at: Some(refund.modified_at), connector: refund.connector, merchant_connector_id: refund.merchant_connector_id, split_refunds: refund.split_refunds, unified_code: refund.unified_code, unified_message: refund.unified_message, issuer_error_code: refund.issuer_error_code, issuer_error_message: refund.issuer_error_message, } } } // ********************************************** PROCESS TRACKER ********************************************** #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn schedule_refund_execution( state: &SessionState, refund: diesel_refund::Refund, refund_type: api_models::refunds::RefundType, merchant_context: &domain::MerchantContext, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, creds_identifier: Option<String>, split_refunds: Option<SplitRefundsRequest>, ) -> RouterResult<diesel_refund::Refund> { // refunds::RefundResponse> { let db = &*state.store; let runner = storage::ProcessTrackerRunner::RefundWorkflowRouter; let task = "EXECUTE_REFUND"; let task_id = format!("{runner}_{task}_{}", refund.internal_reference_id); let refund_process = db .find_process_by_id(&task_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to find the process id")?; let result = match refund.refund_status { enums::RefundStatus::Pending | enums::RefundStatus::ManualReview => { match (refund.sent_to_gateway, refund_process) { (false, None) => { // Execute the refund task based on refund_type match refund_type { api_models::refunds::RefundType::Scheduled => { add_refund_execute_task(db, &refund, runner) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("Failed while pushing refund execute task to scheduler, refund_id: {}", refund.refund_id))?; Ok(refund) } api_models::refunds::RefundType::Instant => { let update_refund = Box::pin(trigger_refund_to_gateway( state, &refund, merchant_context, payment_attempt, payment_intent, creds_identifier, split_refunds, )) .await; match update_refund { Ok(updated_refund_data) => { add_refund_sync_task(db, &updated_refund_data, runner) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!( "Failed while pushing refund sync task in scheduler: refund_id: {}", refund.refund_id ))?; Ok(updated_refund_data) } Err(err) => Err(err), } } } } _ => { // Sync the refund for status check //[#300]: return refund status response match refund_type { api_models::refunds::RefundType::Scheduled => { add_refund_sync_task(db, &refund, runner) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("Failed while pushing refund sync task in scheduler: refund_id: {}", refund.refund_id))?; Ok(refund) } api_models::refunds::RefundType::Instant => { // [#255]: This is not possible in schedule_refund_execution as it will always be scheduled // sync_refund_with_gateway(data, &refund).await Ok(refund) } } } } } // [#255]: This is not allowed to be otherwise or all _ => Ok(refund), }?; Ok(result) } #[instrument(skip_all)] pub async fn sync_refund_with_gateway_workflow( state: &SessionState, refund_tracker: &storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { let key_manager_state = &state.into(); let refund_core = serde_json::from_value::<diesel_refund::RefundCoreWorkflow>( refund_tracker.tracking_data.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "unable to convert into refund_core {:?}", refund_tracker.tracking_data ) })?; let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &refund_core.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await?; let merchant_account = state .store .find_merchant_account_by_merchant_id( key_manager_state, &refund_core.merchant_id, &key_store, ) .await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), key_store.clone(), ))); let response = Box::pin(refund_retrieve_core_with_internal_reference_id( state.clone(), merchant_context, None, refund_core.refund_internal_reference_id, Some(true), )) .await?; let terminal_status = [ enums::RefundStatus::Success, enums::RefundStatus::Failure, enums::RefundStatus::TransactionFailure, ]; match response.refund_status { status if terminal_status.contains(&status) => { state .store .as_scheduler() .finish_process_with_business_status( refund_tracker.clone(), business_status::COMPLETED_BY_PT, ) .await? } _ => { _ = retry_refund_sync_task( &*state.store, response.connector, response.merchant_id, refund_tracker.to_owned(), ) .await?; } } Ok(()) } /// Schedule the task for refund retry /// /// Returns bool which indicates whether this was the last refund retry or not pub async fn retry_refund_sync_task( db: &dyn db::StorageInterface, connector: String, merchant_id: common_utils::id_type::MerchantId, pt: storage::ProcessTracker, ) -> Result<bool, sch_errors::ProcessTrackerError> { let schedule_time = get_refund_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count + 1) .await?; match schedule_time { Some(s_time) => { db.as_scheduler().retry_process(pt, s_time).await?; Ok(false) } None => { db.as_scheduler() .finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED) .await?; Ok(true) } } } #[instrument(skip_all)] pub async fn start_refund_workflow( state: &SessionState, refund_tracker: &storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { match refund_tracker.name.as_deref() { Some("EXECUTE_REFUND") => { Box::pin(trigger_refund_execute_workflow(state, refund_tracker)).await } Some("SYNC_REFUND") => { Box::pin(sync_refund_with_gateway_workflow(state, refund_tracker)).await } _ => Err(errors::ProcessTrackerError::JobNotFound), } } #[instrument(skip_all)] pub async fn trigger_refund_execute_workflow( state: &SessionState, refund_tracker: &storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { let db = &*state.store; let refund_core = serde_json::from_value::<diesel_refund::RefundCoreWorkflow>( refund_tracker.tracking_data.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "unable to convert into refund_core {:?}", refund_tracker.tracking_data ) })?; let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &refund_core.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await?; let merchant_account = db .find_merchant_account_by_merchant_id( key_manager_state, &refund_core.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), key_store.clone(), ))); let refund = db .find_refund_by_internal_reference_id_merchant_id( &refund_core.refund_internal_reference_id, &refund_core.merchant_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; match (&refund.sent_to_gateway, &refund.refund_status) { (false, enums::RefundStatus::Pending) => { let merchant_account = db .find_merchant_account_by_merchant_id( key_manager_state, &refund.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let payment_attempt = db .find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &refund.connector_transaction_id, &refund_core.payment_id, &refund.merchant_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(state.into()), &payment_attempt.payment_id, &refund.merchant_id, &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let split_refunds = core_utils::get_split_refunds(SplitRefundInput { split_payment_request: payment_intent.split_payments.clone(), payment_charges: payment_attempt.charges.clone(), charge_id: payment_attempt.charge_id.clone(), refund_request: refund.split_refunds.clone(), })?; //trigger refund request to gateway let updated_refund = Box::pin(trigger_refund_to_gateway( state, &refund, &merchant_context, &payment_attempt, &payment_intent, None, split_refunds, )) .await?; add_refund_sync_task( db, &updated_refund, storage::ProcessTrackerRunner::RefundWorkflowRouter, ) .await?; } (true, enums::RefundStatus::Pending) => { // create sync task add_refund_sync_task( db, &refund, storage::ProcessTrackerRunner::RefundWorkflowRouter, ) .await?; } (_, _) => { //mark task as finished db.as_scheduler() .finish_process_with_business_status( refund_tracker.clone(), business_status::COMPLETED_BY_PT, ) .await?; } }; Ok(()) } #[instrument] pub fn refund_to_refund_core_workflow_model( refund: &diesel_refund::Refund, ) -> diesel_refund::RefundCoreWorkflow { diesel_refund::RefundCoreWorkflow { refund_internal_reference_id: refund.internal_reference_id.clone(), connector_transaction_id: refund.connector_transaction_id.clone(), merchant_id: refund.merchant_id.clone(), payment_id: refund.payment_id.clone(), processor_transaction_data: refund.processor_transaction_data.clone(), } } #[instrument(skip_all)] pub async fn add_refund_sync_task( db: &dyn db::StorageInterface, refund: &diesel_refund::Refund, runner: storage::ProcessTrackerRunner, ) -> RouterResult<storage::ProcessTracker> { let task = "SYNC_REFUND"; let process_tracker_id = format!("{runner}_{task}_{}", refund.internal_reference_id); let schedule_time = get_refund_sync_process_schedule_time(db, &refund.connector, &refund.merchant_id, 0) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch schedule time for refund sync process")? .unwrap_or_else(common_utils::date_time::now); let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund); let tag = ["REFUND"]; let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, refund_workflow_tracking_data, None, schedule_time, common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct refund sync process tracker task")?; let response = db .insert_process(process_tracker_entry) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest) .attach_printable_lazy(|| { format!( "Failed while inserting task in process_tracker: refund_id: {}", refund.refund_id ) })?; metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "Refund"))); Ok(response) } #[instrument(skip_all)] pub async fn add_refund_execute_task( db: &dyn db::StorageInterface, refund: &diesel_refund::Refund, runner: storage::ProcessTrackerRunner, ) -> RouterResult<storage::ProcessTracker> { let task = "EXECUTE_REFUND"; let process_tracker_id = format!("{runner}_{task}_{}", refund.internal_reference_id); let tag = ["REFUND"]; let schedule_time = common_utils::date_time::now(); let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund); let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, refund_workflow_tracking_data, None, schedule_time, common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct refund execute process tracker task")?; let response = db .insert_process(process_tracker_entry) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest) .attach_printable_lazy(|| { format!( "Failed while inserting task in process_tracker: refund_id: {}", refund.refund_id ) })?; Ok(response) } pub async fn get_refund_sync_process_schedule_time( db: &dyn db::StorageInterface, connector: &str, merchant_id: &common_utils::id_type::MerchantId, retry_count: i32, ) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { let mapping: common_utils::errors::CustomResult< process_data::ConnectorPTMapping, errors::StorageError, > = db .find_config_by_key(&format!("pt_mapping_refund_sync_{connector}")) .await .map(|value| value.config) .and_then(|config| { config .parse_struct("ConnectorPTMapping") .change_context(errors::StorageError::DeserializationFailed) }); let mapping = match mapping { Ok(x) => x, Err(err) => { logger::error!("Error: while getting connector mapping: {err:?}"); process_data::ConnectorPTMapping::default() } }; let time_delta = process_tracker_utils::get_schedule_time(mapping, merchant_id, retry_count); Ok(process_tracker_utils::get_time_from_delta(time_delta)) } </file>
{ "crate": "router", "file": "crates/router/src/core/refunds.rs", "files": null, "module": null, "num_files": null, "token_count": 12620 }
large_file_184426101716723485
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/conditional_config.rs </path> <file> #[cfg(feature = "v2")] use api_models::conditional_configs::DecisionManagerRequest; use api_models::conditional_configs::{ DecisionManager, DecisionManagerRecord, DecisionManagerResponse, }; use common_utils::ext_traits::StringExt; #[cfg(feature = "v2")] use common_utils::types::keymanager::KeyManagerState; use error_stack::ResultExt; use crate::{ core::errors::{self, RouterResponse}, routes::SessionState, services::api as service_api, types::domain, }; #[cfg(feature = "v2")] pub async fn upsert_conditional_config( state: SessionState, key_store: domain::MerchantKeyStore, request: DecisionManagerRequest, profile: domain::Profile, ) -> RouterResponse<common_types::payments::DecisionManagerRecord> { use common_utils::ext_traits::OptionExt; let key_manager_state: &KeyManagerState = &(&state).into(); let db = &*state.store; let name = request.name; let program = request.program; let timestamp = common_utils::date_time::now_unix_timestamp(); euclid::frontend::ast::lowering::lower_program(program.clone()) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid Request Data".to_string(), }) .attach_printable("The Request has an Invalid Comparison")?; let decision_manager_record = common_types::payments::DecisionManagerRecord { name, program, created_at: timestamp, }; let business_profile_update = domain::ProfileUpdate::DecisionManagerRecordUpdate { three_ds_decision_manager_config: decision_manager_record, }; let updated_profile = db .update_profile_by_profile_id( key_manager_state, &key_store, profile, business_profile_update, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update decision manager record in business profile")?; Ok(service_api::ApplicationResponse::Json( updated_profile .three_ds_decision_manager_config .clone() .get_required_value("three_ds_decision_manager_config") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to get updated decision manager record in business profile", )?, )) } #[cfg(feature = "v1")] pub async fn upsert_conditional_config( state: SessionState, merchant_context: domain::MerchantContext, request: DecisionManager, ) -> RouterResponse<DecisionManagerRecord> { use common_utils::ext_traits::{Encode, OptionExt, ValueExt}; use diesel_models::configs; use storage_impl::redis::cache; use super::routing::helpers::update_merchant_active_algorithm_ref; let db = state.store.as_ref(); let (name, prog) = match request { DecisionManager::DecisionManagerv0(ccr) => { let name = ccr.name; let prog = ccr .algorithm .get_required_value("algorithm") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "algorithm", }) .attach_printable("Algorithm for config not given")?; (name, prog) } DecisionManager::DecisionManagerv1(dmr) => { let name = dmr.name; let prog = dmr .program .get_required_value("program") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "program", }) .attach_printable("Program for config not given")?; (name, prog) } }; let timestamp = common_utils::date_time::now_unix_timestamp(); let mut algo_id: api_models::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 key = merchant_context .get_merchant_account() .get_id() .get_payment_config_routing_id(); let read_config_key = db.find_config_by_key(&key).await; euclid::frontend::ast::lowering::lower_program(prog.clone()) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid Request Data".to_string(), }) .attach_printable("The Request has an Invalid Comparison")?; match read_config_key { Ok(config) => { let previous_record: DecisionManagerRecord = config .config .parse_struct("DecisionManagerRecord") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("The Payment Config Key Not Found")?; let new_algo = DecisionManagerRecord { name: previous_record.name, program: prog, modified_at: timestamp, created_at: previous_record.created_at, }; let serialize_updated_str = new_algo .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to serialize config to string")?; let updated_config = configs::ConfigUpdate::Update { config: Some(serialize_updated_str), }; db.update_config_by_key(&key, updated_config) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error serializing the config")?; algo_id.update_conditional_config_id(key.clone()); let config_key = cache::CacheKind::DecisionManager(key.into()); update_merchant_active_algorithm_ref( &state, merchant_context.get_merchant_key_store(), config_key, algo_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref")?; Ok(service_api::ApplicationResponse::Json(new_algo)) } Err(e) if e.current_context().is_db_not_found() => { let new_rec = DecisionManagerRecord { name: name .get_required_value("name") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "name", }) .attach_printable("name of the config not found")?, program: prog, modified_at: timestamp, created_at: timestamp, }; let serialized_str = new_rec .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error serializing the config")?; let new_config = configs::ConfigNew { key: key.clone(), config: serialized_str, }; db.insert_config(new_config) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error fetching the config")?; algo_id.update_conditional_config_id(key.clone()); let config_key = cache::CacheKind::DecisionManager(key.into()); update_merchant_active_algorithm_ref( &state, merchant_context.get_merchant_key_store(), config_key, algo_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref")?; Ok(service_api::ApplicationResponse::Json(new_rec)) } Err(e) => Err(e) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error fetching payment config"), } } #[cfg(feature = "v2")] pub async fn delete_conditional_config( _state: SessionState, _merchant_context: domain::MerchantContext, ) -> RouterResponse<()> { todo!() } #[cfg(feature = "v1")] pub async fn delete_conditional_config( state: SessionState, merchant_context: domain::MerchantContext, ) -> RouterResponse<()> { use common_utils::ext_traits::ValueExt; use storage_impl::redis::cache; use super::routing::helpers::update_merchant_active_algorithm_ref; let db = state.store.as_ref(); let key = merchant_context .get_merchant_account() .get_id() .get_payment_config_routing_id(); let mut algo_id: api_models::routing::RoutingAlgorithmRef = merchant_context .get_merchant_account() .routing_algorithm .clone() .map(|value| value.parse_value("routing algorithm")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not decode the conditional_config algorithm")? .unwrap_or_default(); algo_id.config_algo_id = None; let config_key = cache::CacheKind::DecisionManager(key.clone().into()); update_merchant_active_algorithm_ref( &state, merchant_context.get_merchant_key_store(), config_key, algo_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update deleted algorithm ref")?; db.delete_config_by_key(&key) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to delete routing config from DB")?; Ok(service_api::ApplicationResponse::StatusOk) } #[cfg(feature = "v1")] pub async fn retrieve_conditional_config( state: SessionState, merchant_context: domain::MerchantContext, ) -> RouterResponse<DecisionManagerResponse> { let db = state.store.as_ref(); let algorithm_id = merchant_context .get_merchant_account() .get_id() .get_payment_config_routing_id(); let algo_config = db .find_config_by_key(&algorithm_id) .await .change_context(errors::ApiErrorResponse::ResourceIdNotFound) .attach_printable("The conditional config was not found in the DB")?; let record: DecisionManagerRecord = algo_config .config .parse_struct("ConditionalConfigRecord") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("The Conditional Config Record was not found")?; let response = DecisionManagerRecord { name: record.name, program: record.program, created_at: record.created_at, modified_at: record.modified_at, }; Ok(service_api::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] pub async fn retrieve_conditional_config( state: SessionState, key_store: domain::MerchantKeyStore, profile: domain::Profile, ) -> RouterResponse<common_types::payments::DecisionManagerResponse> { let db = state.store.as_ref(); let key_manager_state: &KeyManagerState = &(&state).into(); let profile_id = profile.get_id(); let record = profile .three_ds_decision_manager_config .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("The Conditional Config Record was not found")?; let response = common_types::payments::DecisionManagerRecord { name: record.name, program: record.program, created_at: record.created_at, }; Ok(service_api::ApplicationResponse::Json(response)) } </file>
{ "crate": "router", "file": "crates/router/src/core/conditional_config.rs", "files": null, "module": null, "num_files": null, "token_count": 2380 }
large_file_-2130670089573806363
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/refunds_v2.rs </path> <file> use std::{fmt::Debug, str::FromStr}; use api_models::{enums::Connector, refunds::RefundErrorDetails}; use common_utils::{id_type, types as common_utils_types}; use diesel_models::refund as diesel_refund; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ refunds::RefundListConstraints, router_data::{ErrorResponse, RouterData}, router_data_v2::RefundFlowData, }; use hyperswitch_interfaces::{ api::{Connector as ConnectorTrait, ConnectorIntegration}, connector_integration_v2::{ConnectorIntegrationV2, ConnectorV2}, integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject}, }; use router_env::{instrument, tracing}; use crate::{ consts, core::{ errors::{self, ConnectorErrorExt, StorageErrorExt}, payments::{self, access_token, helpers}, utils::{self as core_utils, refunds_validator}, }, db, logger, routes::{metrics, SessionState}, services, types::{ self, api::{self, refunds}, domain, storage::{self, enums}, transformers::{ForeignFrom, ForeignTryFrom}, }, utils, }; #[instrument(skip_all)] pub async fn refund_create_core( state: SessionState, merchant_context: domain::MerchantContext, req: refunds::RefundsCreateRequest, global_refund_id: id_type::GlobalRefundId, ) -> errors::RouterResponse<refunds::RefundResponse> { let db = &*state.store; let (payment_intent, payment_attempt, amount); payment_intent = db .find_payment_intent_by_id( &(&state).into(), &req.payment_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; utils::when( !(payment_intent.status == enums::IntentStatus::Succeeded || payment_intent.status == enums::IntentStatus::PartiallyCaptured), || { Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState { current_flow: "refund".into(), field_name: "status".into(), current_value: payment_intent.status.to_string(), states: "succeeded, partially_captured".to_string() }) .attach_printable("unable to refund for a unsuccessful payment intent")) }, )?; let captured_amount = payment_intent .amount_captured .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("amount captured is none in a successful payment")?; // Amount is not passed in request refer from payment intent. amount = req.amount.unwrap_or(captured_amount); utils::when(amount <= common_utils_types::MinorUnit::new(0), || { Err(report!(errors::ApiErrorResponse::InvalidDataFormat { field_name: "amount".to_string(), expected_format: "positive integer".to_string() }) .attach_printable("amount less than or equal to zero")) })?; payment_attempt = db .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( &(&state).into(), merchant_context.get_merchant_key_store(), &req.payment_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::SuccessfulPaymentNotFound)?; tracing::Span::current().record("global_refund_id", global_refund_id.get_string_repr()); let merchant_connector_details = req.merchant_connector_details.clone(); Box::pin(validate_and_create_refund( &state, &merchant_context, &payment_attempt, &payment_intent, amount, req, global_refund_id, merchant_connector_details, )) .await .map(services::ApplicationResponse::Json) } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn trigger_refund_to_gateway( state: &SessionState, refund: &diesel_refund::Refund, merchant_context: &domain::MerchantContext, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, ) -> errors::RouterResult<diesel_refund::Refund> { let db = &*state.store; let mca_id = payment_attempt.get_attempt_merchant_connector_account_id()?; let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let mca = db .find_merchant_connector_account_by_id( &state.into(), &mca_id, merchant_context.get_merchant_key_store(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch merchant connector account")?; metrics::REFUND_COUNT.add( 1, router_env::metric_attributes!(("connector", mca_id.get_string_repr().to_string())), ); let connector_enum = mca.connector_name; let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_enum.to_string(), api::GetToken::Connector, Some(mca_id.clone()), )?; refunds_validator::validate_for_valid_refunds(payment_attempt, connector.connector_name)?; let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(mca)); let mut router_data = core_utils::construct_refund_router_data( state, connector_enum, merchant_context, payment_intent, payment_attempt, refund, &merchant_connector_account, ) .await?; let add_access_token_result = Box::pin(access_token::add_access_token( state, &connector, merchant_context, &router_data, None, )) .await?; logger::debug!(refund_router_data=?router_data); access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &payments::CallConnectorAction::Trigger, ); let connector_response = Box::pin(call_connector_service( state, &connector, add_access_token_result, router_data, )) .await; let refund_update = get_refund_update_object( state, &connector, &storage_scheme, merchant_context, &connector_response, ) .await; let response = match refund_update { Some(refund_update) => state .store .update_refund( refund.to_owned(), refund_update, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while updating refund: refund_id: {}", refund.id.get_string_repr() ) })?, None => refund.to_owned(), }; // Implement outgoing webhooks here connector_response.to_refund_failed_response()?; Ok(response) } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn internal_trigger_refund_to_gateway( state: &SessionState, refund: &diesel_refund::Refund, merchant_context: &domain::MerchantContext, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, merchant_connector_details: common_types::domain::MerchantConnectorAuthDetails, ) -> errors::RouterResult<diesel_refund::Refund> { let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let routed_through = payment_attempt .connector .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve connector from payment attempt")?; metrics::REFUND_COUNT.add( 1, router_env::metric_attributes!(("connector", routed_through.clone())), ); let connector_enum = merchant_connector_details.connector_name; let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_enum.to_string(), api::GetToken::Connector, None, )?; refunds_validator::validate_for_valid_refunds(payment_attempt, connector.connector_name)?; let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails( merchant_connector_details, ); let mut router_data = core_utils::construct_refund_router_data( state, connector_enum, merchant_context, payment_intent, payment_attempt, refund, &merchant_connector_account, ) .await?; let add_access_token_result = Box::pin(access_token::add_access_token( state, &connector, merchant_context, &router_data, None, )) .await?; access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &payments::CallConnectorAction::Trigger, ); let connector_response = Box::pin(call_connector_service( state, &connector, add_access_token_result, router_data, )) .await; let refund_update = get_refund_update_object( state, &connector, &storage_scheme, merchant_context, &connector_response, ) .await; let response = match refund_update { Some(refund_update) => state .store .update_refund( refund.to_owned(), refund_update, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while updating refund: refund_id: {}", refund.id.get_string_repr() ) })?, None => refund.to_owned(), }; // Implement outgoing webhooks here connector_response.to_refund_failed_response()?; Ok(response) } async fn call_connector_service<F>( state: &SessionState, connector: &api::ConnectorData, add_access_token_result: types::AddAccessTokenResult, router_data: RouterData<F, types::RefundsData, types::RefundsResponseData>, ) -> Result< RouterData<F, types::RefundsData, types::RefundsResponseData>, error_stack::Report<errors::ConnectorError>, > where F: Debug + Clone + 'static, dyn ConnectorTrait + Sync: ConnectorIntegration<F, types::RefundsData, types::RefundsResponseData>, dyn ConnectorV2 + Sync: ConnectorIntegrationV2<F, RefundFlowData, types::RefundsData, types::RefundsResponseData>, { if !(add_access_token_result.connector_supports_access_token && router_data.access_token.is_none()) { let connector_integration: services::BoxedRefundConnectorIntegrationInterface< F, types::RefundsData, types::RefundsResponseData, > = connector.connector.get_connector_integration(); services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await } else { Ok(router_data) } } async fn get_refund_update_object( state: &SessionState, connector: &api::ConnectorData, storage_scheme: &enums::MerchantStorageScheme, merchant_context: &domain::MerchantContext, router_data_response: &Result< RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>, error_stack::Report<errors::ConnectorError>, >, ) -> Option<diesel_refund::RefundUpdate> { match router_data_response { // This error is related to connector implementation i.e if no implementation for refunds for that specific connector in HS or the connector does not support refund itself. Err(err) => get_connector_implementation_error_refund_update(err, *storage_scheme), Ok(response) => { let response = perform_integrity_check(response.clone()); match response.response.clone() { Err(err) => Some( get_connector_error_refund_update(state, err, connector, storage_scheme).await, ), Ok(refund_response_data) => Some(get_refund_update_for_refund_response_data( response, connector, refund_response_data, storage_scheme, merchant_context, )), } } } } fn get_connector_implementation_error_refund_update( error: &error_stack::Report<errors::ConnectorError>, storage_scheme: enums::MerchantStorageScheme, ) -> Option<diesel_refund::RefundUpdate> { Option::<diesel_refund::RefundUpdate>::foreign_from((error.current_context(), storage_scheme)) } async fn get_connector_error_refund_update( state: &SessionState, err: ErrorResponse, connector: &api::ConnectorData, storage_scheme: &enums::MerchantStorageScheme, ) -> diesel_refund::RefundUpdate { let unified_error_object = get_unified_error_and_message(state, &err, connector).await; diesel_refund::RefundUpdate::build_error_update_for_unified_error_and_message( unified_error_object, err.reason.or(Some(err.message)), Some(err.code), storage_scheme, ) } async fn get_unified_error_and_message( state: &SessionState, err: &ErrorResponse, connector: &api::ConnectorData, ) -> (String, String) { let option_gsm = helpers::get_gsm_record( state, Some(err.code.clone()), Some(err.message.clone()), connector.connector_name.to_string(), consts::REFUND_FLOW_STR.to_string(), ) .await; // Note: Some connectors do not have a separate list of refund errors // In such cases, the error codes and messages are stored under "Authorize" flow in GSM table // So we will have to fetch the GSM using Authorize flow in case GSM is not found using "refund_flow" let option_gsm = if option_gsm.is_none() { helpers::get_gsm_record( state, Some(err.code.clone()), Some(err.message.clone()), connector.connector_name.to_string(), consts::AUTHORIZE_FLOW_STR.to_string(), ) .await } else { option_gsm }; let gsm_unified_code = option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone()); let gsm_unified_message = option_gsm.and_then(|gsm| gsm.unified_message); match gsm_unified_code.as_ref().zip(gsm_unified_message.as_ref()) { Some((code, message)) => (code.to_owned(), message.to_owned()), None => ( consts::DEFAULT_UNIFIED_ERROR_CODE.to_owned(), consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_owned(), ), } } pub fn get_refund_update_for_refund_response_data( router_data: RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>, connector: &api::ConnectorData, refund_response_data: types::RefundsResponseData, storage_scheme: &enums::MerchantStorageScheme, merchant_context: &domain::MerchantContext, ) -> diesel_refund::RefundUpdate { // match on connector integrity checks match router_data.integrity_check.clone() { Err(err) => { let connector_refund_id = err .connector_transaction_id .map(common_utils_types::ConnectorTransactionId::from); metrics::INTEGRITY_CHECK_FAILED.add( 1, router_env::metric_attributes!( ("connector", connector.connector_name.to_string()), ( "merchant_id", merchant_context.get_merchant_account().get_id().clone() ), ), ); diesel_refund::RefundUpdate::build_error_update_for_integrity_check_failure( err.field_names, connector_refund_id, storage_scheme, ) } Ok(()) => { if refund_response_data.refund_status == diesel_models::enums::RefundStatus::Success { metrics::SUCCESSFUL_REFUND.add( 1, router_env::metric_attributes!(( "connector", connector.connector_name.to_string(), )), ) } let connector_refund_id = common_utils_types::ConnectorTransactionId::from( refund_response_data.connector_refund_id, ); diesel_refund::RefundUpdate::build_refund_update( connector_refund_id, refund_response_data.refund_status, storage_scheme, ) } } } pub fn perform_integrity_check<F>( mut router_data: RouterData<F, types::RefundsData, types::RefundsResponseData>, ) -> RouterData<F, types::RefundsData, types::RefundsResponseData> where F: Debug + Clone + 'static, { // Initiating Integrity check let integrity_result = check_refund_integrity(&router_data.request, &router_data.response); router_data.integrity_check = integrity_result; router_data } impl ForeignFrom<(&errors::ConnectorError, enums::MerchantStorageScheme)> for Option<diesel_refund::RefundUpdate> { fn foreign_from( (from, storage_scheme): (&errors::ConnectorError, enums::MerchantStorageScheme), ) -> Self { match from { errors::ConnectorError::NotImplemented(message) => { Some(diesel_refund::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::Failure), refund_error_message: Some( errors::ConnectorError::NotImplemented(message.to_owned()).to_string(), ), refund_error_code: Some("NOT_IMPLEMENTED".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: None, processor_refund_data: None, unified_code: None, unified_message: None, }) } errors::ConnectorError::NotSupported { message, connector } => { Some(diesel_refund::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::Failure), refund_error_message: Some(format!( "{message} is not supported by {connector}" )), refund_error_code: Some("NOT_SUPPORTED".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: None, processor_refund_data: None, unified_code: None, unified_message: None, }) } _ => None, } } } pub fn check_refund_integrity<T, Request>( request: &Request, refund_response_data: &Result<types::RefundsResponseData, ErrorResponse>, ) -> Result<(), common_utils::errors::IntegrityCheckError> where T: FlowIntegrity, Request: GetIntegrityObject<T> + CheckIntegrity<Request, T>, { let connector_refund_id = refund_response_data .as_ref() .map(|resp_data| resp_data.connector_refund_id.clone()) .ok(); request.check_integrity(request, connector_refund_id.to_owned()) } // ********************************************** REFUND UPDATE ********************************************** pub async fn refund_metadata_update_core( state: SessionState, merchant_account: domain::MerchantAccount, req: refunds::RefundMetadataUpdateRequest, global_refund_id: id_type::GlobalRefundId, ) -> errors::RouterResponse<refunds::RefundResponse> { let db = state.store.as_ref(); let refund = db .find_refund_by_id(&global_refund_id, merchant_account.storage_scheme) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let response = db .update_refund( refund, diesel_refund::RefundUpdate::MetadataAndReasonUpdate { metadata: req.metadata, reason: req.reason, updated_by: merchant_account.storage_scheme.to_string(), }, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Unable to update refund with refund_id: {}", global_refund_id.get_string_repr() ) })?; refunds::RefundResponse::foreign_try_from(response).map(services::ApplicationResponse::Json) } // ********************************************** REFUND SYNC ********************************************** #[instrument(skip_all)] pub async fn refund_retrieve_core_with_refund_id( state: SessionState, merchant_context: domain::MerchantContext, profile: domain::Profile, request: refunds::RefundsRetrieveRequest, ) -> errors::RouterResponse<refunds::RefundResponse> { let refund_id = request.refund_id.clone(); let db = &*state.store; let profile_id = profile.get_id().to_owned(); let refund = db .find_refund_by_id( &refund_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let response = Box::pin(refund_retrieve_core( state.clone(), merchant_context, Some(profile_id), request, refund, )) .await?; api::RefundResponse::foreign_try_from(response).map(services::ApplicationResponse::Json) } #[instrument(skip_all)] pub async fn refund_retrieve_core( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<id_type::ProfileId>, request: refunds::RefundsRetrieveRequest, refund: diesel_refund::Refund, ) -> errors::RouterResult<diesel_refund::Refund> { let db = &*state.store; let key_manager_state = &(&state).into(); core_utils::validate_profile_id_from_auth_layer(profile_id, &refund)?; let payment_id = &refund.payment_id; let payment_intent = db .find_payment_intent_by_id( key_manager_state, payment_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let active_attempt_id = payment_intent .active_attempt_id .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Active attempt id not found")?; let payment_attempt = db .find_payment_attempt_by_id( key_manager_state, merchant_context.get_merchant_key_store(), &active_attempt_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; let unified_translated_message = if let (Some(unified_code), Some(unified_message)) = (refund.unified_code.clone(), refund.unified_message.clone()) { helpers::get_unified_translation( &state, unified_code, unified_message.clone(), state.locale.to_string(), ) .await .or(Some(unified_message)) } else { refund.unified_message }; let refund = diesel_refund::Refund { unified_message: unified_translated_message, ..refund }; let response = if should_call_refund(&refund, request.force_sync.unwrap_or(false)) { if state.conf.merchant_id_auth.merchant_id_auth_enabled { let merchant_connector_details = match request.merchant_connector_details { Some(details) => details, None => { return Err(report!(errors::ApiErrorResponse::MissingRequiredField { field_name: "merchant_connector_details" })); } }; Box::pin(internal_sync_refund_with_gateway( &state, &merchant_context, &payment_attempt, &payment_intent, &refund, merchant_connector_details, )) .await } else { Box::pin(sync_refund_with_gateway( &state, &merchant_context, &payment_attempt, &payment_intent, &refund, )) .await } } else { Ok(refund) }?; Ok(response) } fn should_call_refund(refund: &diesel_models::refund::Refund, force_sync: bool) -> bool { // This implies, we cannot perform a refund sync & `the connector_refund_id` // doesn't exist let predicate1 = refund.connector_refund_id.is_some(); // This allows refund sync at connector level if force_sync is enabled, or // checks if the refund has failed let predicate2 = force_sync || !matches!( refund.refund_status, diesel_models::enums::RefundStatus::Failure | diesel_models::enums::RefundStatus::Success ); predicate1 && predicate2 } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn sync_refund_with_gateway( state: &SessionState, merchant_context: &domain::MerchantContext, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, refund: &diesel_refund::Refund, ) -> errors::RouterResult<diesel_refund::Refund> { let db = &*state.store; let connector_id = refund.connector.to_string(); let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_id, api::GetToken::Connector, payment_attempt.merchant_connector_id.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector")?; let mca_id = payment_attempt.get_attempt_merchant_connector_account_id()?; let mca = db .find_merchant_connector_account_by_id( &state.into(), &mca_id, merchant_context.get_merchant_key_store(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch merchant connector account")?; let connector_enum = mca.connector_name; let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(mca)); let mut router_data = core_utils::construct_refund_router_data::<api::RSync>( state, connector_enum, merchant_context, payment_intent, payment_attempt, refund, &merchant_connector_account, ) .await?; let add_access_token_result = Box::pin(access_token::add_access_token( state, &connector, merchant_context, &router_data, None, )) .await?; logger::debug!(refund_retrieve_router_data=?router_data); access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &payments::CallConnectorAction::Trigger, ); let connector_response = Box::pin(call_connector_service( state, &connector, add_access_token_result, router_data, )) .await .to_refund_failed_response()?; let connector_response = perform_integrity_check(connector_response); let refund_update = build_refund_update_for_rsync(&connector, merchant_context, connector_response); let response = state .store .update_refund( refund.to_owned(), refund_update, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound) .attach_printable_lazy(|| { format!( "Unable to update refund with refund_id: {}", refund.id.get_string_repr() ) })?; // Implement outgoing webhook here Ok(response) } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn internal_sync_refund_with_gateway( state: &SessionState, merchant_context: &domain::MerchantContext, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, refund: &diesel_refund::Refund, merchant_connector_details: common_types::domain::MerchantConnectorAuthDetails, ) -> errors::RouterResult<diesel_refund::Refund> { let connector_enum = merchant_connector_details.connector_name; let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_enum.to_string(), api::GetToken::Connector, None, )?; let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails( merchant_connector_details, ); let mut router_data = core_utils::construct_refund_router_data::<api::RSync>( state, connector_enum, merchant_context, payment_intent, payment_attempt, refund, &merchant_connector_account, ) .await?; let add_access_token_result = Box::pin(access_token::add_access_token( state, &connector, merchant_context, &router_data, None, )) .await?; access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &payments::CallConnectorAction::Trigger, ); let connector_response = Box::pin(call_connector_service( state, &connector, add_access_token_result, router_data, )) .await .to_refund_failed_response()?; let connector_response = perform_integrity_check(connector_response); let refund_update = build_refund_update_for_rsync(&connector, merchant_context, connector_response); let response = state .store .update_refund( refund.to_owned(), refund_update, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound) .attach_printable_lazy(|| { format!( "Unable to update refund with refund_id: {}", refund.id.get_string_repr() ) })?; // Implement outgoing webhook here Ok(response) } pub fn build_refund_update_for_rsync( connector: &api::ConnectorData, merchant_context: &domain::MerchantContext, router_data_response: RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>, ) -> diesel_refund::RefundUpdate { let merchant_account = merchant_context.get_merchant_account(); let storage_scheme = &merchant_context.get_merchant_account().storage_scheme; match router_data_response.response { Err(error_message) => { let refund_status = match error_message.status_code { // marking failure for 2xx because this is genuine refund failure 200..=299 => Some(enums::RefundStatus::Failure), _ => None, }; let refund_error_message = error_message.reason.or(Some(error_message.message)); let refund_error_code = Some(error_message.code); diesel_refund::RefundUpdate::build_error_update_for_refund_failure( refund_status, refund_error_message, refund_error_code, storage_scheme, ) } Ok(response) => match router_data_response.integrity_check.clone() { Err(err) => { metrics::INTEGRITY_CHECK_FAILED.add( 1, router_env::metric_attributes!( ("connector", connector.connector_name.to_string()), ("merchant_id", merchant_account.get_id().clone()), ), ); let connector_refund_id = err .connector_transaction_id .map(common_utils_types::ConnectorTransactionId::from); diesel_refund::RefundUpdate::build_error_update_for_integrity_check_failure( err.field_names, connector_refund_id, storage_scheme, ) } Ok(()) => { let connector_refund_id = common_utils_types::ConnectorTransactionId::from(response.connector_refund_id); diesel_refund::RefundUpdate::build_refund_update( connector_refund_id, response.refund_status, storage_scheme, ) } }, } } // ********************************************** Refund list ********************************************** /// If payment_id is provided, lists all the refunds associated with that particular payment_id /// If payment_id is not provided, lists the refunds associated with that particular merchant - to the limit specified,if no limits given, it is 10 by default #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn refund_list( state: SessionState, merchant_account: domain::MerchantAccount, profile: domain::Profile, req: refunds::RefundListRequest, ) -> errors::RouterResponse<refunds::RefundListResponse> { let db = state.store; let limit = refunds_validator::validate_refund_list(req.limit)?; let offset = req.offset.unwrap_or_default(); let refund_list = db .filter_refund_by_constraints( merchant_account.get_id(), RefundListConstraints::from((req.clone(), profile.clone())), merchant_account.storage_scheme, limit, offset, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let data: Vec<refunds::RefundResponse> = refund_list .into_iter() .map(refunds::RefundResponse::foreign_try_from) .collect::<Result<_, _>>()?; let total_count = db .get_total_count_of_refunds( merchant_account.get_id(), RefundListConstraints::from((req, profile)), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; Ok(services::ApplicationResponse::Json( api_models::refunds::RefundListResponse { count: data.len(), total_count, data, }, )) } // ********************************************** VALIDATIONS ********************************************** #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn validate_and_create_refund( state: &SessionState, merchant_context: &domain::MerchantContext, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, refund_amount: common_utils_types::MinorUnit, req: refunds::RefundsCreateRequest, global_refund_id: id_type::GlobalRefundId, merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, ) -> errors::RouterResult<refunds::RefundResponse> { let db = &*state.store; let refund_type = req.refund_type.unwrap_or_default(); let merchant_reference_id = req.merchant_reference_id; let predicate = req .merchant_id .as_ref() .map(|merchant_id| merchant_id != merchant_context.get_merchant_account().get_id()); utils::when(predicate.unwrap_or(false), || { Err(report!(errors::ApiErrorResponse::InvalidDataFormat { field_name: "merchant_id".to_string(), expected_format: "merchant_id from merchant account".to_string() }) .attach_printable("invalid merchant_id in request")) })?; let connector_payment_id = payment_attempt.clone().connector_payment_id.ok_or_else(|| { report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Transaction in invalid. Missing field \"connector_transaction_id\" in payment_attempt.") })?; let all_refunds = db .find_refund_by_merchant_id_connector_transaction_id( merchant_context.get_merchant_account().get_id(), &connector_payment_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let currency = payment_intent.amount_details.currency; refunds_validator::validate_payment_order_age( &payment_intent.created_at, state.conf.refund.max_age, ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "created_at".to_string(), expected_format: format!( "created_at not older than {} days", state.conf.refund.max_age, ), })?; let total_amount_captured = payment_intent .amount_captured .unwrap_or(payment_attempt.get_total_amount()); refunds_validator::validate_refund_amount( total_amount_captured.get_amount_as_i64(), &all_refunds, refund_amount.get_amount_as_i64(), ) .change_context(errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount)?; refunds_validator::validate_maximum_refund_against_payment_attempt( &all_refunds, state.conf.refund.max_attempts, ) .change_context(errors::ApiErrorResponse::MaximumRefundCount)?; let connector = payment_attempt .connector .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("No connector populated in payment attempt")?; let (connector_transaction_id, processor_transaction_data) = common_utils_types::ConnectorTransactionId::form_id_and_data(connector_payment_id); let refund_create_req = diesel_refund::RefundNew { id: global_refund_id, merchant_reference_id: merchant_reference_id.clone(), external_reference_id: Some(merchant_reference_id.get_string_repr().to_string()), payment_id: req.payment_id, merchant_id: merchant_context.get_merchant_account().get_id().clone(), connector_transaction_id, connector, refund_type: enums::RefundType::foreign_from(req.refund_type.unwrap_or_default()), total_amount: payment_attempt.get_total_amount(), refund_amount, currency, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), refund_status: enums::RefundStatus::Pending, metadata: req.metadata, description: req.reason.clone(), attempt_id: payment_attempt.id.clone(), refund_reason: req.reason, profile_id: Some(payment_intent.profile_id.clone()), connector_id: payment_attempt.merchant_connector_id.clone(), charges: None, split_refunds: None, connector_refund_id: None, sent_to_gateway: Default::default(), refund_arn: None, updated_by: Default::default(), organization_id: merchant_context .get_merchant_account() .organization_id .clone(), processor_transaction_data, processor_refund_data: None, }; let refund = match db .insert_refund( refund_create_req, merchant_context.get_merchant_account().storage_scheme, ) .await { Ok(refund) => { Box::pin(schedule_refund_execution( state, refund.clone(), refund_type, merchant_context, payment_attempt, payment_intent, merchant_connector_details, )) .await? } Err(err) => { if err.current_context().is_db_unique_violation() { Err(errors::ApiErrorResponse::DuplicateRefundRequest)? } else { Err(err) .change_context(errors::ApiErrorResponse::RefundFailed { data: None }) .attach_printable("Failed to insert refund")? } } }; let unified_translated_message = match (refund.unified_code.clone(), refund.unified_message.clone()) { (Some(unified_code), Some(unified_message)) => helpers::get_unified_translation( state, unified_code, unified_message.clone(), state.locale.to_string(), ) .await .or(Some(unified_message)), _ => refund.unified_message, }; let refund = diesel_refund::Refund { unified_message: unified_translated_message, ..refund }; api::RefundResponse::foreign_try_from(refund) } impl ForeignTryFrom<diesel_refund::Refund> for api::RefundResponse { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from(refund: diesel_refund::Refund) -> Result<Self, Self::Error> { let refund = refund; let profile_id = refund .profile_id .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Profile id not found")?; let connector_name = refund.connector; let connector = 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:?}") })?; Ok(Self { payment_id: refund.payment_id, id: refund.id.clone(), amount: refund.refund_amount, currency: refund.currency, reason: refund.refund_reason, status: refunds::RefundStatus::foreign_from(refund.refund_status), profile_id, metadata: refund.metadata, created_at: refund.created_at, updated_at: refund.modified_at, connector, merchant_connector_id: refund.connector_id, merchant_reference_id: Some(refund.merchant_reference_id), error_details: Some(RefundErrorDetails { code: refund.refund_error_code.unwrap_or_default(), message: refund.refund_error_message.unwrap_or_default(), }), connector_refund_reference_id: None, }) } } // ********************************************** PROCESS TRACKER ********************************************** #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn schedule_refund_execution( state: &SessionState, refund: diesel_refund::Refund, refund_type: api_models::refunds::RefundType, merchant_context: &domain::MerchantContext, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, ) -> errors::RouterResult<diesel_refund::Refund> { let db = &*state.store; let runner = storage::ProcessTrackerRunner::RefundWorkflowRouter; let task = "EXECUTE_REFUND"; let task_id = format!("{runner}_{task}_{}", refund.id.get_string_repr()); let refund_process = db .find_process_by_id(&task_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to find the process id")?; let result = match refund.refund_status { enums::RefundStatus::Pending | enums::RefundStatus::ManualReview => { match (refund.sent_to_gateway, refund_process) { (false, None) => { // Execute the refund task based on refund_type match refund_type { api_models::refunds::RefundType::Scheduled => { add_refund_execute_task(db, &refund, runner) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("Failed while pushing refund execute task to scheduler, refund_id: {}", refund.id.get_string_repr()))?; Ok(refund) } api_models::refunds::RefundType::Instant => { let update_refund = if state.conf.merchant_id_auth.merchant_id_auth_enabled { let merchant_connector_details = match merchant_connector_details { Some(details) => details, None => { return Err(report!( errors::ApiErrorResponse::MissingRequiredField { field_name: "merchant_connector_details" } )); } }; Box::pin(internal_trigger_refund_to_gateway( state, &refund, merchant_context, payment_attempt, payment_intent, merchant_connector_details, )) .await } else { Box::pin(trigger_refund_to_gateway( state, &refund, merchant_context, payment_attempt, payment_intent, )) .await }; match update_refund { Ok(updated_refund_data) => { add_refund_sync_task(db, &updated_refund_data, runner) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!( "Failed while pushing refund sync task in scheduler: refund_id: {}", refund.id.get_string_repr() ))?; Ok(updated_refund_data) } Err(err) => Err(err), } } } } _ => { // Sync the refund for status check //[#300]: return refund status response match refund_type { api_models::refunds::RefundType::Scheduled => { add_refund_sync_task(db, &refund, runner) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("Failed while pushing refund sync task in scheduler: refund_id: {}", refund.id.get_string_repr()))?; Ok(refund) } api_models::refunds::RefundType::Instant => { // [#255]: This is not possible in schedule_refund_execution as it will always be scheduled // sync_refund_with_gateway(data, &refund).await Ok(refund) } } } } } // [#255]: This is not allowed to be otherwise or all _ => Ok(refund), }?; Ok(result) } #[instrument] pub fn refund_to_refund_core_workflow_model( refund: &diesel_refund::Refund, ) -> diesel_refund::RefundCoreWorkflow { diesel_refund::RefundCoreWorkflow { refund_id: refund.id.clone(), connector_transaction_id: refund.connector_transaction_id.clone(), merchant_id: refund.merchant_id.clone(), payment_id: refund.payment_id.clone(), processor_transaction_data: refund.processor_transaction_data.clone(), } } #[instrument(skip_all)] pub async fn add_refund_execute_task( db: &dyn db::StorageInterface, refund: &diesel_refund::Refund, runner: storage::ProcessTrackerRunner, ) -> errors::RouterResult<storage::ProcessTracker> { let task = "EXECUTE_REFUND"; let process_tracker_id = format!("{runner}_{task}_{}", refund.id.get_string_repr()); let tag = ["REFUND"]; let schedule_time = common_utils::date_time::now(); let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund); let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, refund_workflow_tracking_data, None, schedule_time, common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct refund execute process tracker task")?; let response = db .insert_process(process_tracker_entry) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest) .attach_printable_lazy(|| { format!( "Failed while inserting task in process_tracker: refund_id: {}", refund.id.get_string_repr() ) })?; Ok(response) } #[instrument(skip_all)] pub async fn add_refund_sync_task( db: &dyn db::StorageInterface, refund: &diesel_refund::Refund, runner: storage::ProcessTrackerRunner, ) -> errors::RouterResult<storage::ProcessTracker> { let task = "SYNC_REFUND"; let process_tracker_id = format!("{runner}_{task}_{}", refund.id.get_string_repr()); let schedule_time = common_utils::date_time::now(); let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund); let tag = ["REFUND"]; let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, refund_workflow_tracking_data, None, schedule_time, common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct refund sync process tracker task")?; let response = db .insert_process(process_tracker_entry) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest) .attach_printable_lazy(|| { format!( "Failed while inserting task in process_tracker: refund_id: {}", refund.id.get_string_repr() ) })?; metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "Refund"))); Ok(response) } </file>
{ "crate": "router", "file": "crates/router/src/core/refunds_v2.rs", "files": null, "module": null, "num_files": null, "token_count": 10376 }
large_file_3138743839776528660
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/fraud_check.rs </path> <file> use std::fmt::Debug; use api_models::{self, enums as api_enums}; use common_enums::CaptureMethod; use error_stack::ResultExt; use masking::PeekInterface; use router_env::{ logger, tracing::{self, instrument}, }; use self::{ flows::{self as frm_flows, FeatureFrm}, types::{ self as frm_core_types, ConnectorDetailsCore, FrmConfigsObject, FrmData, FrmInfo, PaymentDetails, PaymentToFrmData, }, }; use super::errors::{ConnectorErrorExt, RouterResponse}; use crate::{ core::{ errors::{self, RouterResult}, payments::{self, flows::ConstructFlowSpecificData, operations::BoxedOperation}, }, db::StorageInterface, routes::{app::ReqState, SessionState}, services, types::{ self as oss_types, api::{ fraud_check as frm_api, routing::FrmRoutingAlgorithm, Connector, FraudCheckConnectorData, Fulfillment, }, domain, fraud_check as frm_types, storage::{ enums::{ AttemptStatus, FraudCheckLastStep, FraudCheckStatus, FraudCheckType, FrmSuggestion, IntentStatus, }, fraud_check::{FraudCheck, FraudCheckUpdate}, PaymentIntent, }, }, utils::ValueExt, }; pub mod flows; pub mod operation; pub mod types; #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn call_frm_service<D: Clone, F, Req, OperationData>( state: &SessionState, payment_data: &OperationData, frm_data: &mut FrmData, merchant_context: &domain::MerchantContext, customer: &Option<domain::Customer>, ) -> RouterResult<oss_types::RouterData<F, Req, frm_types::FraudCheckResponseData>> where F: Send + Clone, OperationData: payments::OperationSessionGetters<D> + Send + Sync + Clone, // To create connector flow specific interface data FrmData: ConstructFlowSpecificData<F, Req, frm_types::FraudCheckResponseData>, oss_types::RouterData<F, Req, frm_types::FraudCheckResponseData>: FeatureFrm<F, Req> + Send, // To construct connector flow specific api dyn Connector: services::api::ConnectorIntegration<F, Req, frm_types::FraudCheckResponseData>, { todo!() } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn call_frm_service<D: Clone, F, Req, OperationData>( state: &SessionState, payment_data: &OperationData, frm_data: &mut FrmData, merchant_context: &domain::MerchantContext, customer: &Option<domain::Customer>, ) -> RouterResult<oss_types::RouterData<F, Req, frm_types::FraudCheckResponseData>> where F: Send + Clone, OperationData: payments::OperationSessionGetters<D> + Send + Sync + Clone, // To create connector flow specific interface data FrmData: ConstructFlowSpecificData<F, Req, frm_types::FraudCheckResponseData>, oss_types::RouterData<F, Req, frm_types::FraudCheckResponseData>: FeatureFrm<F, Req> + Send, // To construct connector flow specific api dyn Connector: services::api::ConnectorIntegration<F, Req, frm_types::FraudCheckResponseData>, { let merchant_connector_account = payments::construct_profile_id_and_get_mca( state, merchant_context, payment_data, &frm_data.connector_details.connector_name, None, false, ) .await?; frm_data .payment_attempt .connector_transaction_id .clone_from(&payment_data.get_payment_attempt().connector_transaction_id); let mut router_data = frm_data .construct_router_data( state, &frm_data.connector_details.connector_name, merchant_context, customer, &merchant_connector_account, None, None, None, None, ) .await?; router_data.status = payment_data.get_payment_attempt().status; if matches!( frm_data.fraud_check.frm_transaction_type, FraudCheckType::PreFrm ) && matches!( frm_data.fraud_check.last_step, FraudCheckLastStep::CheckoutOrSale ) { frm_data.fraud_check.last_step = FraudCheckLastStep::TransactionOrRecordRefund } let connector = FraudCheckConnectorData::get_connector_by_name(&frm_data.connector_details.connector_name)?; let router_data_res = router_data .decide_frm_flows( state, &connector, payments::CallConnectorAction::Trigger, merchant_context, ) .await?; Ok(router_data_res) } #[cfg(feature = "v2")] pub async fn should_call_frm<F, D>( _merchant_context: &domain::MerchantContext, _payment_data: &D, _state: &SessionState, ) -> RouterResult<( bool, Option<FrmRoutingAlgorithm>, Option<common_utils::id_type::ProfileId>, Option<FrmConfigsObject>, )> where F: Send + Clone, D: payments::OperationSessionGetters<F> + Send + Sync + Clone, { // Frm routing algorithm is not present in the merchant account // it has to be fetched from the business profile todo!() } #[cfg(feature = "v1")] pub async fn should_call_frm<F, D>( merchant_context: &domain::MerchantContext, payment_data: &D, state: &SessionState, ) -> RouterResult<( bool, Option<FrmRoutingAlgorithm>, Option<common_utils::id_type::ProfileId>, Option<FrmConfigsObject>, )> where F: Send + Clone, D: payments::OperationSessionGetters<F> + Send + Sync + Clone, { use common_utils::ext_traits::OptionExt; use masking::ExposeInterface; let db = &*state.store; match merchant_context .get_merchant_account() .frm_routing_algorithm .clone() { Some(frm_routing_algorithm_value) => { let frm_routing_algorithm_struct: FrmRoutingAlgorithm = frm_routing_algorithm_value .clone() .parse_value("FrmRoutingAlgorithm") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "frm_routing_algorithm", }) .attach_printable("Data field not found in frm_routing_algorithm")?; 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 = "v1")] let merchant_connector_account_from_db_option = db .find_merchant_connector_account_by_profile_id_connector_name( &state.into(), &profile_id, &frm_routing_algorithm_struct.data, merchant_context.get_merchant_key_store(), ) .await .map_err(|error| { logger::error!( "{:?}", error.change_context( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_context .get_merchant_account() .get_id() .get_string_repr() .to_owned(), } ) ) }) .ok(); let enabled_merchant_connector_account_from_db_option = merchant_connector_account_from_db_option.and_then(|mca| { if mca.disabled.unwrap_or(false) { logger::info!("No eligible connector found for FRM"); None } else { Some(mca) } }); #[cfg(feature = "v2")] let merchant_connector_account_from_db_option: Option< domain::MerchantConnectorAccount, > = { let _ = key_store; let _ = frm_routing_algorithm_struct; let _ = profile_id; todo!() }; match enabled_merchant_connector_account_from_db_option { Some(merchant_connector_account_from_db) => { let frm_configs_option = merchant_connector_account_from_db .frm_configs .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "frm_configs", }) .ok(); match frm_configs_option { Some(frm_configs_value) => { let frm_configs_struct: Vec<api_models::admin::FrmConfigs> = frm_configs_value .into_iter() .map(|config| { config .expose() .parse_value("FrmConfigs") .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "frm_configs".to_string(), expected_format: r#"[{ "gateway": "stripe", "payment_methods": [{ "payment_method": "card","flow": "post"}]}]"#.to_string(), }) }) .collect::<Result<Vec<_>, _>>()?; let mut is_frm_connector_enabled = false; let mut is_frm_pm_enabled = false; let connector = payment_data.get_payment_attempt().connector.clone(); let filtered_frm_config = frm_configs_struct .iter() .filter(|frm_config| match (&connector, &frm_config.gateway) { (Some(current_connector), Some(configured_connector)) => { let is_enabled = *current_connector == configured_connector.to_string(); if is_enabled { is_frm_connector_enabled = true; } is_enabled } (None, _) | (_, None) => true, }) .collect::<Vec<_>>(); let filtered_payment_methods = filtered_frm_config .iter() .map(|frm_config| { let filtered_frm_config_by_pm = frm_config .payment_methods .iter() .filter(|frm_config_pm| { match ( payment_data.get_payment_attempt().payment_method, frm_config_pm.payment_method, ) { ( Some(current_pm), Some(configured_connector_pm), ) => { let is_enabled = current_pm.to_string() == configured_connector_pm.to_string(); if is_enabled { is_frm_pm_enabled = true; } is_enabled } (None, _) | (_, None) => true, } }) .collect::<Vec<_>>(); filtered_frm_config_by_pm }) .collect::<Vec<_>>() .concat(); let is_frm_enabled = is_frm_connector_enabled && is_frm_pm_enabled; logger::debug!( "is_frm_connector_enabled {:?}, is_frm_pm_enabled: {:?}, is_frm_enabled :{:?}", is_frm_connector_enabled, is_frm_pm_enabled, is_frm_enabled ); // filtered_frm_config... // Panic Safety: we are first checking if the object is present... only if present, we try to fetch index 0 let frm_configs_object = FrmConfigsObject { frm_enabled_gateway: filtered_frm_config .first() .and_then(|c| c.gateway), frm_enabled_pm: filtered_payment_methods .first() .and_then(|pm| pm.payment_method), // flow type should be consumed from payment_method.flow. To provide backward compatibility, if we don't find it there, we consume it from payment_method.payment_method_types[0].flow_type. frm_preferred_flow_type: filtered_payment_methods .first() .and_then(|pm| pm.flow.clone()) .or(filtered_payment_methods.first().and_then(|pm| { pm.payment_method_types.as_ref().and_then(|pmt| { pmt.first().map(|pmts| pmts.flow.clone()) }) })) .ok_or(errors::ApiErrorResponse::InvalidDataFormat { field_name: "frm_configs".to_string(), expected_format: r#"[{ "gateway": "stripe", "payment_methods": [{ "payment_method": "card","flow": "post"}]}]"#.to_string(), })?, }; logger::debug!( "frm_routing_configs: {:?} {:?} {:?} {:?}", frm_routing_algorithm_struct, profile_id, frm_configs_object, is_frm_enabled ); Ok(( is_frm_enabled, Some(frm_routing_algorithm_struct), Some(profile_id), Some(frm_configs_object), )) } None => { logger::error!("Cannot find frm_configs for FRM provider"); Ok((false, None, None, None)) } } } None => { logger::error!("Cannot find merchant connector account for FRM provider"); Ok((false, None, None, None)) } } } _ => Ok((false, None, None, None)), } } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn make_frm_data_and_fraud_check_operation<F, D>( _db: &dyn StorageInterface, state: &SessionState, merchant_context: &domain::MerchantContext, payment_data: D, frm_routing_algorithm: FrmRoutingAlgorithm, profile_id: common_utils::id_type::ProfileId, frm_configs: FrmConfigsObject, _customer: &Option<domain::Customer>, ) -> RouterResult<FrmInfo<F, D>> where F: Send + Clone, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync + Clone, { todo!() } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn make_frm_data_and_fraud_check_operation<F, D>( _db: &dyn StorageInterface, state: &SessionState, merchant_context: &domain::MerchantContext, payment_data: D, frm_routing_algorithm: FrmRoutingAlgorithm, profile_id: common_utils::id_type::ProfileId, frm_configs: FrmConfigsObject, _customer: &Option<domain::Customer>, ) -> RouterResult<FrmInfo<F, D>> where F: Send + Clone, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync + Clone, { let order_details = payment_data .get_payment_intent() .order_details .clone() .or_else(|| // when the order_details are present within the meta_data, we need to take those to support backward compatibility payment_data.get_payment_intent().metadata.clone().and_then(|meta| { let order_details = meta.get("order_details").to_owned(); order_details.map(|order| vec![masking::Secret::new(order.to_owned())]) })) .map(|order_details_value| { order_details_value .into_iter() .map(|data| { data.peek() .to_owned() .parse_value("OrderDetailsWithAmount") .attach_printable("unable to parse OrderDetailsWithAmount") }) .collect::<Result<Vec<_>, _>>() .unwrap_or_default() }); let frm_connector_details = ConnectorDetailsCore { connector_name: frm_routing_algorithm.data, profile_id, }; let payment_to_frm_data = PaymentToFrmData { amount: payment_data.get_amount(), payment_intent: payment_data.get_payment_intent().to_owned(), payment_attempt: payment_data.get_payment_attempt().to_owned(), merchant_account: merchant_context.get_merchant_account().to_owned(), address: payment_data.get_address().clone(), connector_details: frm_connector_details.clone(), order_details, frm_metadata: payment_data.get_payment_intent().frm_metadata.clone(), }; let fraud_check_operation: operation::BoxedFraudCheckOperation<F, D> = fraud_check_operation_by_frm_preferred_flow_type(frm_configs.frm_preferred_flow_type); let frm_data = fraud_check_operation .to_get_tracker()? .get_trackers(state, payment_to_frm_data, frm_connector_details) .await?; Ok(FrmInfo { fraud_check_operation, frm_data, suggested_action: None, }) } fn fraud_check_operation_by_frm_preferred_flow_type<F, D>( frm_preferred_flow_type: api_enums::FrmPreferredFlowTypes, ) -> operation::BoxedFraudCheckOperation<F, D> where operation::FraudCheckPost: operation::FraudCheckOperation<F, D>, operation::FraudCheckPre: operation::FraudCheckOperation<F, D>, { match frm_preferred_flow_type { api_enums::FrmPreferredFlowTypes::Pre => Box::new(operation::FraudCheckPre), api_enums::FrmPreferredFlowTypes::Post => Box::new(operation::FraudCheckPost), } } #[allow(clippy::too_many_arguments)] pub async fn pre_payment_frm_core<F, Req, D>( state: &SessionState, merchant_context: &domain::MerchantContext, payment_data: &mut D, frm_info: &mut FrmInfo<F, D>, frm_configs: FrmConfigsObject, customer: &Option<domain::Customer>, should_continue_transaction: &mut bool, should_continue_capture: &mut bool, operation: &BoxedOperation<'_, F, Req, D>, ) -> RouterResult<Option<FrmData>> where F: Send + Clone, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync + Clone, { let mut frm_data = None; if is_operation_allowed(operation) { frm_data = if let Some(frm_data) = &mut frm_info.frm_data { if matches!( frm_configs.frm_preferred_flow_type, api_enums::FrmPreferredFlowTypes::Pre ) { let fraud_check_operation = &mut frm_info.fraud_check_operation; let frm_router_data = fraud_check_operation .to_domain()? .pre_payment_frm(state, payment_data, frm_data, merchant_context, customer) .await?; let _router_data = call_frm_service::<F, frm_api::Transaction, _, D>( state, payment_data, frm_data, merchant_context, customer, ) .await?; let frm_data_updated = fraud_check_operation .to_update_tracker()? .update_tracker( state, merchant_context.get_merchant_key_store(), frm_data.clone(), payment_data, None, frm_router_data, ) .await?; let frm_fraud_check = frm_data_updated.fraud_check.clone(); payment_data.set_frm_message(frm_fraud_check.clone()); if matches!(frm_fraud_check.frm_status, FraudCheckStatus::Fraud) { *should_continue_transaction = false; frm_info.suggested_action = Some(FrmSuggestion::FrmCancelTransaction); } logger::debug!( "frm_updated_data: {:?} {:?}", frm_info.fraud_check_operation, frm_info.suggested_action ); Some(frm_data_updated) } else if matches!( frm_configs.frm_preferred_flow_type, api_enums::FrmPreferredFlowTypes::Post ) && !matches!( frm_data.fraud_check.frm_status, FraudCheckStatus::TransactionFailure // Incase of TransactionFailure frm status(No frm decision is taken by frm processor), if capture method is automatic we should not change it to manual. ) { *should_continue_capture = false; Some(frm_data.to_owned()) } else { Some(frm_data.to_owned()) } } else { None }; } Ok(frm_data) } #[allow(clippy::too_many_arguments)] pub async fn post_payment_frm_core<F, D>( state: &SessionState, req_state: ReqState, merchant_context: &domain::MerchantContext, payment_data: &mut D, frm_info: &mut FrmInfo<F, D>, frm_configs: FrmConfigsObject, customer: &Option<domain::Customer>, should_continue_capture: &mut bool, ) -> RouterResult<Option<FrmData>> where F: Send + Clone, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync + Clone, { if let Some(frm_data) = &mut frm_info.frm_data { // Allow the Post flow only if the payment is authorized, // this logic has to be removed if we are going to call /sale or /transaction after failed transaction let fraud_check_operation = &mut frm_info.fraud_check_operation; if payment_data.get_payment_attempt().status == AttemptStatus::Authorized { let frm_router_data_opt = fraud_check_operation .to_domain()? .post_payment_frm( state, req_state.clone(), payment_data, frm_data, merchant_context, customer, ) .await?; if let Some(frm_router_data) = frm_router_data_opt { let mut frm_data = fraud_check_operation .to_update_tracker()? .update_tracker( state, merchant_context.get_merchant_key_store(), frm_data.to_owned(), payment_data, None, frm_router_data.to_owned(), ) .await?; let frm_fraud_check = frm_data.fraud_check.clone(); let mut frm_suggestion = None; payment_data.set_frm_message(frm_fraud_check.clone()); if matches!(frm_fraud_check.frm_status, FraudCheckStatus::Fraud) { frm_info.suggested_action = Some(FrmSuggestion::FrmCancelTransaction); } else if matches!(frm_fraud_check.frm_status, FraudCheckStatus::ManualReview) { frm_info.suggested_action = Some(FrmSuggestion::FrmManualReview); } fraud_check_operation .to_domain()? .execute_post_tasks( state, req_state, &mut frm_data, merchant_context, frm_configs, &mut frm_suggestion, payment_data, customer, should_continue_capture, ) .await?; logger::debug!("frm_post_tasks_data: {:?}", frm_data); let updated_frm_data = fraud_check_operation .to_update_tracker()? .update_tracker( state, merchant_context.get_merchant_key_store(), frm_data.to_owned(), payment_data, frm_suggestion, frm_router_data.to_owned(), ) .await?; return Ok(Some(updated_frm_data)); } } Ok(Some(frm_data.to_owned())) } else { Ok(None) } } #[allow(clippy::too_many_arguments)] pub async fn call_frm_before_connector_call<F, Req, D>( operation: &BoxedOperation<'_, F, Req, D>, merchant_context: &domain::MerchantContext, payment_data: &mut D, state: &SessionState, frm_info: &mut Option<FrmInfo<F, D>>, customer: &Option<domain::Customer>, should_continue_transaction: &mut bool, should_continue_capture: &mut bool, ) -> RouterResult<Option<FrmConfigsObject>> where F: Send + Clone, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync + Clone, { let (is_frm_enabled, frm_routing_algorithm, frm_connector_label, frm_configs) = should_call_frm(merchant_context, payment_data, state).await?; if let Some((frm_routing_algorithm_val, profile_id)) = frm_routing_algorithm.zip(frm_connector_label) { if let Some(frm_configs) = frm_configs.clone() { let mut updated_frm_info = Box::pin(make_frm_data_and_fraud_check_operation( &*state.store, state, merchant_context, payment_data.to_owned(), frm_routing_algorithm_val, profile_id, frm_configs.clone(), customer, )) .await?; if is_frm_enabled { pre_payment_frm_core( state, merchant_context, payment_data, &mut updated_frm_info, frm_configs, customer, should_continue_transaction, should_continue_capture, operation, ) .await?; } *frm_info = Some(updated_frm_info); } } let fraud_capture_method = frm_info.as_ref().and_then(|frm_info| { frm_info .frm_data .as_ref() .map(|frm_data| frm_data.fraud_check.payment_capture_method) }); if matches!(fraud_capture_method, Some(Some(CaptureMethod::Manual))) && matches!( payment_data.get_payment_attempt().status, AttemptStatus::Unresolved ) { if let Some(info) = frm_info { info.suggested_action = Some(FrmSuggestion::FrmAuthorizeTransaction) }; *should_continue_transaction = false; logger::debug!( "skipping connector call since payment_capture_method is already {:?}", fraud_capture_method ); }; logger::debug!("frm_configs: {:?} {:?}", frm_configs, is_frm_enabled); Ok(frm_configs) } pub fn is_operation_allowed<Op: Debug>(operation: &Op) -> bool { ![ "PaymentSession", "PaymentApprove", "PaymentReject", "PaymentCapture", "PaymentsCancel", ] .contains(&format!("{operation:?}").as_str()) } #[cfg(feature = "v1")] impl From<PaymentToFrmData> for PaymentDetails { fn from(payment_data: PaymentToFrmData) -> Self { Self { amount: common_utils::types::MinorUnit::from(payment_data.amount).get_amount_as_i64(), currency: payment_data.payment_attempt.currency, payment_method: payment_data.payment_attempt.payment_method, payment_method_type: payment_data.payment_attempt.payment_method_type, refund_transaction_id: None, } } } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn frm_fulfillment_core( state: SessionState, merchant_context: domain::MerchantContext, req: frm_core_types::FrmFulfillmentRequest, ) -> RouterResponse<frm_types::FraudCheckResponseData> { let db = &*state.clone().store; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), &req.payment_id.clone(), 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)?; match payment_intent.status { IntentStatus::Succeeded => { let invalid_request_error = errors::ApiErrorResponse::InvalidRequestData { message: "no fraud check entry found for this payment_id".to_string(), }; let existing_fraud_check = db .find_fraud_check_by_payment_id_if_present( req.payment_id.clone(), merchant_context.get_merchant_account().get_id().clone(), ) .await .change_context(invalid_request_error.to_owned())?; match existing_fraud_check { Some(fraud_check) => { if (matches!(fraud_check.frm_transaction_type, FraudCheckType::PreFrm) && fraud_check.last_step == FraudCheckLastStep::TransactionOrRecordRefund) || (matches!(fraud_check.frm_transaction_type, FraudCheckType::PostFrm) && fraud_check.last_step == FraudCheckLastStep::CheckoutOrSale) { Box::pin(make_fulfillment_api_call( db, fraud_check, payment_intent, state, merchant_context, req, )) .await } else { Err(errors::ApiErrorResponse::PreconditionFailed {message:"Frm pre/post flow hasn't terminated yet, so fulfillment cannot be called".to_string(),}.into()) } } None => Err(invalid_request_error.into()), } } _ => Err(errors::ApiErrorResponse::PreconditionFailed { message: "Fulfillment can be performed only for succeeded payment".to_string(), } .into()), } } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn make_fulfillment_api_call( db: &dyn StorageInterface, fraud_check: FraudCheck, payment_intent: PaymentIntent, state: SessionState, merchant_context: domain::MerchantContext, req: frm_core_types::FrmFulfillmentRequest, ) -> RouterResponse<frm_types::FraudCheckResponseData> { 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 .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let connector_data = FraudCheckConnectorData::get_connector_by_name(&fraud_check.frm_name)?; let connector_integration: services::BoxedFrmConnectorIntegrationInterface< Fulfillment, frm_types::FraudCheckFulfillmentData, frm_types::FraudCheckResponseData, > = connector_data.connector.get_connector_integration(); let router_data = frm_flows::fulfillment_flow::construct_fulfillment_router_data( &state, &payment_intent, &payment_attempt, &merchant_context, fraud_check.frm_name.clone(), req, ) .await?; let response = services::execute_connector_processing_step( &state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_payment_failed_response()?; let fraud_check_copy = fraud_check.clone(); let fraud_check_update = FraudCheckUpdate::ResponseUpdate { frm_status: fraud_check.frm_status, frm_transaction_id: fraud_check.frm_transaction_id, frm_reason: fraud_check.frm_reason, frm_score: fraud_check.frm_score, metadata: fraud_check.metadata, modified_at: common_utils::date_time::now(), last_step: FraudCheckLastStep::Fulfillment, payment_capture_method: fraud_check.payment_capture_method, }; let _updated = db .update_fraud_check_response_with_attempt_id(fraud_check_copy, fraud_check_update) .await .map_err(|error| error.change_context(errors::ApiErrorResponse::PaymentNotFound))?; let fulfillment_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, })?; Ok(services::ApplicationResponse::Json(fulfillment_response)) } </file>
{ "crate": "router", "file": "crates/router/src/core/fraud_check.rs", "files": null, "module": null, "num_files": null, "token_count": 6686 }
large_file_7990626904350013738
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/cards_info.rs </path> <file> 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())) } </file>
{ "crate": "router", "file": "crates/router/src/core/cards_info.rs", "files": null, "module": null, "num_files": null, "token_count": 2579 }
large_file_1881616681875615632
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/revenue_recovery_data_backfill.rs </path> <file> use std::collections::HashMap; use api_models::revenue_recovery_data_backfill::{ BackfillError, ComprehensiveCardData, GetRedisDataQuery, RedisDataResponse, RedisKeyType, RevenueRecoveryBackfillRequest, RevenueRecoveryDataBackfillResponse, ScheduledAtUpdate, UnlockStatusResponse, UpdateTokenStatusRequest, UpdateTokenStatusResponse, }; use common_enums::{CardNetwork, PaymentMethodType}; use error_stack::ResultExt; use hyperswitch_domain_models::api::ApplicationResponse; use masking::ExposeInterface; use router_env::{instrument, logger}; use time::{format_description, Date}; use crate::{ connection, core::errors::{self, RouterResult}, routes::SessionState, types::{domain, storage}, }; pub async fn revenue_recovery_data_backfill( state: SessionState, records: Vec<RevenueRecoveryBackfillRequest>, cutoff_datetime: Option<time::PrimitiveDateTime>, ) -> RouterResult<ApplicationResponse<RevenueRecoveryDataBackfillResponse>> { let mut processed_records = 0; let mut failed_records = 0; // Process each record for record in records { match process_payment_method_record(&state, &record, cutoff_datetime).await { Ok(_) => { processed_records += 1; logger::info!( "Successfully processed record with connector customer id: {}", record.customer_id_resp ); } Err(e) => { failed_records += 1; logger::error!( "Payment method backfill failed: customer_id={}, error={}", record.customer_id_resp, e ); } } } let response = RevenueRecoveryDataBackfillResponse { processed_records, failed_records, }; logger::info!( "Revenue recovery data backfill completed - Processed: {}, Failed: {}", processed_records, failed_records ); Ok(ApplicationResponse::Json(response)) } pub async fn unlock_connector_customer_status( state: SessionState, connector_customer_id: String, ) -> RouterResult<ApplicationResponse<UnlockStatusResponse>> { let unlocked = storage::revenue_recovery_redis_operation:: RedisTokenManager::unlock_connector_customer_status(&state, &connector_customer_id) .await .map_err(|e| { logger::error!( "Failed to unlock connector customer status for {}: {}", connector_customer_id, e ); errors::ApiErrorResponse::InternalServerError })?; let response = UnlockStatusResponse { unlocked }; logger::info!( "Unlock operation completed for connector customer {}: {}", connector_customer_id, unlocked ); Ok(ApplicationResponse::Json(response)) } pub async fn get_redis_data( state: SessionState, connector_customer_id: &str, key_type: &RedisKeyType, ) -> RouterResult<ApplicationResponse<RedisDataResponse>> { match storage::revenue_recovery_redis_operation::RedisTokenManager::get_redis_key_data_raw( &state, connector_customer_id, key_type, ) .await { Ok((exists, ttl_seconds, data)) => { let response = RedisDataResponse { exists, ttl_seconds, data, }; logger::info!( "Retrieved Redis data for connector customer {}, exists={}, ttl={}", connector_customer_id, exists, ttl_seconds ); Ok(ApplicationResponse::Json(response)) } Err(error) => Err( error.change_context(errors::ApiErrorResponse::GenericNotFoundError { message: format!( "Redis data not found for connector customer id:- '{}'", connector_customer_id ), }), ), } } pub async fn redis_update_additional_details_for_revenue_recovery( state: SessionState, request: UpdateTokenStatusRequest, ) -> RouterResult<ApplicationResponse<UpdateTokenStatusResponse>> { // Get existing token let existing_token = storage::revenue_recovery_redis_operation:: RedisTokenManager::get_payment_processor_token_using_token_id( &state, &request.connector_customer_id, &request.payment_processor_token.clone().expose(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve existing token data")?; // Check if token exists let mut token_status = existing_token.ok_or_else(|| { error_stack::Report::new(errors::ApiErrorResponse::GenericNotFoundError { message: format!( "Token '{:?}' not found for connector customer id:- '{}'", request.payment_processor_token, request.connector_customer_id ), }) })?; let mut updated_fields = Vec::new(); // Handle scheduled_at update match request.scheduled_at { Some(ScheduledAtUpdate::SetToDateTime(dt)) => { // Field provided with datetime - update schedule_at field with datetime token_status.scheduled_at = Some(dt); updated_fields.push(format!("scheduled_at: {}", dt)); logger::info!( "Set scheduled_at to '{}' for token '{:?}'", dt, request.payment_processor_token ); } Some(ScheduledAtUpdate::SetToNull) => { // Field provided with "null" variable - set schedule_at field to null token_status.scheduled_at = None; updated_fields.push("scheduled_at: set to null".to_string()); logger::info!( "Set scheduled_at to null for token '{:?}'", request.payment_processor_token ); } None => { // Field not provided - we don't update schedule_at field logger::debug!("scheduled_at not provided in request - leaving unchanged"); } } // Update is_hard_decline field request.is_hard_decline.map(|is_hard_decline| { token_status.is_hard_decline = Some(is_hard_decline); updated_fields.push(format!("is_hard_decline: {}", is_hard_decline)); }); // Update error_code field request.error_code.as_ref().map(|error_code| { token_status.error_code = Some(error_code.clone()); updated_fields.push(format!("error_code: {}", error_code)); }); // Update Redis with modified token let mut tokens_map = HashMap::new(); tokens_map.insert( request.payment_processor_token.clone().expose(), token_status, ); storage::revenue_recovery_redis_operation:: RedisTokenManager::update_or_add_connector_customer_payment_processor_tokens( &state, &request.connector_customer_id, tokens_map, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update token status in Redis")?; let updated_fields_str = if updated_fields.is_empty() { "no fields were updated".to_string() } else { updated_fields.join(", ") }; let response = UpdateTokenStatusResponse { updated: true, message: format!( "Successfully updated token '{:?}' for connector customer '{}'. Updated fields: {}", request.payment_processor_token, request.connector_customer_id, updated_fields_str ), }; logger::info!( "Updated token status for connector customer {}, token: {:?}", request.connector_customer_id, request.payment_processor_token ); Ok(ApplicationResponse::Json(response)) } async fn process_payment_method_record( state: &SessionState, record: &RevenueRecoveryBackfillRequest, cutoff_datetime: Option<time::PrimitiveDateTime>, ) -> Result<(), BackfillError> { // Build comprehensive card data from CSV record let card_data = match build_comprehensive_card_data(record) { Ok(data) => data, Err(e) => { logger::warn!( "Failed to build card data for connector customer id: {}, error: {}.", record.customer_id_resp, e ); ComprehensiveCardData { card_type: Some("card".to_string()), card_exp_month: None, card_exp_year: None, card_network: None, card_issuer: None, card_issuing_country: None, daily_retry_history: None, } } }; logger::info!( "Built comprehensive card data - card_type: {:?}, exp_month: {}, exp_year: {}, network: {:?}, issuer: {:?}, country: {:?}, daily_retry_history: {:?}", card_data.card_type, card_data.card_exp_month.as_ref().map(|_| "**").unwrap_or("None"), card_data.card_exp_year.as_ref().map(|_| "**").unwrap_or("None"), card_data.card_network, card_data.card_issuer, card_data.card_issuing_country, card_data.daily_retry_history ); // Update Redis if token exists and is valid match record.token.as_ref().map(|token| token.clone().expose()) { Some(token) if !token.is_empty() => { logger::info!("Updating Redis for customer: {}", record.customer_id_resp,); storage::revenue_recovery_redis_operation:: RedisTokenManager::update_redis_token_with_comprehensive_card_data( state, &record.customer_id_resp, &token, &card_data, cutoff_datetime, ) .await .map_err(|e| { logger::error!("Redis update failed: {}", e); BackfillError::RedisError(format!("Token not found in Redis: {}", e)) })?; } _ => { logger::info!( "Skipping Redis update - token is missing, empty or 'nan': {:?}", record.token ); } } logger::info!( "Successfully completed processing for connector customer id: {}", record.customer_id_resp ); Ok(()) } /// Parse daily retry history from CSV fn parse_daily_retry_history(json_str: Option<&str>) -> Option<HashMap<Date, i32>> { match json_str { Some(json) if !json.is_empty() => { match serde_json::from_str::<HashMap<String, i32>>(json) { Ok(string_retry_history) => { // Convert string dates to Date objects let format = format_description::parse("[year]-[month]-[day]") .map_err(|e| { BackfillError::CsvParsingError(format!( "Invalid date format configuration: {}", e )) }) .ok()?; let mut date_retry_history = HashMap::new(); for (date_str, count) in string_retry_history { match Date::parse(&date_str, &format) { Ok(date) => { date_retry_history.insert(date, count); } Err(e) => { logger::warn!( "Failed to parse date '{}' in daily_retry_history: {}", date_str, e ); } } } logger::debug!( "Successfully parsed daily_retry_history with {} entries", date_retry_history.len() ); Some(date_retry_history) } Err(e) => { logger::warn!("Failed to parse daily_retry_history JSON '{}': {}", json, e); None } } } _ => { logger::debug!("Daily retry history not present or invalid, preserving existing data"); None } } } /// Build comprehensive card data from CSV record fn build_comprehensive_card_data( record: &RevenueRecoveryBackfillRequest, ) -> Result<ComprehensiveCardData, BackfillError> { // Extract card type from request, if not present then update it with 'card' let card_type = Some(determine_card_type(record.payment_method_sub_type)); // Parse expiration date let (exp_month, exp_year) = parse_expiration_date( record .exp_date .as_ref() .map(|date| date.clone().expose()) .as_deref(), )?; let card_exp_month = exp_month.map(masking::Secret::new); let card_exp_year = exp_year.map(masking::Secret::new); // Extract card network let card_network = record.card_network.clone(); // Extract card issuer and issuing country let card_issuer = record .clean_bank_name .as_ref() .filter(|value| !value.is_empty()) .cloned(); let card_issuing_country = record .country_name .as_ref() .filter(|value| !value.is_empty()) .cloned(); // Parse daily retry history let daily_retry_history = parse_daily_retry_history(record.daily_retry_history.as_deref()); Ok(ComprehensiveCardData { card_type, card_exp_month, card_exp_year, card_network, card_issuer, card_issuing_country, daily_retry_history, }) } /// Determine card type with fallback logic: payment_method_sub_type if not present -> "Card" fn determine_card_type(payment_method_sub_type: Option<PaymentMethodType>) -> String { match payment_method_sub_type { Some(card_type_enum) => { let mapped_type = match card_type_enum { PaymentMethodType::Credit => "credit".to_string(), PaymentMethodType::Debit => "debit".to_string(), PaymentMethodType::Card => "card".to_string(), // For all other payment method types, default to "card" _ => "card".to_string(), }; logger::debug!( "Using payment_method_sub_type enum '{:?}' -> '{}'", card_type_enum, mapped_type ); mapped_type } None => { logger::info!("In CSV payment_method_sub_type not present, defaulting to 'card'"); "card".to_string() } } } /// Parse expiration date fn parse_expiration_date( exp_date: Option<&str>, ) -> Result<(Option<String>, Option<String>), BackfillError> { exp_date .filter(|date| !date.is_empty()) .map(|date| { date.split_once('/') .ok_or_else(|| { logger::warn!("Unrecognized expiration date format (MM/YY expected)"); BackfillError::CsvParsingError( "Invalid expiration date format: expected MM/YY".to_string(), ) }) .and_then(|(month_part, year_part)| { let month = month_part.trim(); let year = year_part.trim(); logger::debug!("Split expiration date - parsing month and year"); // Validate and parse month let month_num = month.parse::<u8>().map_err(|_| { logger::warn!("Failed to parse month component in expiration date"); BackfillError::CsvParsingError( "Invalid month format in expiration date".to_string(), ) })?; if !(1..=12).contains(&month_num) { logger::warn!("Invalid month value in expiration date (not in range 1-12)"); return Err(BackfillError::CsvParsingError( "Invalid month value in expiration date".to_string(), )); } // Handle year conversion let final_year = match year.len() { 4 => &year[2..4], // Convert 4-digit to 2-digit 2 => year, // Already 2-digit _ => { logger::warn!( "Invalid year length in expiration date (expected 2 or 4 digits)" ); return Err(BackfillError::CsvParsingError( "Invalid year format in expiration date".to_string(), )); } }; logger::debug!("Successfully parsed expiration date... ",); Ok((Some(month.to_string()), Some(final_year.to_string()))) }) }) .unwrap_or_else(|| { logger::debug!("Empty expiration date, returning None"); Ok((None, None)) }) } </file>
{ "crate": "router", "file": "crates/router/src/core/revenue_recovery_data_backfill.rs", "files": null, "module": null, "num_files": null, "token_count": 3367 }
large_file_3681633180251526511
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/payout_link.rs </path> <file> use std::{ cmp::Ordering, collections::{HashMap, HashSet}, }; use actix_web::http::header; use api_models::payouts; use common_utils::{ ext_traits::{AsyncExt, Encode, OptionExt}, link_utils, types::{AmountConvertor, StringMajorUnitForConnector}, }; use diesel_models::PayoutLinkUpdate; use error_stack::ResultExt; use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData}; use super::errors::{RouterResponse, StorageErrorExt}; use crate::{ configs::settings::{PaymentMethodFilterKey, PaymentMethodFilters}, core::payouts::{helpers as payout_helpers, validator}, errors, routes::{app::StorageInterface, SessionState}, services, types::{api, domain, transformers::ForeignFrom}, utils::get_payout_attempt_id, }; #[cfg(feature = "v2")] pub async fn initiate_payout_link( _state: SessionState, _merchant_context: domain::MerchantContext, _req: payouts::PayoutLinkInitiateRequest, _request_headers: &header::HeaderMap, _locale: String, ) -> RouterResponse<services::GenericLinkFormData> { todo!() } #[cfg(feature = "v1")] pub async fn initiate_payout_link( state: SessionState, merchant_context: domain::MerchantContext, req: payouts::PayoutLinkInitiateRequest, request_headers: &header::HeaderMap, ) -> RouterResponse<services::GenericLinkFormData> { let db: &dyn StorageInterface = &*state.store; let merchant_id = merchant_context.get_merchant_account().get_id(); // Fetch payout let payout = db .find_payout_by_merchant_id_payout_id( merchant_id, &req.payout_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; let payout_attempt = db .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_id, &get_payout_attempt_id(payout.payout_id.get_string_repr(), payout.attempt_count), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; let payout_link_id = payout .payout_link_id .clone() .get_required_value("payout link id") .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "payout link not found".to_string(), })?; // Fetch payout link let payout_link = db .find_payout_link_by_link_id(&payout_link_id) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "payout link not found".to_string(), })?; let allowed_domains = validator::validate_payout_link_render_request_and_get_allowed_domains( request_headers, &payout_link, )?; // Check status and return form data accordingly let has_expired = common_utils::date_time::now() > payout_link.expiry; let status = payout_link.link_status.clone(); let link_data = payout_link.link_data.clone(); let default_config = &state.conf.generic_link.payout_link.clone(); let default_ui_config = default_config.ui_config.clone(); let ui_config_data = 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 (has_expired, &status) { // Send back generic expired page (true, _) | (_, &link_utils::PayoutLinkStatus::Invalidated) => { let expired_link_data = services::GenericExpiredLinkData { title: "Payout Expired".to_string(), message: "This payout link has expired.".to_string(), theme: link_data.ui_config.theme.unwrap_or(default_ui_config.theme), }; if status != link_utils::PayoutLinkStatus::Invalidated { let payout_link_update = PayoutLinkUpdate::StatusUpdate { link_status: link_utils::PayoutLinkStatus::Invalidated, }; db.update_payout_link(payout_link, payout_link_update) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout links in db")?; } Ok(services::ApplicationResponse::GenericLinkForm(Box::new( GenericLinks { allowed_domains, data: GenericLinksData::ExpiredLink(expired_link_data), locale: state.locale, }, ))) } // Initiate Payout link flow (_, link_utils::PayoutLinkStatus::Initiated) => { let customer_id = link_data.customer_id; let required_amount_type = StringMajorUnitForConnector; let amount = required_amount_type .convert(payout.amount, payout.destination_currency) .change_context(errors::ApiErrorResponse::CurrencyConversionFailed)?; // 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 - {}", customer_id, payout_link.link_id ), }) .attach_printable_lazy(|| format!("customer [{customer_id:?}] not found"))?; let address = payout .address_id .as_ref() .async_map(|address_id| async { db.find_address_by_address_id( &(&state).into(), address_id, merchant_context.get_merchant_key_store(), ) .await }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while fetching address [id - {:?}] for payout [id - {:?}]", payout.address_id, payout.payout_id ) })?; let enabled_payout_methods = filter_payout_methods(&state, &merchant_context, &payout, address.as_ref()).await?; // Fetch default enabled_payout_methods let mut default_enabled_payout_methods: Vec<link_utils::EnabledPaymentMethod> = vec![]; for (payment_method, payment_method_types) in default_config.enabled_payment_methods.clone().into_iter() { let enabled_payment_method = link_utils::EnabledPaymentMethod { payment_method, payment_method_types, }; default_enabled_payout_methods.push(enabled_payment_method); } let fallback_enabled_payout_methods = if enabled_payout_methods.is_empty() { &default_enabled_payout_methods } else { &enabled_payout_methods }; // Fetch enabled payout methods from the request. If not found, fetch the enabled payout methods from MCA, // If none are configured for merchant connector accounts, fetch them from the default enabled payout methods. let mut enabled_payment_methods = link_data .enabled_payment_methods .unwrap_or(fallback_enabled_payout_methods.to_vec()); // Sort payment methods (cards first) enabled_payment_methods.sort_by(|a, b| match (a.payment_method, b.payment_method) { (_, common_enums::PaymentMethod::Card) => Ordering::Greater, (common_enums::PaymentMethod::Card, _) => Ordering::Less, _ => Ordering::Equal, }); let required_field_override = api::RequiredFieldsOverrideRequest { billing: address .as_ref() .map(hyperswitch_domain_models::address::Address::from) .map(From::from), }; let enabled_payment_methods_with_required_fields = ForeignFrom::foreign_from(( &state.conf.payouts.required_fields, enabled_payment_methods.clone(), required_field_override, )); let js_data = payouts::PayoutLinkDetails { publishable_key: masking::Secret::new( merchant_context .get_merchant_account() .clone() .publishable_key, ), client_secret: link_data.client_secret.clone(), payout_link_id: payout_link.link_id, payout_id: payout_link.primary_reference.clone(), customer_id: customer.customer_id, session_expiry: payout_link.expiry, return_url: payout_link .return_url .as_ref() .map(|url| url::Url::parse(url)) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse payout status link's return URL")?, ui_config: ui_config_data, enabled_payment_methods, enabled_payment_methods_with_required_fields, amount, currency: payout.destination_currency, locale: state.locale.clone(), form_layout: link_data.form_layout, test_mode: link_data.test_mode.unwrap_or(false), }; let serialized_css_content = String::new(); let serialized_js_content = format!( "window.__PAYOUT_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, data: GenericLinksData::PayoutLink(generic_form_data), locale: state.locale.clone(), }, ))) } // Send back status page (_, link_utils::PayoutLinkStatus::Submitted) => { let translated_unified_message = payout_helpers::get_translated_unified_code_and_message( &state, payout_attempt.unified_code.as_ref(), payout_attempt.unified_message.as_ref(), &state.locale.clone(), ) .await?; let js_data = payouts::PayoutLinkStatusDetails { payout_link_id: payout_link.link_id, payout_id: payout_link.primary_reference.clone(), customer_id: link_data.customer_id, session_expiry: payout_link.expiry, return_url: payout_link .return_url .as_ref() .map(|url| url::Url::parse(url)) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse payout status link's return URL")?, status: payout.status, error_code: payout_attempt.unified_code, error_message: translated_unified_message, ui_config: ui_config_data, test_mode: link_data.test_mode.unwrap_or(false), }; let serialized_css_content = String::new(); let serialized_js_content = format!( "window.__PAYOUT_DETAILS = {}", js_data .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize PaymentMethodCollectLinkDetails")? ); 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, data: GenericLinksData::PayoutLinkStatus(generic_status_data), locale: state.locale.clone(), }, ))) } } } #[cfg(all(feature = "payouts", feature = "v1"))] pub async fn filter_payout_methods( state: &SessionState, merchant_context: &domain::MerchantContext, payout: &hyperswitch_domain_models::payouts::payouts::Payouts, address: Option<&domain::Address>, ) -> errors::RouterResult<Vec<link_utils::EnabledPaymentMethod>> { use masking::ExposeInterface; let db = &*state.store; let key_manager_state = &state.into(); //Fetch all merchant connector accounts let all_mcas = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( key_manager_state, merchant_context.get_merchant_account().get_id(), false, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; // Filter MCAs based on profile_id and connector_type let filtered_mcas = all_mcas.filter_based_on_profile_and_connector_type( &payout.profile_id, common_enums::ConnectorType::PayoutProcessor, ); let mut response: Vec<link_utils::EnabledPaymentMethod> = vec![]; let mut payment_method_list_hm: HashMap< common_enums::PaymentMethod, HashSet<common_enums::PaymentMethodType>, > = HashMap::new(); let mut bank_transfer_hash_set: HashSet<common_enums::PaymentMethodType> = HashSet::new(); let mut card_hash_set: HashSet<common_enums::PaymentMethodType> = HashSet::new(); let mut wallet_hash_set: HashSet<common_enums::PaymentMethodType> = HashSet::new(); let payout_filter_config = &state.conf.payout_method_filters.clone(); for mca in &filtered_mcas { let payout_methods = match &mca.payment_methods_enabled { Some(pm) => pm, None => continue, }; for payout_method in payout_methods.iter() { let parse_result = serde_json::from_value::<api_models::admin::PaymentMethodsEnabled>( payout_method.clone().expose(), ); if let Ok(payment_methods_enabled) = parse_result { let payment_method = payment_methods_enabled.payment_method; let payment_method_types = match payment_methods_enabled.payment_method_types { Some(payment_method_types) => payment_method_types, None => continue, }; let connector = mca.connector_name.clone(); let payout_filter = payout_filter_config.0.get(&connector); for request_payout_method_type in &payment_method_types { let currency_country_filter = check_currency_country_filters( payout_filter, request_payout_method_type, payout.destination_currency, address .as_ref() .and_then(|address| address.country) .as_ref(), )?; if currency_country_filter.unwrap_or(true) { match payment_method { common_enums::PaymentMethod::Card => { card_hash_set .insert(request_payout_method_type.payment_method_type); payment_method_list_hm .insert(payment_method, card_hash_set.clone()); } common_enums::PaymentMethod::Wallet => { wallet_hash_set .insert(request_payout_method_type.payment_method_type); payment_method_list_hm .insert(payment_method, wallet_hash_set.clone()); } common_enums::PaymentMethod::BankTransfer => { bank_transfer_hash_set .insert(request_payout_method_type.payment_method_type); payment_method_list_hm .insert(payment_method, bank_transfer_hash_set.clone()); } common_enums::PaymentMethod::CardRedirect | common_enums::PaymentMethod::PayLater | common_enums::PaymentMethod::BankRedirect | common_enums::PaymentMethod::Crypto | common_enums::PaymentMethod::BankDebit | common_enums::PaymentMethod::Reward | common_enums::PaymentMethod::RealTimePayment | common_enums::PaymentMethod::MobilePayment | common_enums::PaymentMethod::Upi | common_enums::PaymentMethod::Voucher | common_enums::PaymentMethod::OpenBanking | common_enums::PaymentMethod::GiftCard => continue, } } } } } } for (payment_method, payment_method_types) in payment_method_list_hm { if !payment_method_types.is_empty() { let enabled_payment_method = link_utils::EnabledPaymentMethod { payment_method, payment_method_types, }; response.push(enabled_payment_method); } } Ok(response) } pub fn check_currency_country_filters( payout_method_filter: Option<&PaymentMethodFilters>, request_payout_method_type: &api_models::payment_methods::RequestPaymentMethodTypes, currency: common_enums::Currency, country: Option<&common_enums::CountryAlpha2>, ) -> errors::RouterResult<Option<bool>> { if matches!( request_payout_method_type.payment_method_type, common_enums::PaymentMethodType::Credit | common_enums::PaymentMethodType::Debit ) { Ok(Some(true)) } else { let payout_method_type_filter = payout_method_filter.and_then(|payout_method_filter: &PaymentMethodFilters| { payout_method_filter .0 .get(&PaymentMethodFilterKey::PaymentMethodType( request_payout_method_type.payment_method_type, )) }); let country_filter = country.as_ref().and_then(|country| { payout_method_type_filter.and_then(|currency_country_filter| { currency_country_filter .country .as_ref() .map(|country_hash_set| country_hash_set.contains(country)) }) }); let currency_filter = payout_method_type_filter.and_then(|currency_country_filter| { currency_country_filter .currency .as_ref() .map(|currency_hash_set| currency_hash_set.contains(&currency)) }); Ok(currency_filter.or(country_filter)) } } </file>
{ "crate": "router", "file": "crates/router/src/core/payout_link.rs", "files": null, "module": null, "num_files": null, "token_count": 3845 }
large_file_7888237817904256020
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/connector_validation.rs </path> <file> use api_models::enums as api_enums; use common_utils::pii; use error_stack::ResultExt; use external_services::http_client::client; use masking::PeekInterface; use pm_auth::connector::plaid::transformers::PlaidAuthType; use crate::{core::errors, types, types::transformers::ForeignTryFrom}; pub struct ConnectorAuthTypeAndMetadataValidation<'a> { pub connector_name: &'a api_models::enums::Connector, pub auth_type: &'a types::ConnectorAuthType, pub connector_meta_data: &'a Option<pii::SecretSerdeValue>, } impl ConnectorAuthTypeAndMetadataValidation<'_> { pub fn validate_auth_and_metadata_type( &self, ) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> { let connector_auth_type_validation = ConnectorAuthTypeValidation { auth_type: self.auth_type, }; connector_auth_type_validation.validate_connector_auth_type()?; self.validate_auth_and_metadata_type_with_connector() .map_err(|err| match *err.current_context() { errors::ConnectorError::InvalidConnectorName => { err.change_context(errors::ApiErrorResponse::InvalidRequestData { message: "The connector name is invalid".to_string(), }) } errors::ConnectorError::InvalidConnectorConfig { config: field_name } => err .change_context(errors::ApiErrorResponse::InvalidRequestData { message: format!("The {field_name} is invalid"), }), errors::ConnectorError::FailedToObtainAuthType => { err.change_context(errors::ApiErrorResponse::InvalidRequestData { message: "The auth type is invalid for the connector".to_string(), }) } _ => err.change_context(errors::ApiErrorResponse::InvalidRequestData { message: "The request body is invalid".to_string(), }), }) } fn validate_auth_and_metadata_type_with_connector( &self, ) -> Result<(), error_stack::Report<errors::ConnectorError>> { use crate::connector::*; match self.connector_name { api_enums::Connector::Vgs => { vgs::transformers::VgsAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Adyenplatform => { adyenplatform::transformers::AdyenplatformAuthType::try_from(self.auth_type)?; Ok(()) } #[cfg(feature = "dummy_connector")] api_enums::Connector::DummyBillingConnector | api_enums::Connector::DummyConnector1 | api_enums::Connector::DummyConnector2 | api_enums::Connector::DummyConnector3 | api_enums::Connector::DummyConnector4 | api_enums::Connector::DummyConnector5 | api_enums::Connector::DummyConnector6 | api_enums::Connector::DummyConnector7 => { hyperswitch_connectors::connectors::dummyconnector::transformers::DummyConnectorAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Aci => { aci::transformers::AciAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Adyen => { adyen::transformers::AdyenAuthType::try_from(self.auth_type)?; adyen::transformers::AdyenConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Affirm => { affirm::transformers::AffirmAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Airwallex => { airwallex::transformers::AirwallexAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Amazonpay => { amazonpay::transformers::AmazonpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Archipel => { archipel::transformers::ArchipelAuthType::try_from(self.auth_type)?; archipel::transformers::ArchipelConfigData::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Authipay => { authipay::transformers::AuthipayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Authorizedotnet => { authorizedotnet::transformers::AuthorizedotnetAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Bankofamerica => { bankofamerica::transformers::BankOfAmericaAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Barclaycard => { barclaycard::transformers::BarclaycardAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Billwerk => { billwerk::transformers::BillwerkAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Bitpay => { bitpay::transformers::BitpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Bambora => { bambora::transformers::BamboraAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Bamboraapac => { bamboraapac::transformers::BamboraapacAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Boku => { boku::transformers::BokuAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Bluesnap => { bluesnap::transformers::BluesnapAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Blackhawknetwork => { blackhawknetwork::transformers::BlackhawknetworkAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Calida => { calida::transformers::CalidaAuthType::try_from(self.auth_type)?; calida::transformers::CalidaMetadataObject::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Braintree => { braintree::transformers::BraintreeAuthType::try_from(self.auth_type)?; braintree::transformers::BraintreeMeta::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Breadpay => { breadpay::transformers::BreadpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Cardinal => Ok(()), api_enums::Connector::Cashtocode => { cashtocode::transformers::CashtocodeAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Chargebee => { chargebee::transformers::ChargebeeAuthType::try_from(self.auth_type)?; chargebee::transformers::ChargebeeMetadata::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Celero => { celero::transformers::CeleroAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Checkbook => { checkbook::transformers::CheckbookAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Checkout => { checkout::transformers::CheckoutAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Coinbase => { coinbase::transformers::CoinbaseAuthType::try_from(self.auth_type)?; coinbase::transformers::CoinbaseConnectorMeta::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Coingate => { coingate::transformers::CoingateAuthType::try_from(self.auth_type)?; coingate::transformers::CoingateConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Cryptopay => { cryptopay::transformers::CryptopayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::CtpMastercard => Ok(()), api_enums::Connector::Custombilling => Ok(()), api_enums::Connector::CtpVisa => Ok(()), api_enums::Connector::Cybersource => { cybersource::transformers::CybersourceAuthType::try_from(self.auth_type)?; cybersource::transformers::CybersourceConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Datatrans => { datatrans::transformers::DatatransAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Deutschebank => { deutschebank::transformers::DeutschebankAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Digitalvirgo => { digitalvirgo::transformers::DigitalvirgoAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Dlocal => { dlocal::transformers::DlocalAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Dwolla => { dwolla::transformers::DwollaAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Ebanx => { ebanx::transformers::EbanxAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Elavon => { elavon::transformers::ElavonAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Facilitapay => { facilitapay::transformers::FacilitapayAuthType::try_from(self.auth_type)?; facilitapay::transformers::FacilitapayConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Fiserv => { fiserv::transformers::FiservAuthType::try_from(self.auth_type)?; fiserv::transformers::FiservSessionObject::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Fiservemea => { fiservemea::transformers::FiservemeaAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Fiuu => { fiuu::transformers::FiuuAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Flexiti => { flexiti::transformers::FlexitiAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Forte => { forte::transformers::ForteAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Getnet => { getnet::transformers::GetnetAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Gigadat => { gigadat::transformers::GigadatAuthType::try_from(self.auth_type)?; gigadat::transformers::GigadatConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Globalpay => { globalpay::transformers::GlobalpayAuthType::try_from(self.auth_type)?; globalpay::transformers::GlobalPayMeta::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Globepay => { globepay::transformers::GlobepayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Gocardless => { gocardless::transformers::GocardlessAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Gpayments => { gpayments::transformers::GpaymentsAuthType::try_from(self.auth_type)?; gpayments::transformers::GpaymentsMetaData::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Hipay => { hipay::transformers::HipayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Helcim => { helcim::transformers::HelcimAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::HyperswitchVault => { hyperswitch_vault::transformers::HyperswitchVaultAuthType::try_from( self.auth_type, )?; Ok(()) } api_enums::Connector::Iatapay => { iatapay::transformers::IatapayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Inespay => { inespay::transformers::InespayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Itaubank => { itaubank::transformers::ItaubankAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Jpmorgan => { jpmorgan::transformers::JpmorganAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Juspaythreedsserver => Ok(()), api_enums::Connector::Klarna => { klarna::transformers::KlarnaAuthType::try_from(self.auth_type)?; klarna::transformers::KlarnaConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Loonio => { loonio::transformers::LoonioAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Mifinity => { mifinity::transformers::MifinityAuthType::try_from(self.auth_type)?; mifinity::transformers::MifinityConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Mollie => { mollie::transformers::MollieAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Moneris => { moneris::transformers::MonerisAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Multisafepay => { multisafepay::transformers::MultisafepayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Netcetera => { netcetera::transformers::NetceteraAuthType::try_from(self.auth_type)?; netcetera::transformers::NetceteraMetaData::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Nexinets => { nexinets::transformers::NexinetsAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Nexixpay => { nexixpay::transformers::NexixpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Nmi => { nmi::transformers::NmiAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Nomupay => { nomupay::transformers::NomupayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Noon => { noon::transformers::NoonAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Nordea => { nordea::transformers::NordeaAuthType::try_from(self.auth_type)?; nordea::transformers::NordeaConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Novalnet => { novalnet::transformers::NovalnetAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Nuvei => { nuvei::transformers::NuveiAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Opennode => { opennode::transformers::OpennodeAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Paybox => { paybox::transformers::PayboxAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Payload => { payload::transformers::PayloadAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Payme => { payme::transformers::PaymeAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Paypal => { paypal::transformers::PaypalAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Paysafe => { paysafe::transformers::PaysafeAuthType::try_from(self.auth_type)?; paysafe::transformers::PaysafeConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Payone => { payone::transformers::PayoneAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Paystack => { paystack::transformers::PaystackAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Payu => { payu::transformers::PayuAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Peachpayments => { peachpayments::transformers::PeachpaymentsAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Placetopay => { placetopay::transformers::PlacetopayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Powertranz => { powertranz::transformers::PowertranzAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Prophetpay => { prophetpay::transformers::ProphetpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Rapyd => { rapyd::transformers::RapydAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Razorpay => { razorpay::transformers::RazorpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Recurly => { recurly::transformers::RecurlyAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Redsys => { redsys::transformers::RedsysAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Santander => { santander::transformers::SantanderAuthType::try_from(self.auth_type)?; santander::transformers::SantanderMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Shift4 => { shift4::transformers::Shift4AuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Silverflow => { silverflow::transformers::SilverflowAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Square => { square::transformers::SquareAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Stax => { stax::transformers::StaxAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Taxjar => { taxjar::transformers::TaxjarAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Stripe => { stripe::transformers::StripeAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Stripebilling => { stripebilling::transformers::StripebillingAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Tesouro => { tesouro::transformers::TesouroAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Trustpay => { trustpay::transformers::TrustpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Trustpayments => { trustpayments::transformers::TrustpaymentsAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Tokenex => { tokenex::transformers::TokenexAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Tokenio => { tokenio::transformers::TokenioAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Tsys => { tsys::transformers::TsysAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Volt => { volt::transformers::VoltAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Wellsfargo => { wellsfargo::transformers::WellsfargoAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Wise => { wise::transformers::WiseAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Worldline => { worldline::transformers::WorldlineAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Worldpay => { worldpay::transformers::WorldpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Worldpayvantiv => { worldpayvantiv::transformers::WorldpayvantivAuthType::try_from(self.auth_type)?; worldpayvantiv::transformers::WorldpayvantivMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Worldpayxml => { worldpayxml::transformers::WorldpayxmlAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Xendit => { xendit::transformers::XenditAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Zen => { zen::transformers::ZenAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Zsl => { zsl::transformers::ZslAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Signifyd => { signifyd::transformers::SignifydAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Riskified => { riskified::transformers::RiskifiedAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Plaid => { PlaidAuthType::foreign_try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Threedsecureio => { threedsecureio::transformers::ThreedsecureioAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Phonepe => { phonepe::transformers::PhonepeAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Paytm => { paytm::transformers::PaytmAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Finix => { finix::transformers::FinixAuthType::try_from(self.auth_type)?; Ok(()) } } } } struct ConnectorAuthTypeValidation<'a> { auth_type: &'a types::ConnectorAuthType, } impl ConnectorAuthTypeValidation<'_> { fn validate_connector_auth_type( &self, ) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> { let validate_non_empty_field = |field_value: &str, field_name: &str| { if field_value.trim().is_empty() { Err(errors::ApiErrorResponse::InvalidDataFormat { field_name: format!("connector_account_details.{field_name}"), expected_format: "a non empty String".to_string(), } .into()) } else { Ok(()) } }; match self.auth_type { hyperswitch_domain_models::router_data::ConnectorAuthType::TemporaryAuth => Ok(()), hyperswitch_domain_models::router_data::ConnectorAuthType::HeaderKey { api_key } => { validate_non_empty_field(api_key.peek(), "api_key") } hyperswitch_domain_models::router_data::ConnectorAuthType::BodyKey { api_key, key1, } => { validate_non_empty_field(api_key.peek(), "api_key")?; validate_non_empty_field(key1.peek(), "key1") } hyperswitch_domain_models::router_data::ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => { validate_non_empty_field(api_key.peek(), "api_key")?; validate_non_empty_field(key1.peek(), "key1")?; validate_non_empty_field(api_secret.peek(), "api_secret") } hyperswitch_domain_models::router_data::ConnectorAuthType::MultiAuthKey { api_key, key1, api_secret, key2, } => { validate_non_empty_field(api_key.peek(), "api_key")?; validate_non_empty_field(key1.peek(), "key1")?; validate_non_empty_field(api_secret.peek(), "api_secret")?; validate_non_empty_field(key2.peek(), "key2") } hyperswitch_domain_models::router_data::ConnectorAuthType::CurrencyAuthKey { auth_key_map, } => { if auth_key_map.is_empty() { Err(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_account_details.auth_key_map".to_string(), expected_format: "a non empty map".to_string(), } .into()) } else { Ok(()) } } hyperswitch_domain_models::router_data::ConnectorAuthType::CertificateAuth { certificate, private_key, } => { client::create_identity_from_certificate_and_key( certificate.to_owned(), private_key.to_owned(), ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_account_details.certificate or connector_account_details.private_key" .to_string(), expected_format: "a valid base64 encoded string of PEM encoded Certificate and Private Key" .to_string(), })?; Ok(()) } hyperswitch_domain_models::router_data::ConnectorAuthType::NoKey => Ok(()), } } } </file>
{ "crate": "router", "file": "crates/router/src/core/connector_validation.rs", "files": null, "module": null, "num_files": null, "token_count": 6053 }
large_file_1241565140882274840
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/disputes.rs </path> <file> use std::{collections::HashMap, ops::Deref, str::FromStr}; use api_models::{ admin::MerchantConnectorInfo, disputes as dispute_models, files as files_api_models, }; use common_utils::ext_traits::{Encode, ValueExt}; use error_stack::ResultExt; use router_env::{ instrument, logger, tracing::{self, Instrument}, }; use strum::IntoEnumIterator; pub mod transformers; use super::{ errors::{self, ConnectorErrorExt, RouterResponse, StorageErrorExt}, metrics, }; use crate::{ core::{files, payments, utils as core_utils, webhooks}, routes::{app::StorageInterface, metrics::TASKS_ADDED_COUNT, SessionState}, services, types::{ api::{self, disputes}, domain, storage::enums as storage_enums, transformers::{ForeignFrom, ForeignInto}, AcceptDisputeRequestData, AcceptDisputeResponse, DefendDisputeRequestData, DefendDisputeResponse, DisputePayload, DisputeSyncData, DisputeSyncResponse, FetchDisputesRequestData, FetchDisputesResponse, SubmitEvidenceRequestData, SubmitEvidenceResponse, }, workflows::process_dispute, }; pub(crate) fn should_call_connector_for_dispute_sync( force_sync: Option<bool>, dispute_status: storage_enums::DisputeStatus, ) -> bool { force_sync == Some(true) && matches!( dispute_status, common_enums::DisputeStatus::DisputeAccepted | common_enums::DisputeStatus::DisputeChallenged | common_enums::DisputeStatus::DisputeOpened ) } #[instrument(skip(state))] pub async fn retrieve_dispute( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, req: dispute_models::DisputeRetrieveRequest, ) -> RouterResponse<api_models::disputes::DisputeResponse> { let dispute = state .store .find_dispute_by_merchant_id_dispute_id( merchant_context.get_merchant_account().get_id(), &req.dispute_id, ) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: req.dispute_id, })?; core_utils::validate_profile_id_from_auth_layer(profile_id.clone(), &dispute)?; #[cfg(feature = "v1")] let dispute_response = if should_call_connector_for_dispute_sync(req.force_sync, dispute.dispute_status) { let db = &state.store; core_utils::validate_profile_id_from_auth_layer(profile_id.clone(), &dispute)?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), &dispute.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)?; let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &dispute.attempt_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &dispute.connector, api::GetToken::Connector, dispute.merchant_connector_id.clone(), )?; let connector_integration: services::BoxedDisputeConnectorIntegrationInterface< api::Dsync, DisputeSyncData, DisputeSyncResponse, > = connector_data.connector.get_connector_integration(); let router_data = core_utils::construct_dispute_sync_router_data( &state, &payment_intent, &payment_attempt, &merchant_context, &dispute, ) .await?; let response = services::execute_connector_processing_step( &state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_dispute_failed_response() .attach_printable("Failed while calling accept dispute connector api")?; let dispute_sync_response = response.response.map_err(|err| { errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: dispute.connector.clone(), status_code: err.status_code, reason: err.reason, } })?; let business_profile = state .store .find_business_profile_by_profile_id( &(&state).into(), merchant_context.get_merchant_key_store(), &payment_attempt.profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: payment_attempt.profile_id.get_string_repr().to_owned(), })?; update_dispute_data( &state, merchant_context, business_profile, Some(dispute.clone()), dispute_sync_response, payment_attempt, dispute.connector.as_str(), ) .await .attach_printable("Dispute update failed")? } else { api_models::disputes::DisputeResponse::foreign_from(dispute) }; #[cfg(not(feature = "v1"))] let dispute_response = api_models::disputes::DisputeResponse::foreign_from(dispute); Ok(services::ApplicationResponse::Json(dispute_response)) } #[instrument(skip(state))] pub async fn retrieve_disputes_list( state: SessionState, merchant_context: domain::MerchantContext, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, constraints: api_models::disputes::DisputeListGetConstraints, ) -> RouterResponse<Vec<api_models::disputes::DisputeResponse>> { let dispute_list_constraints = &(constraints.clone(), profile_id_list.clone()).try_into()?; let disputes = state .store .find_disputes_by_constraints( merchant_context.get_merchant_account().get_id(), dispute_list_constraints, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to retrieve disputes")?; let disputes_list = disputes .into_iter() .map(api_models::disputes::DisputeResponse::foreign_from) .collect(); Ok(services::ApplicationResponse::Json(disputes_list)) } #[cfg(feature = "v2")] #[instrument(skip(state))] pub async fn accept_dispute( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, req: disputes::DisputeId, ) -> RouterResponse<dispute_models::DisputeResponse> { todo!() } #[cfg(feature = "v1")] #[instrument(skip(state))] pub async fn get_filters_for_disputes( state: SessionState, merchant_context: domain::MerchantContext, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, ) -> RouterResponse<api_models::disputes::DisputeListFilters> { 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(error_stack::report!( errors::ApiErrorResponse::InternalServerError )) .attach_printable( "Failed to retrieve merchant connector accounts while fetching dispute list filters.", ); }; let connector_map = merchant_connector_accounts .into_iter() .filter_map(|merchant_connector_account| { merchant_connector_account .connector_label .clone() .map(|label| { let info = merchant_connector_account.to_merchant_connector_info(&label); (merchant_connector_account.connector_name, info) }) }) .fold( HashMap::new(), |mut map: HashMap<String, Vec<MerchantConnectorInfo>>, (connector_name, info)| { map.entry(connector_name).or_default().push(info); map }, ); Ok(services::ApplicationResponse::Json( api_models::disputes::DisputeListFilters { connector: connector_map, currency: storage_enums::Currency::iter().collect(), dispute_status: storage_enums::DisputeStatus::iter().collect(), dispute_stage: storage_enums::DisputeStage::iter().collect(), }, )) } #[cfg(feature = "v1")] #[instrument(skip(state))] pub async fn accept_dispute( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, req: disputes::DisputeId, ) -> RouterResponse<dispute_models::DisputeResponse> { let db = &state.store; let dispute = state .store .find_dispute_by_merchant_id_dispute_id( merchant_context.get_merchant_account().get_id(), &req.dispute_id, ) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: req.dispute_id, })?; core_utils::validate_profile_id_from_auth_layer(profile_id, &dispute)?; let dispute_id = dispute.dispute_id.clone(); common_utils::fp_utils::when( !core_utils::should_proceed_with_accept_dispute( dispute.dispute_stage, dispute.dispute_status, ), || { metrics::ACCEPT_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC.add(1, &[]); Err(errors::ApiErrorResponse::DisputeStatusValidationFailed { reason: format!( "This dispute cannot be accepted because the dispute is in {} stage and has {} status", dispute.dispute_stage, dispute.dispute_status ), }) }, )?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), &dispute.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)?; let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &dispute.attempt_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &dispute.connector, api::GetToken::Connector, dispute.merchant_connector_id.clone(), )?; let connector_integration: services::BoxedDisputeConnectorIntegrationInterface< api::Accept, AcceptDisputeRequestData, AcceptDisputeResponse, > = connector_data.connector.get_connector_integration(); let router_data = core_utils::construct_accept_dispute_router_data( &state, &payment_intent, &payment_attempt, &merchant_context, &dispute, ) .await?; let response = services::execute_connector_processing_step( &state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_dispute_failed_response() .attach_printable("Failed while calling accept dispute connector api")?; let accept_dispute_response = response .response .map_err(|err| errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: dispute.connector.clone(), status_code: err.status_code, reason: err.reason, })?; let update_dispute = diesel_models::dispute::DisputeUpdate::StatusUpdate { dispute_status: accept_dispute_response.dispute_status, connector_status: accept_dispute_response.connector_status.clone(), }; let updated_dispute = db .update_dispute(dispute.clone(), update_dispute) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("Unable to update dispute with dispute_id: {dispute_id}") })?; let dispute_response = api_models::disputes::DisputeResponse::foreign_from(updated_dispute); Ok(services::ApplicationResponse::Json(dispute_response)) } #[cfg(feature = "v2")] #[instrument(skip(state))] pub async fn submit_evidence( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, req: dispute_models::SubmitEvidenceRequest, ) -> RouterResponse<dispute_models::DisputeResponse> { todo!() } #[cfg(feature = "v1")] #[instrument(skip(state))] pub async fn submit_evidence( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, req: dispute_models::SubmitEvidenceRequest, ) -> RouterResponse<dispute_models::DisputeResponse> { let db = &state.store; let dispute = state .store .find_dispute_by_merchant_id_dispute_id( merchant_context.get_merchant_account().get_id(), &req.dispute_id, ) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: req.dispute_id.clone(), })?; core_utils::validate_profile_id_from_auth_layer(profile_id, &dispute)?; let dispute_id = dispute.dispute_id.clone(); common_utils::fp_utils::when( !core_utils::should_proceed_with_submit_evidence( dispute.dispute_stage, dispute.dispute_status, ), || { metrics::EVIDENCE_SUBMISSION_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC.add(1, &[]); Err(errors::ApiErrorResponse::DisputeStatusValidationFailed { reason: format!( "Evidence cannot be submitted because the dispute is in {} stage and has {} status", dispute.dispute_stage, dispute.dispute_status ), }) }, )?; let submit_evidence_request_data = transformers::get_evidence_request_data(&state, &merchant_context, req, &dispute).await?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), &dispute.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)?; let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &dispute.attempt_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &dispute.connector, api::GetToken::Connector, dispute.merchant_connector_id.clone(), )?; let connector_integration: services::BoxedDisputeConnectorIntegrationInterface< api::Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse, > = connector_data.connector.get_connector_integration(); let router_data = core_utils::construct_submit_evidence_router_data( &state, &payment_intent, &payment_attempt, &merchant_context, &dispute, submit_evidence_request_data, ) .await?; let response = services::execute_connector_processing_step( &state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_dispute_failed_response() .attach_printable("Failed while calling submit evidence connector api")?; let submit_evidence_response = response .response .map_err(|err| errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: dispute.connector.clone(), status_code: err.status_code, reason: err.reason, })?; //Defend Dispute Optionally if connector expects to defend / submit evidence in a separate api call let (dispute_status, connector_status) = if connector_data .connector_name .requires_defend_dispute() { let connector_integration_defend_dispute: services::BoxedDisputeConnectorIntegrationInterface< api::Defend, DefendDisputeRequestData, DefendDisputeResponse, > = connector_data.connector.get_connector_integration(); let defend_dispute_router_data = core_utils::construct_defend_dispute_router_data( &state, &payment_intent, &payment_attempt, &merchant_context, &dispute, ) .await?; let defend_response = services::execute_connector_processing_step( &state, connector_integration_defend_dispute, &defend_dispute_router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_dispute_failed_response() .attach_printable("Failed while calling defend dispute connector api")?; let defend_dispute_response = defend_response.response.map_err(|err| { errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: dispute.connector.clone(), status_code: err.status_code, reason: err.reason, } })?; ( defend_dispute_response.dispute_status, defend_dispute_response.connector_status, ) } else { ( submit_evidence_response.dispute_status, submit_evidence_response.connector_status, ) }; let update_dispute = diesel_models::dispute::DisputeUpdate::StatusUpdate { dispute_status, connector_status, }; let updated_dispute = db .update_dispute(dispute.clone(), update_dispute) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: dispute_id.to_owned(), }) .attach_printable_lazy(|| { format!("Unable to update dispute with dispute_id: {dispute_id}") })?; let dispute_response = api_models::disputes::DisputeResponse::foreign_from(updated_dispute); Ok(services::ApplicationResponse::Json(dispute_response)) } pub async fn attach_evidence( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, attach_evidence_request: api::AttachEvidenceRequest, ) -> RouterResponse<files_api_models::CreateFileResponse> { let db = &state.store; let dispute_id = attach_evidence_request .create_file_request .dispute_id .clone() .ok_or(errors::ApiErrorResponse::MissingDisputeId)?; let dispute = db .find_dispute_by_merchant_id_dispute_id( merchant_context.get_merchant_account().get_id(), &dispute_id, ) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: dispute_id.clone(), })?; core_utils::validate_profile_id_from_auth_layer(profile_id, &dispute)?; common_utils::fp_utils::when( !(dispute.dispute_stage == storage_enums::DisputeStage::Dispute && dispute.dispute_status == storage_enums::DisputeStatus::DisputeOpened), || { metrics::ATTACH_EVIDENCE_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC.add(1, &[]); Err(errors::ApiErrorResponse::DisputeStatusValidationFailed { reason: format!( "Evidence cannot be attached because the dispute is in {} stage and has {} status", dispute.dispute_stage, dispute.dispute_status ), }) }, )?; let create_file_response = Box::pin(files::files_create_core( state.clone(), merchant_context, attach_evidence_request.create_file_request, )) .await?; let file_id = match &create_file_response { services::ApplicationResponse::Json(res) => res.file_id.clone(), _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unexpected response received from files create core")?, }; let dispute_evidence: api::DisputeEvidence = dispute .evidence .clone() .parse_value("DisputeEvidence") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while parsing dispute evidence record")?; let updated_dispute_evidence = transformers::update_dispute_evidence( dispute_evidence, attach_evidence_request.evidence_type, file_id, ); let update_dispute = diesel_models::dispute::DisputeUpdate::EvidenceUpdate { evidence: updated_dispute_evidence .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while encoding dispute evidence")? .into(), }; db.update_dispute(dispute, update_dispute) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: dispute_id.to_owned(), }) .attach_printable_lazy(|| { format!("Unable to update dispute with dispute_id: {dispute_id}") })?; Ok(create_file_response) } #[instrument(skip(state))] pub async fn retrieve_dispute_evidence( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, req: disputes::DisputeId, ) -> RouterResponse<Vec<api_models::disputes::DisputeEvidenceBlock>> { let dispute = state .store .find_dispute_by_merchant_id_dispute_id( merchant_context.get_merchant_account().get_id(), &req.dispute_id, ) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: req.dispute_id, })?; core_utils::validate_profile_id_from_auth_layer(profile_id, &dispute)?; let dispute_evidence: api::DisputeEvidence = dispute .evidence .clone() .parse_value("DisputeEvidence") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while parsing dispute evidence record")?; let dispute_evidence_vec = transformers::get_dispute_evidence_vec(&state, merchant_context, dispute_evidence).await?; Ok(services::ApplicationResponse::Json(dispute_evidence_vec)) } pub async fn delete_evidence( state: SessionState, merchant_context: domain::MerchantContext, delete_evidence_request: dispute_models::DeleteEvidenceRequest, ) -> RouterResponse<serde_json::Value> { let dispute_id = delete_evidence_request.dispute_id.clone(); let dispute = state .store .find_dispute_by_merchant_id_dispute_id( merchant_context.get_merchant_account().get_id(), &dispute_id, ) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: dispute_id.clone(), })?; let dispute_evidence: api::DisputeEvidence = dispute .evidence .clone() .parse_value("DisputeEvidence") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while parsing dispute evidence record")?; let updated_dispute_evidence = transformers::delete_evidence_file(dispute_evidence, delete_evidence_request.evidence_type); let update_dispute = diesel_models::dispute::DisputeUpdate::EvidenceUpdate { evidence: updated_dispute_evidence .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while encoding dispute evidence")? .into(), }; state .store .update_dispute(dispute, update_dispute) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: dispute_id.to_owned(), }) .attach_printable_lazy(|| { format!("Unable to update dispute with dispute_id: {dispute_id}") })?; Ok(services::ApplicationResponse::StatusOk) } #[instrument(skip(state))] pub async fn get_aggregates_for_disputes( state: SessionState, merchant_context: domain::MerchantContext, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: common_utils::types::TimeRange, ) -> RouterResponse<dispute_models::DisputesAggregateResponse> { let db = state.store.as_ref(); let dispute_status_with_count = db .get_dispute_status_with_count( merchant_context.get_merchant_account().get_id(), profile_id_list, &time_range, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to retrieve disputes aggregate")?; let mut status_map: HashMap<storage_enums::DisputeStatus, i64> = dispute_status_with_count.into_iter().collect(); for status in storage_enums::DisputeStatus::iter() { status_map.entry(status).or_default(); } Ok(services::ApplicationResponse::Json( dispute_models::DisputesAggregateResponse { status_with_count: status_map, }, )) } #[cfg(feature = "v1")] #[instrument(skip(state))] pub async fn connector_sync_disputes( state: SessionState, merchant_context: domain::MerchantContext, merchant_connector_id: String, payload: disputes::DisputeFetchQueryData, ) -> RouterResponse<FetchDisputesResponse> { let connector_id = common_utils::id_type::MerchantConnectorAccountId::wrap(merchant_connector_id) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse merchant connector account id format")?; let format = time::format_description::parse("[year]-[month]-[day]T[hour]:[minute]:[second]") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse the date-time format")?; let created_from = time::PrimitiveDateTime::parse(&payload.fetch_from, &format) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "fetch_from".to_string(), expected_format: "YYYY-MM-DDTHH:MM:SS".to_string(), })?; let created_till = time::PrimitiveDateTime::parse(&payload.fetch_till, &format) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "fetch_till".to_string(), expected_format: "YYYY-MM-DDTHH:MM:SS".to_string(), })?; let fetch_dispute_request = FetchDisputesRequestData { created_from, created_till, }; Box::pin(fetch_disputes_from_connector( state, merchant_context, connector_id, fetch_dispute_request, )) .await } #[cfg(feature = "v1")] #[instrument(skip(state))] pub async fn fetch_disputes_from_connector( state: SessionState, merchant_context: domain::MerchantContext, merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, req: FetchDisputesRequestData, ) -> RouterResponse<FetchDisputesResponse> { let db = &*state.store; let key_manager_state = &(&state).into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let merchant_connector_account = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, 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(), })?; let connector_name = merchant_connector_account.connector_name.clone(); let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_name, api::GetToken::Connector, Some(merchant_connector_id.clone()), )?; let connector_integration: services::BoxedDisputeConnectorIntegrationInterface< api::Fetch, FetchDisputesRequestData, FetchDisputesResponse, > = connector_data.connector.get_connector_integration(); let router_data = core_utils::construct_dispute_list_router_data(&state, merchant_connector_account, req) .await?; let response = services::execute_connector_processing_step( &state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_dispute_failed_response() .attach_printable("Failed while calling accept dispute connector api")?; let fetch_dispute_response = response .response .map_err(|err| errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: connector_name.clone(), status_code: err.status_code, reason: err.reason, })?; for dispute in &fetch_dispute_response { // check if payment already exist let payment_attempt = webhooks::incoming::get_payment_attempt_from_object_reference_id( &state, dispute.object_reference_id.clone(), &merchant_context, ) .await; if payment_attempt.is_ok() { let schedule_time = process_dispute::get_sync_process_schedule_time( &*state.store, &connector_name, merchant_id, 0, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting process schedule time")?; let response = add_process_dispute_task_to_pt( db, &connector_name, dispute, merchant_id.clone(), schedule_time, ) .await; match response { Err(report) if report .downcast_ref::<errors::StorageError>() .is_some_and(|error| { matches!(error, errors::StorageError::DuplicateValue { .. }) }) => { Ok(()) } Ok(_) => Ok(()), Err(_) => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while adding task to process tracker"), }?; } else { router_env::logger::info!("Disputed payment does not exist in our records"); } } Ok(services::ApplicationResponse::Json(fetch_dispute_response)) } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn update_dispute_data( state: &SessionState, merchant_context: domain::MerchantContext, business_profile: domain::Profile, option_dispute: Option<diesel_models::dispute::Dispute>, dispute_details: DisputeSyncResponse, payment_attempt: domain::PaymentAttempt, connector_name: &str, ) -> errors::CustomResult<api_models::disputes::DisputeResponse, errors::ApiErrorResponse> { let dispute_data = DisputePayload::from(dispute_details.clone()); let dispute_object = webhooks::incoming::get_or_update_dispute_object( state.clone(), option_dispute, dispute_data, merchant_context.get_merchant_account().get_id(), &merchant_context.get_merchant_account().organization_id, &payment_attempt, dispute_details.dispute_status, &business_profile, connector_name, ) .await?; let disputes_response: dispute_models::DisputeResponse = dispute_object.clone().foreign_into(); let event_type: storage_enums::EventType = dispute_details.dispute_status.into(); Box::pin(webhooks::create_event_and_trigger_outgoing_webhook( state.clone(), merchant_context, business_profile, event_type, storage_enums::EventClass::Disputes, dispute_object.dispute_id.clone(), storage_enums::EventObjectType::DisputeDetails, api::OutgoingWebhookContent::DisputeDetails(Box::new(disputes_response.clone())), Some(dispute_object.created_at), )) .await?; Ok(disputes_response) } #[cfg(feature = "v1")] pub async fn add_process_dispute_task_to_pt( db: &dyn StorageInterface, connector_name: &str, dispute_payload: &DisputeSyncResponse, merchant_id: common_utils::id_type::MerchantId, schedule_time: Option<time::PrimitiveDateTime>, ) -> common_utils::errors::CustomResult<(), errors::StorageError> { match schedule_time { Some(time) => { TASKS_ADDED_COUNT.add( 1, router_env::metric_attributes!(("flow", "dispute_process")), ); let tracking_data = disputes::ProcessDisputePTData { connector_name: connector_name.to_string(), dispute_payload: dispute_payload.clone(), merchant_id: merchant_id.clone(), }; let runner = common_enums::ProcessTrackerRunner::ProcessDisputeWorkflow; let task = "DISPUTE_PROCESS"; let tag = ["PROCESS", "DISPUTE"]; let process_tracker_id = scheduler::utils::get_process_tracker_id( runner, task, &dispute_payload.connector_dispute_id.clone(), &merchant_id, ); let process_tracker_entry = diesel_models::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, tracking_data, None, time, common_types::consts::API_VERSION, ) .map_err(errors::StorageError::from)?; db.insert_process(process_tracker_entry).await?; Ok(()) } None => Ok(()), } } #[cfg(feature = "v1")] pub async fn add_dispute_list_task_to_pt( db: &dyn StorageInterface, connector_name: &str, merchant_id: common_utils::id_type::MerchantId, merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, profile_id: common_utils::id_type::ProfileId, fetch_request: FetchDisputesRequestData, ) -> common_utils::errors::CustomResult<(), errors::StorageError> { TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "dispute_list"))); let tracking_data = disputes::DisputeListPTData { connector_name: connector_name.to_string(), merchant_id: merchant_id.clone(), merchant_connector_id: merchant_connector_id.clone(), created_from: fetch_request.created_from, created_till: fetch_request.created_till, profile_id, }; let runner = common_enums::ProcessTrackerRunner::DisputeListWorkflow; let task = "DISPUTE_LIST"; let tag = ["LIST", "DISPUTE"]; let process_tracker_id = scheduler::utils::get_process_tracker_id_for_dispute_list( runner, &merchant_connector_id, fetch_request.created_from, &merchant_id, ); let process_tracker_entry = diesel_models::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, tracking_data, None, fetch_request.created_from, common_types::consts::API_VERSION, ) .map_err(errors::StorageError::from)?; db.insert_process(process_tracker_entry).await?; Ok(()) } #[cfg(feature = "v1")] pub async fn schedule_dispute_sync_task( state: &SessionState, business_profile: &domain::Profile, mca: &domain::MerchantConnectorAccount, ) -> common_utils::errors::CustomResult<(), errors::ApiErrorResponse> { let connector = api::enums::Connector::from_str(&mca.connector_name).change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "connector", }, )?; if core_utils::should_add_dispute_sync_task_to_pt(state, connector) { let offset_date_time = time::OffsetDateTime::now_utc(); let created_from = time::PrimitiveDateTime::new(offset_date_time.date(), offset_date_time.time()); let dispute_polling_interval = *business_profile .dispute_polling_interval .unwrap_or_default() .deref(); let created_till = created_from .checked_add(time::Duration::hours(i64::from(dispute_polling_interval))) .ok_or(errors::ApiErrorResponse::InternalServerError)?; let m_db = state.clone().store; let connector_name = mca.connector_name.clone(); let merchant_id = mca.merchant_id.clone(); let merchant_connector_id = mca.merchant_connector_id.clone(); let business_profile_id = business_profile.get_id().clone(); tokio::spawn( async move { add_dispute_list_task_to_pt( &*m_db, &connector_name, merchant_id.clone(), merchant_connector_id.clone(), business_profile_id, FetchDisputesRequestData { created_from, created_till, }, ) .await .map_err(|error| { logger::error!("Failed to add dispute list task to process tracker: {error}") }) } .in_current_span(), ); } Ok(()) } </file>
{ "crate": "router", "file": "crates/router/src/core/disputes.rs", "files": null, "module": null, "num_files": null, "token_count": 8119 }
large_file_-6578587953957268211
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/unified_authentication_service.rs </path> <file> pub mod types; use std::str::FromStr; pub mod utils; #[cfg(feature = "v1")] use api_models::authentication::{ AuthenticationEligibilityRequest, AuthenticationEligibilityResponse, AuthenticationSyncPostUpdateRequest, AuthenticationSyncRequest, AuthenticationSyncResponse, }; use api_models::{ authentication::{ AcquirerDetails, AuthenticationAuthenticateRequest, AuthenticationAuthenticateResponse, AuthenticationCreateRequest, AuthenticationResponse, }, payments, }; #[cfg(feature = "v1")] use common_utils::{ext_traits::ValueExt, types::keymanager::ToEncryptable}; use diesel_models::authentication::{Authentication, AuthenticationNew}; use error_stack::ResultExt; use hyperswitch_domain_models::{ errors::api_error_response::ApiErrorResponse, payment_method_data, router_request_types::{ authentication::{MessageCategory, PreAuthenticationData}, unified_authentication_service::{ AuthenticationInfo, PaymentDetails, ServiceSessionIds, ThreeDsMetaData, TransactionDetails, UasAuthenticationRequestData, UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, BrowserInformation, }, types::{ UasAuthenticationRouterData, UasPostAuthenticationRouterData, UasPreAuthenticationRouterData, }, }; use masking::{ExposeInterface, PeekInterface}; use super::{ errors::{RouterResponse, RouterResult}, payments::helpers::MerchantConnectorAccountType, }; use crate::{ consts, core::{ authentication::utils as auth_utils, errors::utils::StorageErrorExt, payments::helpers, unified_authentication_service::types::{ ClickToPay, ExternalAuthentication, UnifiedAuthenticationService, UNIFIED_AUTHENTICATION_SERVICE, }, utils as core_utils, }, db::domain, routes::SessionState, services::AuthFlow, types::{domain::types::AsyncLift, transformers::ForeignTryFrom}, }; #[cfg(feature = "v1")] #[async_trait::async_trait] impl UnifiedAuthenticationService for ClickToPay { fn get_pre_authentication_request_data( _payment_method_data: Option<&domain::PaymentMethodData>, service_details: Option<payments::CtpServiceDetails>, amount: common_utils::types::MinorUnit, currency: Option<common_enums::Currency>, merchant_details: Option<&hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails>, billing_address: Option<&hyperswitch_domain_models::address::Address>, acquirer_bin: Option<String>, acquirer_merchant_id: Option<String>, _payment_method_type: Option<common_enums::PaymentMethodType>, ) -> RouterResult<UasPreAuthenticationRequestData> { let domain_service_details = hyperswitch_domain_models::router_request_types::unified_authentication_service::CtpServiceDetails { service_session_ids: Some(ServiceSessionIds { merchant_transaction_id: service_details .as_ref() .and_then(|details| details.merchant_transaction_id.clone()), correlation_id: service_details .as_ref() .and_then(|details| details.correlation_id.clone()), x_src_flow_id: service_details .as_ref() .and_then(|details| details.x_src_flow_id.clone()), }), payment_details: None, }; let transaction_details = TransactionDetails { amount: Some(amount), currency, device_channel: None, message_category: None, }; let authentication_info = Some(AuthenticationInfo { authentication_type: None, authentication_reasons: None, consent_received: false, // This is not relevant in this flow so keeping it as false is_authenticated: false, // This is not relevant in this flow so keeping it as false locale: None, supported_card_brands: None, encrypted_payload: service_details .as_ref() .and_then(|details| details.encrypted_payload.clone()), }); Ok(UasPreAuthenticationRequestData { service_details: Some(domain_service_details), transaction_details: Some(transaction_details), payment_details: None, authentication_info, merchant_details: merchant_details.cloned(), billing_address: billing_address.cloned(), acquirer_bin, acquirer_merchant_id, }) } async fn pre_authentication( state: &SessionState, merchant_id: &common_utils::id_type::MerchantId, payment_id: Option<&common_utils::id_type::PaymentId>, payment_method_data: Option<&domain::PaymentMethodData>, payment_method_type: Option<common_enums::PaymentMethodType>, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, authentication_id: &common_utils::id_type::AuthenticationId, payment_method: common_enums::PaymentMethod, amount: common_utils::types::MinorUnit, currency: Option<common_enums::Currency>, service_details: Option<payments::CtpServiceDetails>, merchant_details: Option<&hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails>, billing_address: Option<&hyperswitch_domain_models::address::Address>, acquirer_bin: Option<String>, acquirer_merchant_id: Option<String>, ) -> RouterResult<UasPreAuthenticationRouterData> { let pre_authentication_data = Self::get_pre_authentication_request_data( payment_method_data, service_details, amount, currency, merchant_details, billing_address, acquirer_bin, acquirer_merchant_id, payment_method_type, )?; let pre_auth_router_data: UasPreAuthenticationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method, merchant_id.clone(), None, pre_authentication_data, merchant_connector_account, Some(authentication_id.to_owned()), payment_id.cloned(), )?; Box::pin(utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), pre_auth_router_data, )) .await } async fn post_authentication( state: &SessionState, _business_profile: &domain::Profile, payment_id: Option<&common_utils::id_type::PaymentId>, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, authentication_id: &common_utils::id_type::AuthenticationId, payment_method: common_enums::PaymentMethod, merchant_id: &common_utils::id_type::MerchantId, _authentication: Option<&Authentication>, ) -> RouterResult<UasPostAuthenticationRouterData> { let post_authentication_data = UasPostAuthenticationRequestData { threeds_server_transaction_id: None, }; let post_auth_router_data: UasPostAuthenticationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method, merchant_id.clone(), None, post_authentication_data, merchant_connector_account, Some(authentication_id.to_owned()), payment_id.cloned(), )?; utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), post_auth_router_data, ) .await } async fn confirmation( state: &SessionState, authentication_id: Option<&common_utils::id_type::AuthenticationId>, currency: Option<common_enums::Currency>, status: common_enums::AttemptStatus, service_details: Option<payments::CtpServiceDetails>, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, payment_method: common_enums::PaymentMethod, net_amount: common_utils::types::MinorUnit, payment_id: Option<&common_utils::id_type::PaymentId>, merchant_id: &common_utils::id_type::MerchantId, ) -> RouterResult<()> { let authentication_id = authentication_id .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Missing authentication id in tracker")?; let currency = currency.ok_or(ApiErrorResponse::MissingRequiredField { field_name: "currency", })?; let current_time = common_utils::date_time::date_as_yyyymmddthhmmssmmmz() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get current time")?; let payment_attempt_status = status; let (checkout_event_status, confirmation_reason) = utils::get_checkout_event_status_and_reason(payment_attempt_status); let click_to_pay_details = service_details.clone(); let authentication_confirmation_data = UasConfirmationRequestData { x_src_flow_id: click_to_pay_details .as_ref() .and_then(|details| details.x_src_flow_id.clone()), transaction_amount: net_amount, transaction_currency: currency, checkout_event_type: Some("01".to_string()), // hardcoded to '01' since only authorise flow is implemented checkout_event_status: checkout_event_status.clone(), confirmation_status: checkout_event_status.clone(), confirmation_reason, confirmation_timestamp: Some(current_time), network_authorization_code: Some("01".to_string()), // hardcoded to '01' since only authorise flow is implemented network_transaction_identifier: Some("mastercard".to_string()), // hardcoded to 'mastercard' since only mastercard has confirmation flow requirement correlation_id: click_to_pay_details .clone() .and_then(|details| details.correlation_id), merchant_transaction_id: click_to_pay_details .and_then(|details| details.merchant_transaction_id), }; let authentication_confirmation_router_data : hyperswitch_domain_models::types::UasAuthenticationConfirmationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method, merchant_id.clone(), None, authentication_confirmation_data, merchant_connector_account, Some(authentication_id.to_owned()), payment_id.cloned(), )?; utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), authentication_confirmation_router_data, ) .await .ok(); // marking this as .ok() since this is not a required step at our end for completing the transaction Ok(()) } } #[cfg(feature = "v1")] #[async_trait::async_trait] impl UnifiedAuthenticationService for ExternalAuthentication { fn get_pre_authentication_request_data( payment_method_data: Option<&domain::PaymentMethodData>, _service_details: Option<payments::CtpServiceDetails>, amount: common_utils::types::MinorUnit, currency: Option<common_enums::Currency>, merchant_details: Option<&hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails>, billing_address: Option<&hyperswitch_domain_models::address::Address>, acquirer_bin: Option<String>, acquirer_merchant_id: Option<String>, payment_method_type: Option<common_enums::PaymentMethodType>, ) -> RouterResult<UasPreAuthenticationRequestData> { let payment_method_data = payment_method_data .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("payment_method_data is missing")?; let payment_details = if let payment_method_data::PaymentMethodData::Card(card) = payment_method_data { Some(PaymentDetails { pan: card.card_number.clone(), digital_card_id: None, payment_data_type: payment_method_type, encrypted_src_card_details: None, card_expiry_month: card.card_exp_month.clone(), card_expiry_year: card.card_exp_year.clone(), cardholder_name: card.card_holder_name.clone(), card_token_number: None, account_type: payment_method_type, card_cvc: Some(card.card_cvc.clone()), }) } else { None }; let transaction_details = TransactionDetails { amount: Some(amount), currency, device_channel: None, message_category: None, }; Ok(UasPreAuthenticationRequestData { service_details: None, transaction_details: Some(transaction_details), payment_details, authentication_info: None, merchant_details: merchant_details.cloned(), billing_address: billing_address.cloned(), acquirer_bin, acquirer_merchant_id, }) } #[allow(clippy::too_many_arguments)] async fn pre_authentication( state: &SessionState, merchant_id: &common_utils::id_type::MerchantId, payment_id: Option<&common_utils::id_type::PaymentId>, payment_method_data: Option<&domain::PaymentMethodData>, payment_method_type: Option<common_enums::PaymentMethodType>, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, authentication_id: &common_utils::id_type::AuthenticationId, payment_method: common_enums::PaymentMethod, amount: common_utils::types::MinorUnit, currency: Option<common_enums::Currency>, service_details: Option<payments::CtpServiceDetails>, merchant_details: Option<&hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails>, billing_address: Option<&hyperswitch_domain_models::address::Address>, acquirer_bin: Option<String>, acquirer_merchant_id: Option<String>, ) -> RouterResult<UasPreAuthenticationRouterData> { let pre_authentication_data = Self::get_pre_authentication_request_data( payment_method_data, service_details, amount, currency, merchant_details, billing_address, acquirer_bin, acquirer_merchant_id, payment_method_type, )?; let pre_auth_router_data: UasPreAuthenticationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method, merchant_id.clone(), None, pre_authentication_data, merchant_connector_account, Some(authentication_id.to_owned()), payment_id.cloned(), )?; Box::pin(utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), pre_auth_router_data, )) .await } fn get_authentication_request_data( browser_details: Option<BrowserInformation>, amount: Option<common_utils::types::MinorUnit>, currency: Option<common_enums::Currency>, message_category: MessageCategory, device_channel: payments::DeviceChannel, authentication: Authentication, return_url: Option<String>, sdk_information: Option<payments::SdkInformation>, threeds_method_comp_ind: payments::ThreeDsCompletionIndicator, email: Option<common_utils::pii::Email>, webhook_url: String, ) -> RouterResult<UasAuthenticationRequestData> { Ok(UasAuthenticationRequestData { browser_details, transaction_details: TransactionDetails { amount, currency, device_channel: Some(device_channel), message_category: Some(message_category), }, pre_authentication_data: PreAuthenticationData { threeds_server_transaction_id: authentication.threeds_server_transaction_id.ok_or( ApiErrorResponse::MissingRequiredField { field_name: "authentication.threeds_server_transaction_id", }, )?, message_version: authentication.message_version.ok_or( ApiErrorResponse::MissingRequiredField { field_name: "authentication.message_version", }, )?, acquirer_bin: authentication.acquirer_bin, acquirer_merchant_id: authentication.acquirer_merchant_id, acquirer_country_code: authentication.acquirer_country_code, connector_metadata: authentication.connector_metadata, }, return_url, sdk_information, email, threeds_method_comp_ind, webhook_url, }) } #[allow(clippy::too_many_arguments)] async fn authentication( state: &SessionState, business_profile: &domain::Profile, payment_method: &common_enums::PaymentMethod, browser_details: Option<BrowserInformation>, amount: Option<common_utils::types::MinorUnit>, currency: Option<common_enums::Currency>, message_category: MessageCategory, device_channel: payments::DeviceChannel, authentication: Authentication, return_url: Option<String>, sdk_information: Option<payments::SdkInformation>, threeds_method_comp_ind: payments::ThreeDsCompletionIndicator, email: Option<common_utils::pii::Email>, webhook_url: String, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, payment_id: Option<common_utils::id_type::PaymentId>, ) -> RouterResult<UasAuthenticationRouterData> { let authentication_data = <Self as UnifiedAuthenticationService>::get_authentication_request_data( browser_details, amount, currency, message_category, device_channel, authentication.clone(), return_url, sdk_information, threeds_method_comp_ind, email, webhook_url, )?; let auth_router_data: UasAuthenticationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method.to_owned(), business_profile.merchant_id.clone(), None, authentication_data, merchant_connector_account, Some(authentication.authentication_id.to_owned()), payment_id, )?; Box::pin(utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), auth_router_data, )) .await } fn get_post_authentication_request_data( authentication: Option<Authentication>, ) -> RouterResult<UasPostAuthenticationRequestData> { Ok(UasPostAuthenticationRequestData { // authentication.threeds_server_transaction_id is mandatory for post-authentication in ExternalAuthentication threeds_server_transaction_id: Some( authentication .and_then(|auth| auth.threeds_server_transaction_id) .ok_or(ApiErrorResponse::MissingRequiredField { field_name: "authentication.threeds_server_transaction_id", })?, ), }) } async fn post_authentication( state: &SessionState, business_profile: &domain::Profile, payment_id: Option<&common_utils::id_type::PaymentId>, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, authentication_id: &common_utils::id_type::AuthenticationId, payment_method: common_enums::PaymentMethod, _merchant_id: &common_utils::id_type::MerchantId, authentication: Option<&Authentication>, ) -> RouterResult<UasPostAuthenticationRouterData> { let authentication_data = <Self as UnifiedAuthenticationService>::get_post_authentication_request_data( authentication.cloned(), )?; let auth_router_data: UasPostAuthenticationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method, business_profile.merchant_id.clone(), None, authentication_data, merchant_connector_account, Some(authentication_id.clone()), payment_id.cloned(), )?; utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), auth_router_data, ) .await } } #[allow(clippy::too_many_arguments)] pub async fn create_new_authentication( state: &SessionState, merchant_id: common_utils::id_type::MerchantId, authentication_connector: Option<String>, profile_id: common_utils::id_type::ProfileId, payment_id: Option<common_utils::id_type::PaymentId>, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, authentication_id: &common_utils::id_type::AuthenticationId, service_details: Option<payments::CtpServiceDetails>, authentication_status: common_enums::AuthenticationStatus, network_token: Option<payment_method_data::NetworkTokenData>, organization_id: common_utils::id_type::OrganizationId, force_3ds_challenge: Option<bool>, psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, acquirer_bin: Option<String>, acquirer_merchant_id: Option<String>, acquirer_country_code: Option<String>, amount: Option<common_utils::types::MinorUnit>, currency: Option<common_enums::Currency>, return_url: Option<String>, profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>, ) -> RouterResult<Authentication> { let service_details_value = service_details .map(serde_json::to_value) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable( "unable to parse service details into json value while inserting to DB", )?; let authentication_client_secret = Some(common_utils::generate_id_with_default_len(&format!( "{}_secret", authentication_id.get_string_repr() ))); let new_authorization = AuthenticationNew { authentication_id: authentication_id.to_owned(), merchant_id, authentication_connector, connector_authentication_id: None, payment_method_id: "".to_string(), authentication_type: None, authentication_status, authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus::Unused, error_message: None, error_code: None, connector_metadata: None, maximum_supported_version: None, threeds_server_transaction_id: None, cavv: None, authentication_flow_type: None, message_version: None, eci: network_token.and_then(|data| data.eci), trans_status: None, acquirer_bin, acquirer_merchant_id, three_ds_method_data: None, three_ds_method_url: None, acs_url: None, challenge_request: None, challenge_request_key: None, acs_reference_number: None, acs_trans_id: None, acs_signed_content: None, profile_id, payment_id, merchant_connector_id, ds_trans_id: None, directory_server_id: None, acquirer_country_code, service_details: service_details_value, organization_id, authentication_client_secret, force_3ds_challenge, psd2_sca_exemption_type, return_url, amount, currency, billing_address: None, shipping_address: None, browser_info: None, email: None, profile_acquirer_id, challenge_code: None, challenge_cancel: None, challenge_code_reason: None, message_extension: None, }; state .store .insert_authentication(new_authorization) .await .to_duplicate_response(ApiErrorResponse::GenericDuplicateError { message: format!( "Authentication with authentication_id {} already exists", authentication_id.get_string_repr() ), }) } // Modular authentication #[cfg(feature = "v1")] pub async fn authentication_create_core( state: SessionState, merchant_context: domain::MerchantContext, req: AuthenticationCreateRequest, ) -> RouterResponse<AuthenticationResponse> { let db = &*state.store; let merchant_account = merchant_context.get_merchant_account(); let merchant_id = merchant_account.get_id(); let key_manager_state = (&state).into(); let profile_id = core_utils::get_profile_id_from_business_details( &key_manager_state, None, None, &merchant_context, req.profile_id.as_ref(), db, true, ) .await?; 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(ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let organization_id = merchant_account.organization_id.clone(); let authentication_id = common_utils::id_type::AuthenticationId::generate_authentication_id( consts::AUTHENTICATION_ID_PREFIX, ); let force_3ds_challenge = Some( req.force_3ds_challenge .unwrap_or(business_profile.force_3ds_challenge), ); // Priority logic: First check req.acquirer_details, then fallback to profile_acquirer_id lookup let (acquirer_bin, acquirer_merchant_id, acquirer_country_code) = if let Some(acquirer_details) = &req.acquirer_details { // Priority 1: Use acquirer_details from request if present ( acquirer_details.acquirer_bin.clone(), acquirer_details.acquirer_merchant_id.clone(), acquirer_details.merchant_country_code.clone(), ) } else { // Priority 2: Fallback to profile_acquirer_id lookup let acquirer_details = req.profile_acquirer_id.clone().and_then(|acquirer_id| { business_profile .acquirer_config_map .and_then(|acquirer_config_map| { acquirer_config_map.0.get(&acquirer_id).cloned() }) }); acquirer_details .as_ref() .map(|details| { ( Some(details.acquirer_bin.clone()), Some(details.acquirer_assigned_merchant_id.clone()), business_profile .merchant_country_code .map(|code| code.get_country_code().to_owned()), ) }) .unwrap_or((None, None, None)) }; let new_authentication = create_new_authentication( &state, merchant_id.clone(), req.authentication_connector .map(|connector| connector.to_string()), profile_id.clone(), None, None, &authentication_id, None, common_enums::AuthenticationStatus::Started, None, organization_id, force_3ds_challenge, req.psd2_sca_exemption_type, acquirer_bin, acquirer_merchant_id, acquirer_country_code, Some(req.amount), Some(req.currency), req.return_url, req.profile_acquirer_id.clone(), ) .await?; let acquirer_details = Some(AcquirerDetails { acquirer_bin: new_authentication.acquirer_bin.clone(), acquirer_merchant_id: new_authentication.acquirer_merchant_id.clone(), merchant_country_code: new_authentication.acquirer_country_code.clone(), }); let amount = new_authentication .amount .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("amount failed to get amount from authentication table")?; let currency = new_authentication .currency .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("currency failed to get currency from authentication table")?; let response = AuthenticationResponse::foreign_try_from(( new_authentication.clone(), amount, currency, profile_id, acquirer_details, new_authentication.profile_acquirer_id, ))?; Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) } impl ForeignTryFrom<( Authentication, common_utils::types::MinorUnit, common_enums::Currency, common_utils::id_type::ProfileId, Option<AcquirerDetails>, Option<common_utils::id_type::ProfileAcquirerId>, )> for AuthenticationResponse { type Error = error_stack::Report<ApiErrorResponse>; fn foreign_try_from( (authentication, amount, currency, profile_id, acquirer_details, profile_acquirer_id): ( Authentication, common_utils::types::MinorUnit, common_enums::Currency, common_utils::id_type::ProfileId, Option<AcquirerDetails>, Option<common_utils::id_type::ProfileAcquirerId>, ), ) -> Result<Self, Self::Error> { let authentication_connector = authentication .authentication_connector .map(|connector| common_enums::AuthenticationConnectors::from_str(&connector)) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Incorrect authentication connector stored in table")?; Ok(Self { authentication_id: authentication.authentication_id, client_secret: authentication .authentication_client_secret .map(masking::Secret::new), amount, currency, force_3ds_challenge: authentication.force_3ds_challenge, merchant_id: authentication.merchant_id, status: authentication.authentication_status, authentication_connector, return_url: authentication.return_url, created_at: Some(authentication.created_at), error_code: authentication.error_code, error_message: authentication.error_message, profile_id: Some(profile_id), psd2_sca_exemption_type: authentication.psd2_sca_exemption_type, acquirer_details, profile_acquirer_id, }) } } #[cfg(feature = "v1")] impl ForeignTryFrom<( Authentication, api_models::authentication::NextAction, common_utils::id_type::ProfileId, Option<payments::Address>, Option<payments::Address>, Option<payments::BrowserInformation>, common_utils::crypto::OptionalEncryptableEmail, )> for AuthenticationEligibilityResponse { type Error = error_stack::Report<ApiErrorResponse>; fn foreign_try_from( (authentication, next_action, profile_id, billing, shipping, browser_information, email): ( Authentication, api_models::authentication::NextAction, common_utils::id_type::ProfileId, Option<payments::Address>, Option<payments::Address>, Option<payments::BrowserInformation>, common_utils::crypto::OptionalEncryptableEmail, ), ) -> Result<Self, Self::Error> { let authentication_connector = authentication .authentication_connector .map(|connector| common_enums::AuthenticationConnectors::from_str(&connector)) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Incorrect authentication connector stored in table")?; let three_ds_method_url = authentication .three_ds_method_url .map(|url| url::Url::parse(&url)) .transpose() .map_err(error_stack::Report::from) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse three_ds_method_url")?; let three_ds_data = Some(api_models::authentication::ThreeDsData { three_ds_server_transaction_id: authentication.threeds_server_transaction_id, maximum_supported_3ds_version: authentication.maximum_supported_version, connector_authentication_id: authentication.connector_authentication_id, three_ds_method_data: authentication.three_ds_method_data, three_ds_method_url, message_version: authentication.message_version, directory_server_id: authentication.directory_server_id, }); let acquirer_details = AcquirerDetails { acquirer_bin: authentication.acquirer_bin, acquirer_merchant_id: authentication.acquirer_merchant_id, merchant_country_code: authentication.acquirer_country_code, }; Ok(Self { authentication_id: authentication.authentication_id, next_action, status: authentication.authentication_status, eligibility_response_params: three_ds_data .map(api_models::authentication::EligibilityResponseParams::ThreeDsData), connector_metadata: authentication.connector_metadata, profile_id, error_message: authentication.error_message, error_code: authentication.error_code, billing, shipping, authentication_connector, browser_information, email, acquirer_details: Some(acquirer_details), }) } } #[cfg(feature = "v1")] pub async fn authentication_eligibility_core( state: SessionState, merchant_context: domain::MerchantContext, req: AuthenticationEligibilityRequest, authentication_id: common_utils::id_type::AuthenticationId, ) -> RouterResponse<AuthenticationEligibilityResponse> { let merchant_account = merchant_context.get_merchant_account(); let merchant_id = merchant_account.get_id(); let db = &*state.store; let authentication = db .find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id) .await .to_not_found_response(ApiErrorResponse::AuthenticationNotFound { id: authentication_id.get_string_repr().to_owned(), })?; req.client_secret .clone() .map(|client_secret| { utils::authenticate_authentication_client_secret_and_check_expiry( client_secret.peek(), &authentication, ) }) .transpose()?; ensure_not_terminal_status(authentication.trans_status.clone())?; let key_manager_state = (&state).into(); let profile_id = core_utils::get_profile_id_from_business_details( &key_manager_state, None, None, &merchant_context, req.profile_id.as_ref(), db, true, ) .await?; 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(ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let (authentication_connector, three_ds_connector_account) = auth_utils::get_authentication_connector_data( &state, merchant_context.get_merchant_key_store(), &business_profile, authentication.authentication_connector.clone(), ) .await?; let notification_url = match authentication_connector { common_enums::AuthenticationConnectors::Juspaythreedsserver => { Some(url::Url::parse(&format!( "{base_url}/authentication/{merchant_id}/{authentication_id}/redirect", base_url = state.base_url, merchant_id = merchant_id.get_string_repr(), authentication_id = authentication_id.get_string_repr() ))) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse notification url")? } _ => authentication .return_url .as_ref() .map(|url| url::Url::parse(url)) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse return url")?, }; let authentication_connector_name = authentication_connector.to_string(); let payment_method_data = domain::PaymentMethodData::from(req.payment_method_data.clone()); let amount = authentication .amount .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("no amount found in authentication table")?; let acquirer_details = authentication .profile_acquirer_id .clone() .and_then(|acquirer_id| { business_profile .acquirer_config_map .and_then(|acquirer_config_map| acquirer_config_map.0.get(&acquirer_id).cloned()) }); let metadata: Option<ThreeDsMetaData> = three_ds_connector_account .get_metadata() .map(|metadata| { metadata.expose().parse_value("ThreeDsMetaData").inspect_err(|err| { router_env::logger::warn!(parsing_error=?err,"Error while parsing ThreeDsMetaData"); }) }) .transpose() .change_context(ApiErrorResponse::InternalServerError)?; let merchant_country_code = authentication.acquirer_country_code.clone(); let merchant_details = Some(hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails { merchant_id: Some(authentication.merchant_id.get_string_repr().to_string()), merchant_name: acquirer_details.clone().map(|detail| detail.merchant_name.clone()).or(metadata.clone().and_then(|metadata| metadata.merchant_name)), merchant_category_code: business_profile.merchant_category_code.or(metadata.clone().and_then(|metadata| metadata.merchant_category_code)), endpoint_prefix: metadata.clone().and_then(|metadata| metadata.endpoint_prefix), three_ds_requestor_url: business_profile.authentication_connector_details.map(|details| details.three_ds_requestor_url), three_ds_requestor_id: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_id), three_ds_requestor_name: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_name), merchant_country_code: merchant_country_code.map(common_types::payments::MerchantCountryCode::new), notification_url, }); let domain_address = req .billing .clone() .map(hyperswitch_domain_models::address::Address::from); let pre_auth_response = <ExternalAuthentication as UnifiedAuthenticationService>::pre_authentication( &state, merchant_id, None, Some(&payment_method_data), req.payment_method_type, &three_ds_connector_account, &authentication_connector_name, &authentication_id, req.payment_method, amount, authentication.currency, None, merchant_details.as_ref(), domain_address.as_ref(), authentication.acquirer_bin.clone(), authentication.acquirer_merchant_id.clone(), ) .await?; let billing_details_encoded = req .billing .clone() .map(|billing| { common_utils::ext_traits::Encode::encode_to_value(&billing) .map(masking::Secret::<serde_json::Value>::new) }) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encode billing details to serde_json::Value")?; let shipping_details_encoded = req .shipping .clone() .map(|shipping| { common_utils::ext_traits::Encode::encode_to_value(&shipping) .map(masking::Secret::<serde_json::Value>::new) }) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encode shipping details to serde_json::Value")?; let encrypted_data = domain::types::crypto_operation( &key_manager_state, common_utils::type_name!(hyperswitch_domain_models::authentication::Authentication), domain::types::CryptoOperation::BatchEncrypt( hyperswitch_domain_models::authentication::UpdateEncryptableAuthentication::to_encryptable( hyperswitch_domain_models::authentication::UpdateEncryptableAuthentication { billing_address: billing_details_encoded, shipping_address: shipping_details_encoded, }, ), ), common_utils::types::keymanager::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(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt authentication data".to_string())?; let encrypted_data = hyperswitch_domain_models::authentication::FromRequestEncryptableAuthentication::from_encryptable(encrypted_data) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to get encrypted data for authentication after encryption")?; let email_encrypted = req .email .clone() .async_lift(|inner| async { domain::types::crypto_operation( &key_manager_state, common_utils::type_name!(Authentication), domain::types::CryptoOperation::EncryptOptional(inner.map(|inner| inner.expose())), common_utils::types::keymanager::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_optionaloperation()) }) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt email")?; let browser_info = req .browser_information .as_ref() .map(common_utils::ext_traits::Encode::encode_to_value) .transpose() .change_context(ApiErrorResponse::InvalidDataValue { field_name: "browser_information", })?; let updated_authentication = utils::external_authentication_update_trackers( &state, pre_auth_response, authentication.clone(), None, merchant_context.get_merchant_key_store(), encrypted_data .billing_address .map(common_utils::encryption::Encryption::from), encrypted_data .shipping_address .map(common_utils::encryption::Encryption::from), email_encrypted .clone() .map(common_utils::encryption::Encryption::from), browser_info, ) .await?; let response = AuthenticationEligibilityResponse::foreign_try_from(( updated_authentication, req.get_next_action_api( state.base_url, authentication_id.get_string_repr().to_string(), ) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to get next action api")?, profile_id, req.get_billing_address(), req.get_shipping_address(), req.get_browser_information(), email_encrypted, ))?; Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) } #[cfg(feature = "v1")] pub async fn authentication_authenticate_core( state: SessionState, merchant_context: domain::MerchantContext, req: AuthenticationAuthenticateRequest, auth_flow: AuthFlow, ) -> RouterResponse<AuthenticationAuthenticateResponse> { let authentication_id = req.authentication_id.clone(); let merchant_account = merchant_context.get_merchant_account(); let merchant_id = merchant_account.get_id(); let db = &*state.store; let authentication = db .find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id) .await .to_not_found_response(ApiErrorResponse::AuthenticationNotFound { id: authentication_id.get_string_repr().to_owned(), })?; req.client_secret .map(|client_secret| { utils::authenticate_authentication_client_secret_and_check_expiry( client_secret.peek(), &authentication, ) }) .transpose()?; ensure_not_terminal_status(authentication.trans_status.clone())?; let key_manager_state = (&state).into(); let profile_id = authentication.profile_id.clone(); 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(ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let email_encrypted = authentication .email .clone() .async_lift(|inner| async { domain::types::crypto_operation( &key_manager_state, common_utils::type_name!(Authentication), domain::types::CryptoOperation::DecryptOptional(inner), common_utils::types::keymanager::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_optionaloperation()) }) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to decrypt email from authentication table")?; let browser_info = authentication .browser_info .clone() .map(|browser_info| browser_info.parse_value::<BrowserInformation>("BrowserInformation")) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse browser information from authentication table")?; let (authentication_connector, three_ds_connector_account) = auth_utils::get_authentication_connector_data( &state, merchant_context.get_merchant_key_store(), &business_profile, authentication.authentication_connector.clone(), ) .await?; let authentication_details = business_profile .authentication_connector_details .clone() .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("authentication_connector_details not configured by the merchant")?; let connector_name_string = authentication_connector.to_string(); let mca_id_option = three_ds_connector_account.get_mca_id(); let merchant_connector_account_id_or_connector_name = mca_id_option .as_ref() .map(|mca_id| mca_id.get_string_repr()) .unwrap_or(&connector_name_string); let webhook_url = helpers::create_webhook_url( &state.base_url, merchant_id, merchant_connector_account_id_or_connector_name, ); let auth_response = <ExternalAuthentication as UnifiedAuthenticationService>::authentication( &state, &business_profile, &common_enums::PaymentMethod::Card, browser_info, authentication.amount, authentication.currency, MessageCategory::Payment, req.device_channel, authentication.clone(), None, req.sdk_information, req.threeds_method_comp_ind, email_encrypted.map(common_utils::pii::Email::from), webhook_url, &three_ds_connector_account, &authentication_connector.to_string(), None, ) .await?; let authentication = utils::external_authentication_update_trackers( &state, auth_response, authentication.clone(), None, merchant_context.get_merchant_key_store(), None, None, None, None, ) .await?; let (authentication_value, eci) = match auth_flow { AuthFlow::Client => (None, None), AuthFlow::Merchant => { if let Some(common_enums::TransactionStatus::Success) = authentication.trans_status { let tokenised_data = crate::core::payment_methods::vault::get_tokenized_data( &state, authentication_id.get_string_repr(), false, merchant_context.get_merchant_key_store().key.get_inner(), ) .await .inspect_err(|err| router_env::logger::error!(tokenized_data_result=?err)) .attach_printable("cavv not present after authentication status is success")?; ( Some(masking::Secret::new(tokenised_data.value1)), authentication.eci.clone(), ) } else { (None, None) } } }; let response = AuthenticationAuthenticateResponse::foreign_try_from(( &authentication, authentication_value, eci, authentication_details, ))?; Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) } impl ForeignTryFrom<( &Authentication, Option<masking::Secret<String>>, Option<String>, diesel_models::business_profile::AuthenticationConnectorDetails, )> for AuthenticationAuthenticateResponse { type Error = error_stack::Report<ApiErrorResponse>; fn foreign_try_from( (authentication, authentication_value, eci, authentication_details): ( &Authentication, Option<masking::Secret<String>>, Option<String>, diesel_models::business_profile::AuthenticationConnectorDetails, ), ) -> Result<Self, Self::Error> { let authentication_connector = authentication .authentication_connector .as_ref() .map(|connector| common_enums::AuthenticationConnectors::from_str(connector)) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Incorrect authentication connector stored in table")?; let acs_url = authentication .acs_url .clone() .map(|acs_url| url::Url::parse(&acs_url)) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse the url with param")?; let acquirer_details = AcquirerDetails { acquirer_bin: authentication.acquirer_bin.clone(), acquirer_merchant_id: authentication.acquirer_merchant_id.clone(), merchant_country_code: authentication.acquirer_country_code.clone(), }; Ok(Self { transaction_status: authentication.trans_status.clone(), acs_url, challenge_request: authentication.challenge_request.clone(), acs_reference_number: authentication.acs_reference_number.clone(), acs_trans_id: authentication.acs_trans_id.clone(), three_ds_server_transaction_id: authentication.threeds_server_transaction_id.clone(), acs_signed_content: authentication.acs_signed_content.clone(), three_ds_requestor_url: authentication_details.three_ds_requestor_url.clone(), three_ds_requestor_app_url: authentication_details.three_ds_requestor_app_url.clone(), error_code: None, error_message: authentication.error_message.clone(), authentication_value, status: authentication.authentication_status, authentication_connector, eci, authentication_id: authentication.authentication_id.clone(), acquirer_details: Some(acquirer_details), }) } } #[cfg(feature = "v1")] pub async fn authentication_sync_core( state: SessionState, merchant_context: domain::MerchantContext, auth_flow: AuthFlow, req: AuthenticationSyncRequest, ) -> RouterResponse<AuthenticationSyncResponse> { let authentication_id = req.authentication_id; let merchant_account = merchant_context.get_merchant_account(); let merchant_id = merchant_account.get_id(); let db = &*state.store; let authentication = db .find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id) .await .to_not_found_response(ApiErrorResponse::AuthenticationNotFound { id: authentication_id.get_string_repr().to_owned(), })?; req.client_secret .map(|client_secret| { utils::authenticate_authentication_client_secret_and_check_expiry( client_secret.peek(), &authentication, ) }) .transpose()?; let key_manager_state = (&state).into(); let profile_id = authentication.profile_id.clone(); 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(ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let (authentication_connector, three_ds_connector_account) = auth_utils::get_authentication_connector_data( &state, merchant_context.get_merchant_key_store(), &business_profile, authentication.authentication_connector.clone(), ) .await?; let updated_authentication = match authentication.trans_status.clone() { Some(trans_status) if trans_status.clone().is_pending() => { let post_auth_response = ExternalAuthentication::post_authentication( &state, &business_profile, None, &three_ds_connector_account, &authentication_connector.to_string(), &authentication_id, common_enums::PaymentMethod::Card, merchant_id, Some(&authentication), ) .await?; utils::external_authentication_update_trackers( &state, post_auth_response, authentication.clone(), None, merchant_context.get_merchant_key_store(), None, None, None, None, ) .await? } _ => authentication, }; let (authentication_value, eci) = match auth_flow { AuthFlow::Client => (None, None), AuthFlow::Merchant => { if let Some(common_enums::TransactionStatus::Success) = updated_authentication.trans_status { let tokenised_data = crate::core::payment_methods::vault::get_tokenized_data( &state, authentication_id.get_string_repr(), false, merchant_context.get_merchant_key_store().key.get_inner(), ) .await .inspect_err(|err| router_env::logger::error!(tokenized_data_result=?err)) .attach_printable("cavv not present after authentication status is success")?; ( Some(masking::Secret::new(tokenised_data.value1)), updated_authentication.eci.clone(), ) } else { (None, None) } } }; let acquirer_details = Some(AcquirerDetails { acquirer_bin: updated_authentication.acquirer_bin.clone(), acquirer_merchant_id: updated_authentication.acquirer_merchant_id.clone(), merchant_country_code: updated_authentication.acquirer_country_code.clone(), }); let encrypted_data = domain::types::crypto_operation( &key_manager_state, common_utils::type_name!(hyperswitch_domain_models::authentication::Authentication), domain::types::CryptoOperation::BatchDecrypt( hyperswitch_domain_models::authentication::EncryptedAuthentication::to_encryptable( hyperswitch_domain_models::authentication::EncryptedAuthentication { billing_address: updated_authentication.billing_address, shipping_address: updated_authentication.shipping_address, }, ), ), common_utils::types::keymanager::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(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt authentication data".to_string())?; let encrypted_data = hyperswitch_domain_models::authentication::FromRequestEncryptableAuthentication::from_encryptable(encrypted_data) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to get encrypted data for authentication after encryption")?; let email_decrypted = updated_authentication .email .clone() .async_lift(|inner| async { domain::types::crypto_operation( &key_manager_state, common_utils::type_name!(Authentication), domain::types::CryptoOperation::DecryptOptional(inner), common_utils::types::keymanager::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_optionaloperation()) }) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt email")?; let browser_info = updated_authentication .browser_info .clone() .map(|browser_info| { browser_info.parse_value::<payments::BrowserInformation>("BrowserInformation") }) .transpose() .change_context(ApiErrorResponse::InternalServerError)?; let amount = updated_authentication .amount .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("amount failed to get amount from authentication table")?; let currency = updated_authentication .currency .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("currency failed to get currency from authentication table")?; let authentication_connector = updated_authentication .authentication_connector .map(|connector| common_enums::AuthenticationConnectors::from_str(&connector)) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Incorrect authentication connector stored in table")?; let billing = encrypted_data .billing_address .map(|billing| { billing .into_inner() .expose() .parse_value::<payments::Address>("Address") }) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse billing address")?; let shipping = encrypted_data .shipping_address .map(|shipping| { shipping .into_inner() .expose() .parse_value::<payments::Address>("Address") }) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse shipping address")?; let response = AuthenticationSyncResponse { authentication_id: authentication_id.clone(), merchant_id: merchant_id.clone(), status: updated_authentication.authentication_status, client_secret: updated_authentication .authentication_client_secret .map(masking::Secret::new), amount, currency, authentication_connector, force_3ds_challenge: updated_authentication.force_3ds_challenge, return_url: updated_authentication.return_url.clone(), created_at: updated_authentication.created_at, profile_id: updated_authentication.profile_id.clone(), psd2_sca_exemption_type: updated_authentication.psd2_sca_exemption_type, acquirer_details, error_message: updated_authentication.error_message.clone(), error_code: updated_authentication.error_code.clone(), authentication_value, threeds_server_transaction_id: updated_authentication.threeds_server_transaction_id.clone(), maximum_supported_3ds_version: updated_authentication.maximum_supported_version.clone(), connector_authentication_id: updated_authentication.connector_authentication_id.clone(), three_ds_method_data: updated_authentication.three_ds_method_data.clone(), three_ds_method_url: updated_authentication.three_ds_method_url.clone(), message_version: updated_authentication.message_version.clone(), connector_metadata: updated_authentication.connector_metadata.clone(), directory_server_id: updated_authentication.directory_server_id.clone(), billing, shipping, browser_information: browser_info, email: email_decrypted, transaction_status: updated_authentication.trans_status.clone(), acs_url: updated_authentication.acs_url.clone(), challenge_request: updated_authentication.challenge_request.clone(), acs_reference_number: updated_authentication.acs_reference_number.clone(), acs_trans_id: updated_authentication.acs_trans_id.clone(), acs_signed_content: updated_authentication.acs_signed_content, three_ds_requestor_url: business_profile .authentication_connector_details .clone() .map(|details| details.three_ds_requestor_url), three_ds_requestor_app_url: business_profile .authentication_connector_details .and_then(|details| details.three_ds_requestor_app_url), profile_acquirer_id: updated_authentication.profile_acquirer_id.clone(), eci, }; Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) } #[cfg(feature = "v1")] pub async fn authentication_post_sync_core( state: SessionState, merchant_context: domain::MerchantContext, req: AuthenticationSyncPostUpdateRequest, ) -> RouterResponse<()> { let authentication_id = req.authentication_id; let merchant_account = merchant_context.get_merchant_account(); let merchant_id = merchant_account.get_id(); let db = &*state.store; let authentication = db .find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id) .await .to_not_found_response(ApiErrorResponse::AuthenticationNotFound { id: authentication_id.get_string_repr().to_owned(), })?; ensure_not_terminal_status(authentication.trans_status.clone())?; let key_manager_state = (&state).into(); let business_profile = db .find_business_profile_by_profile_id( &key_manager_state, merchant_context.get_merchant_key_store(), &authentication.profile_id, ) .await .to_not_found_response(ApiErrorResponse::ProfileNotFound { id: authentication.profile_id.get_string_repr().to_owned(), })?; let (authentication_connector, three_ds_connector_account) = auth_utils::get_authentication_connector_data( &state, merchant_context.get_merchant_key_store(), &business_profile, authentication.authentication_connector.clone(), ) .await?; let post_auth_response = <ExternalAuthentication as UnifiedAuthenticationService>::post_authentication( &state, &business_profile, None, &three_ds_connector_account, &authentication_connector.to_string(), &authentication_id, common_enums::PaymentMethod::Card, merchant_id, Some(&authentication), ) .await?; let updated_authentication = utils::external_authentication_update_trackers( &state, post_auth_response, authentication.clone(), None, merchant_context.get_merchant_key_store(), None, None, None, None, ) .await?; let authentication_details = business_profile .authentication_connector_details .clone() .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("authentication_connector_details not configured by the merchant")?; let authentication_response = AuthenticationAuthenticateResponse::foreign_try_from(( &updated_authentication, None, None, authentication_details, ))?; let redirect_response = helpers::get_handle_response_url_for_modular_authentication( authentication_id, &business_profile, &authentication_response, authentication_connector.to_string(), authentication.return_url, updated_authentication .authentication_client_secret .clone() .map(masking::Secret::new) .as_ref(), updated_authentication.amount, )?; Ok(hyperswitch_domain_models::api::ApplicationResponse::JsonForRedirection(redirect_response)) } fn ensure_not_terminal_status( status: Option<common_enums::TransactionStatus>, ) -> Result<(), error_stack::Report<ApiErrorResponse>> { status .filter(|s| s.clone().is_terminal_state()) .map(|s| { Err(error_stack::Report::new( ApiErrorResponse::UnprocessableEntity { message: format!( "authentication status for the given authentication_id is already in {s}" ), }, )) }) .unwrap_or(Ok(())) } </file>
{ "crate": "router", "file": "crates/router/src/core/unified_authentication_service.rs", "files": null, "module": null, "num_files": null, "token_count": 12852 }
large_file_8978881104527700733
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/user_role.rs </path> <file> use std::{ collections::{HashMap, HashSet}, sync::LazyLock, }; use api_models::{ user as user_api, user_role::{self as user_role_api, role as role_api}, }; use diesel_models::{ enums::{UserRoleVersion, UserStatus}, organization::OrganizationBridge, user_role::UserRoleUpdate, }; use error_stack::{report, ResultExt}; use masking::Secret; use crate::{ core::errors::{StorageErrorExt, UserErrors, UserResponse}, db::user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload}, routes::{app::ReqState, SessionState}, services::{ authentication as auth, authorization::{ info, permission_groups::{ParentGroupExt, PermissionGroupExt}, roles, }, ApplicationResponse, }, types::domain, utils, }; pub mod role; use common_enums::{EntityType, ParentGroup, PermissionGroup}; use strum::IntoEnumIterator; // TODO: To be deprecated pub async fn get_authorization_info_with_groups( _state: SessionState, ) -> UserResponse<user_role_api::AuthorizationInfoResponse> { Ok(ApplicationResponse::Json( user_role_api::AuthorizationInfoResponse( info::get_group_authorization_info() .ok_or(UserErrors::InternalServerError) .attach_printable("No visible groups found")? .into_iter() .map(user_role_api::AuthorizationInfo::Group) .collect(), ), )) } pub async fn get_authorization_info_with_group_tag( ) -> UserResponse<user_role_api::AuthorizationInfoResponse> { static GROUPS_WITH_PARENT_TAGS: LazyLock<Vec<user_role_api::ParentInfo>> = LazyLock::new(|| { PermissionGroup::iter() .map(|group| (group.parent(), group)) .fold( HashMap::new(), |mut acc: HashMap<ParentGroup, Vec<PermissionGroup>>, (key, value)| { acc.entry(key).or_default().push(value); acc }, ) .into_iter() .filter_map(|(name, value)| { Some(user_role_api::ParentInfo { name: name.clone(), description: info::get_parent_group_description(name)?, groups: value, }) }) .collect() }); Ok(ApplicationResponse::Json( user_role_api::AuthorizationInfoResponse( GROUPS_WITH_PARENT_TAGS .iter() .cloned() .map(user_role_api::AuthorizationInfo::GroupWithTag) .collect(), ), )) } pub async fn get_parent_group_info( state: SessionState, user_from_token: auth::UserFromToken, request: role_api::GetParentGroupsInfoQueryParams, ) -> UserResponse<Vec<role_api::ParentGroupDescription>> { let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .to_not_found_response(UserErrors::InvalidRoleId)?; let entity_type = request .entity_type .unwrap_or_else(|| role_info.get_entity_type()); if role_info.get_entity_type() < entity_type { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "Invalid operation, requestor entity type = {} cannot access entity type = {}", role_info.get_entity_type(), entity_type )); } let parent_groups = ParentGroup::get_descriptions_for_groups(entity_type, PermissionGroup::iter().collect()) .unwrap_or_default() .into_iter() .map( |(parent_group, description)| role_api::ParentGroupDescription { name: parent_group.clone(), description, scopes: PermissionGroup::iter() .filter_map(|group| { (group.parent() == parent_group).then_some(group.scope()) }) // TODO: Remove this hashset conversion when merchant access // and organization access groups are removed .collect::<HashSet<_>>() .into_iter() .collect(), }, ) .collect::<Vec<_>>(); Ok(ApplicationResponse::Json(parent_groups)) } pub async fn update_user_role( state: SessionState, user_from_token: auth::UserFromToken, req: user_role_api::UpdateUserRoleRequest, _req_state: ReqState, ) -> UserResponse<()> { let role_info = roles::RoleInfo::from_role_id_in_lineage( &state, &req.role_id, &user_from_token.merchant_id, &user_from_token.org_id, &user_from_token.profile_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .to_not_found_response(UserErrors::InvalidRoleId)?; if !role_info.is_updatable() { return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable(format!("User role cannot be updated to {}", req.role_id)); } let user_to_be_updated = utils::user::get_user_from_db_by_email(&state, domain::UserEmail::try_from(req.email)?) .await .to_not_found_response(UserErrors::InvalidRoleOperation) .attach_printable("User not found in our records".to_string())?; if user_from_token.user_id == user_to_be_updated.get_user_id() { return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable("User Changing their own role"); } let updator_role = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; let mut is_updated = false; let v2_user_role_to_be_updated = match state .global_store .find_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V2, ) .await { Ok(user_role) => Some(user_role), Err(e) => { if e.current_context().is_db_not_found() { None } else { return Err(UserErrors::InternalServerError.into()); } } }; if let Some(user_role) = v2_user_role_to_be_updated { let role_to_be_updated = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_role.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; if !role_to_be_updated.is_updatable() { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "User role cannot be updated from {}", role_to_be_updated.get_role_id() )); } if role_info.get_entity_type() != role_to_be_updated.get_entity_type() { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "Upgrade and downgrade of roles is not allowed, user_entity_type = {} req_entity_type = {}", role_to_be_updated.get_entity_type(), role_info.get_entity_type(), )); } if updator_role.get_entity_type() < role_to_be_updated.get_entity_type() { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "Invalid operation, update requestor = {} cannot update target = {}", updator_role.get_entity_type(), role_to_be_updated.get_entity_type() )); } state .global_store .update_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, Some(&user_from_token.merchant_id), Some(&user_from_token.profile_id), UserRoleUpdate::UpdateRole { role_id: req.role_id.clone(), modified_by: user_from_token.user_id.clone(), }, UserRoleVersion::V2, ) .await .change_context(UserErrors::InternalServerError)?; is_updated = true; } let v1_user_role_to_be_updated = match state .global_store .find_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V1, ) .await { Ok(user_role) => Some(user_role), Err(e) => { if e.current_context().is_db_not_found() { None } else { return Err(UserErrors::InternalServerError.into()); } } }; if let Some(user_role) = v1_user_role_to_be_updated { let role_to_be_updated = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_role.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; if !role_to_be_updated.is_updatable() { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "User role cannot be updated from {}", role_to_be_updated.get_role_id() )); } if role_info.get_entity_type() != role_to_be_updated.get_entity_type() { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "Upgrade and downgrade of roles is not allowed, user_entity_type = {} req_entity_type = {}", role_to_be_updated.get_entity_type(), role_info.get_entity_type(), )); } if updator_role.get_entity_type() < role_to_be_updated.get_entity_type() { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "Invalid operation, update requestor = {} cannot update target = {}", updator_role.get_entity_type(), role_to_be_updated.get_entity_type() )); } state .global_store .update_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, Some(&user_from_token.merchant_id), Some(&user_from_token.profile_id), UserRoleUpdate::UpdateRole { role_id: req.role_id.clone(), modified_by: user_from_token.user_id, }, UserRoleVersion::V1, ) .await .change_context(UserErrors::InternalServerError)?; is_updated = true; } if !is_updated { return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable("User with given email is not found in the organization")?; } auth::blacklist::insert_user_in_blacklist(&state, user_to_be_updated.get_user_id()).await?; Ok(ApplicationResponse::StatusOk) } pub async fn accept_invitations_v2( state: SessionState, user_from_token: auth::UserFromToken, req: user_role_api::AcceptInvitationsV2Request, ) -> UserResponse<()> { let lineages = futures::future::try_join_all(req.into_iter().map(|entity| { utils::user_role::get_lineage_for_user_id_and_entity_for_accepting_invite( &state, &user_from_token.user_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), entity.entity_id, entity.entity_type, ) })) .await? .into_iter() .flatten() .collect::<Vec<_>>(); let update_results = futures::future::join_all(lineages.iter().map( |(org_id, merchant_id, profile_id)| async { let (update_v1_result, update_v2_result) = utils::user_role::update_v1_and_v2_user_roles_in_db( &state, user_from_token.user_id.as_str(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id, merchant_id.as_ref(), profile_id.as_ref(), UserRoleUpdate::UpdateStatus { status: UserStatus::Active, modified_by: user_from_token.user_id.clone(), }, ) .await; if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found()) || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found()) { Err(report!(UserErrors::InternalServerError)) } else { Ok(()) } }, )) .await; if update_results.is_empty() || update_results.iter().all(Result::is_err) { return Err(UserErrors::MerchantIdNotFound.into()); } Ok(ApplicationResponse::StatusOk) } pub async fn accept_invitations_pre_auth( state: SessionState, user_token: auth::UserFromSinglePurposeToken, req: user_role_api::AcceptInvitationsPreAuthRequest, ) -> UserResponse<user_api::TokenResponse> { let lineages = futures::future::try_join_all(req.into_iter().map(|entity| { utils::user_role::get_lineage_for_user_id_and_entity_for_accepting_invite( &state, &user_token.user_id, user_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), entity.entity_id, entity.entity_type, ) })) .await? .into_iter() .flatten() .collect::<Vec<_>>(); let update_results = futures::future::join_all(lineages.iter().map( |(org_id, merchant_id, profile_id)| async { let (update_v1_result, update_v2_result) = utils::user_role::update_v1_and_v2_user_roles_in_db( &state, user_token.user_id.as_str(), user_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id, merchant_id.as_ref(), profile_id.as_ref(), UserRoleUpdate::UpdateStatus { status: UserStatus::Active, modified_by: user_token.user_id.clone(), }, ) .await; if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found()) || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found()) { Err(report!(UserErrors::InternalServerError)) } else { Ok(()) } }, )) .await; if update_results.is_empty() || update_results.iter().all(Result::is_err) { return Err(UserErrors::MerchantIdNotFound.into()); } let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_id(user_token.user_id.as_str()) .await .change_context(UserErrors::InternalServerError)? .into(); let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::MerchantSelect.into())?; let next_flow = current_flow.next(user_from_db.clone(), &state).await?; let token = next_flow.get_token(&state).await?; let response = user_api::TokenResponse { token: token.clone(), token_type: next_flow.get_flow().into(), }; auth::cookies::set_cookie_response(response, token) } pub async fn delete_user_role( state: SessionState, user_from_token: auth::UserFromToken, request: user_role_api::DeleteUserRoleRequest, _req_state: ReqState, ) -> UserResponse<()> { let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_email(&domain::UserEmail::from_pii_email(request.email)?) .await .map_err(|e| { if e.current_context().is_db_not_found() { e.change_context(UserErrors::InvalidRoleOperation) .attach_printable("User not found in our records") } else { e.change_context(UserErrors::InternalServerError) } })? .into(); if user_from_db.get_user_id() == user_from_token.user_id { return Err(report!(UserErrors::InvalidDeleteOperation)) .attach_printable("User deleting himself"); } let deletion_requestor_role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; let mut user_role_deleted_flag = false; // Find in V2 let user_role_v2 = match state .global_store .find_user_role_by_user_id_and_lineage( user_from_db.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V2, ) .await { Ok(user_role) => Some(user_role), Err(e) => { if e.current_context().is_db_not_found() { None } else { return Err(UserErrors::InternalServerError.into()); } } }; if let Some(role_to_be_deleted) = user_role_v2 { let target_role_info = roles::RoleInfo::from_role_id_in_lineage( &state, &role_to_be_deleted.role_id, &user_from_token.merchant_id, &user_from_token.org_id, &user_from_token.profile_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; if !target_role_info.is_deletable() { return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable(format!( "Invalid operation, role_id = {} is not deletable", role_to_be_deleted.role_id )); } if deletion_requestor_role_info.get_entity_type() < target_role_info.get_entity_type() { return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable(format!( "Invalid operation, deletion requestor = {} cannot delete target = {}", deletion_requestor_role_info.get_entity_type(), target_role_info.get_entity_type() )); } user_role_deleted_flag = true; state .global_store .delete_user_role_by_user_id_and_lineage( user_from_db.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V2, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error while deleting user role")?; } // Find in V1 let user_role_v1 = match state .global_store .find_user_role_by_user_id_and_lineage( user_from_db.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V1, ) .await { Ok(user_role) => Some(user_role), Err(e) => { if e.current_context().is_db_not_found() { None } else { return Err(UserErrors::InternalServerError.into()); } } }; if let Some(role_to_be_deleted) = user_role_v1 { let target_role_info = roles::RoleInfo::from_role_id_in_lineage( &state, &role_to_be_deleted.role_id, &user_from_token.merchant_id, &user_from_token.org_id, &user_from_token.profile_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; if !target_role_info.is_deletable() { return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable(format!( "Invalid operation, role_id = {} is not deletable", role_to_be_deleted.role_id )); } if deletion_requestor_role_info.get_entity_type() < target_role_info.get_entity_type() { return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable(format!( "Invalid operation, deletion requestor = {} cannot delete target = {}", deletion_requestor_role_info.get_entity_type(), target_role_info.get_entity_type() )); } user_role_deleted_flag = true; state .global_store .delete_user_role_by_user_id_and_lineage( user_from_db.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V1, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error while deleting user role")?; } if !user_role_deleted_flag { return Err(report!(UserErrors::InvalidDeleteOperation)) .attach_printable("User is not associated with the merchant"); } // Check if user has any more role associations let remaining_roles = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: user_from_db.get_user_id(), tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: None, merchant_id: None, profile_id: None, entity_id: None, version: None, status: None, limit: None, }) .await .change_context(UserErrors::InternalServerError)?; // If user has no more role associated with him then deleting user if remaining_roles.is_empty() { state .global_store .delete_user_by_user_id(user_from_db.get_user_id()) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error while deleting user entry")?; } auth::blacklist::insert_user_in_blacklist(&state, user_from_db.get_user_id()).await?; Ok(ApplicationResponse::StatusOk) } pub async fn list_users_in_lineage( state: SessionState, user_from_token: auth::UserFromToken, request: user_role_api::ListUsersInEntityRequest, ) -> UserResponse<Vec<user_role_api::ListUsersInEntityResponse>> { let requestor_role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; let user_roles_set: HashSet<_> = match utils::user_role::get_min_entity( requestor_role_info.get_entity_type(), request.entity_type, )? { EntityType::Tenant => { let mut org_users = utils::user_role::fetch_user_roles_by_payload( &state, ListUserRolesByOrgIdPayload { user_id: None, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: &user_from_token.org_id, merchant_id: None, profile_id: None, version: None, limit: None, }, request.entity_type, ) .await?; // Fetch tenant user let tenant_user = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &user_from_token.user_id, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: None, merchant_id: None, profile_id: None, entity_id: None, version: None, status: None, limit: None, }) .await .change_context(UserErrors::InternalServerError)?; org_users.extend(tenant_user); org_users } EntityType::Organization => { utils::user_role::fetch_user_roles_by_payload( &state, ListUserRolesByOrgIdPayload { user_id: None, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: &user_from_token.org_id, merchant_id: None, profile_id: None, version: None, limit: None, }, request.entity_type, ) .await? } EntityType::Merchant => { utils::user_role::fetch_user_roles_by_payload( &state, ListUserRolesByOrgIdPayload { user_id: None, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: &user_from_token.org_id, merchant_id: Some(&user_from_token.merchant_id), profile_id: None, version: None, limit: None, }, request.entity_type, ) .await? } EntityType::Profile => { utils::user_role::fetch_user_roles_by_payload( &state, ListUserRolesByOrgIdPayload { user_id: None, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: &user_from_token.org_id, merchant_id: Some(&user_from_token.merchant_id), profile_id: Some(&user_from_token.profile_id), version: None, limit: None, }, request.entity_type, ) .await? } }; // This filtering is needed because for org level users in V1, merchant_id is present. // Due to this, we get org level users in merchant level users list. let user_roles_set = user_roles_set .into_iter() .filter_map(|user_role| { let (_entity_id, entity_type) = user_role.get_entity_id_and_type()?; (entity_type <= requestor_role_info.get_entity_type()).then_some(user_role) }) .collect::<HashSet<_>>(); let mut email_map = state .global_store .find_users_by_user_ids( user_roles_set .iter() .map(|user_role| user_role.user_id.clone()) .collect(), ) .await .change_context(UserErrors::InternalServerError)? .into_iter() .map(|user| (user.user_id.clone(), user.email)) .collect::<HashMap<_, _>>(); let role_info_map = futures::future::try_join_all(user_roles_set.iter().map(|user_role| async { roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_role.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .map(|role_info| { ( user_role.role_id.clone(), user_role_api::role::MinimalRoleInfo { role_id: user_role.role_id.clone(), role_name: role_info.get_role_name().to_string(), }, ) }) })) .await .change_context(UserErrors::InternalServerError)? .into_iter() .collect::<HashMap<_, _>>(); let user_role_map = user_roles_set .into_iter() .fold(HashMap::new(), |mut map, user_role| { map.entry(user_role.user_id) .or_insert(Vec::with_capacity(1)) .push(user_role.role_id); map }); Ok(ApplicationResponse::Json( user_role_map .into_iter() .map(|(user_id, role_id_vec)| { Ok::<_, error_stack::Report<UserErrors>>(user_role_api::ListUsersInEntityResponse { email: email_map .remove(&user_id) .ok_or(UserErrors::InternalServerError)?, roles: role_id_vec .into_iter() .map(|role_id| { role_info_map .get(&role_id) .cloned() .ok_or(UserErrors::InternalServerError) }) .collect::<Result<Vec<_>, _>>()?, }) }) .collect::<Result<Vec<_>, _>>()?, )) } pub async fn list_invitations_for_user( state: SessionState, user_from_token: auth::UserIdFromAuth, ) -> UserResponse<Vec<user_role_api::ListInvitationForUserResponse>> { let user_roles = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &user_from_token.user_id, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: None, merchant_id: None, profile_id: None, entity_id: None, version: None, status: Some(UserStatus::InvitationSent), limit: None, }) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to list user roles by user id and invitation sent")? .into_iter() .collect::<HashSet<_>>(); let (org_ids, merchant_ids, profile_ids_with_merchant_ids) = user_roles.iter().try_fold( (Vec::new(), Vec::new(), Vec::new()), |(mut org_ids, mut merchant_ids, mut profile_ids_with_merchant_ids), user_role| { let (_, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError) .attach_printable("Failed to compute entity id and type")?; match entity_type { EntityType::Tenant => { return Err(report!(UserErrors::InternalServerError)) .attach_printable("Tenant roles are not allowed for this operation"); } EntityType::Organization => org_ids.push( user_role .org_id .clone() .ok_or(UserErrors::InternalServerError)?, ), EntityType::Merchant => merchant_ids.push( user_role .merchant_id .clone() .ok_or(UserErrors::InternalServerError)?, ), EntityType::Profile => profile_ids_with_merchant_ids.push(( user_role .profile_id .clone() .ok_or(UserErrors::InternalServerError)?, user_role .merchant_id .clone() .ok_or(UserErrors::InternalServerError)?, )), } Ok::<_, error_stack::Report<UserErrors>>(( org_ids, merchant_ids, profile_ids_with_merchant_ids, )) }, )?; let org_name_map = futures::future::try_join_all(org_ids.into_iter().map(|org_id| async { let org_name = state .accounts_store .find_organization_by_org_id(&org_id) .await .change_context(UserErrors::InternalServerError)? .get_organization_name() .map(Secret::new); Ok::<_, error_stack::Report<UserErrors>>((org_id, org_name)) })) .await? .into_iter() .collect::<HashMap<_, _>>(); let key_manager_state = &(&state).into(); let merchant_name_map = state .store .list_multiple_merchant_accounts(key_manager_state, merchant_ids) .await .change_context(UserErrors::InternalServerError)? .into_iter() .map(|merchant| { ( merchant.get_id().clone(), merchant .merchant_name .map(|encryptable_name| encryptable_name.into_inner()), ) }) .collect::<HashMap<_, _>>(); let master_key = &state.store.get_master_key().to_vec().into(); let profile_name_map = futures::future::try_join_all(profile_ids_with_merchant_ids.iter().map( |(profile_id, merchant_id)| async { let merchant_key_store = state .store .get_merchant_key_store_by_merchant_id(key_manager_state, merchant_id, master_key) .await .change_context(UserErrors::InternalServerError)?; let business_profile = state .store .find_business_profile_by_profile_id( key_manager_state, &merchant_key_store, profile_id, ) .await .change_context(UserErrors::InternalServerError)?; Ok::<_, error_stack::Report<UserErrors>>(( profile_id.clone(), Secret::new(business_profile.profile_name), )) }, )) .await? .into_iter() .collect::<HashMap<_, _>>(); user_roles .into_iter() .map(|user_role| { let (entity_id, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError) .attach_printable("Failed to compute entity id and type")?; let entity_name = match entity_type { EntityType::Tenant => { return Err(report!(UserErrors::InternalServerError)) .attach_printable("Tenant roles are not allowed for this operation"); } EntityType::Organization => user_role .org_id .as_ref() .and_then(|org_id| org_name_map.get(org_id).cloned()) .ok_or(UserErrors::InternalServerError)?, EntityType::Merchant => user_role .merchant_id .as_ref() .and_then(|merchant_id| merchant_name_map.get(merchant_id).cloned()) .ok_or(UserErrors::InternalServerError)?, EntityType::Profile => user_role .profile_id .as_ref() .map(|profile_id| profile_name_map.get(profile_id).cloned()) .ok_or(UserErrors::InternalServerError)?, }; Ok(user_role_api::ListInvitationForUserResponse { entity_id, entity_type, entity_name, role_id: user_role.role_id, }) }) .collect::<Result<Vec<_>, _>>() .map(ApplicationResponse::Json) } </file>
{ "crate": "router", "file": "crates/router/src/core/user_role.rs", "files": null, "module": null, "num_files": null, "token_count": 7809 }
large_file_5732372792088767618
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/unified_connector_service.rs </path> <file> 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(()) } </file>
{ "crate": "router", "file": "crates/router/src/core/unified_connector_service.rs", "files": null, "module": null, "num_files": null, "token_count": 8721 }
large_file_2793034049759833760
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/payment_link.rs </path> <file> pub mod validator; use std::collections::HashMap; use actix_web::http::header; use api_models::{ admin::PaymentLinkConfig, payments::{PaymentLinkData, PaymentLinkStatusWrap}, }; use common_utils::{ consts::{DEFAULT_LOCALE, DEFAULT_SESSION_EXPIRY}, ext_traits::{OptionExt, ValueExt}, types::{AmountConvertor, StringMajorUnitForCore}, }; use error_stack::{report, ResultExt}; use futures::future; use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData}; use masking::{PeekInterface, Secret}; use router_env::logger; use time::PrimitiveDateTime; use super::{ errors::{self, RouterResult, StorageErrorExt}, payments::helpers, }; use crate::{ consts::{ self, DEFAULT_ALLOWED_DOMAINS, DEFAULT_BACKGROUND_COLOR, DEFAULT_DISPLAY_SDK_ONLY, DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, DEFAULT_HIDE_CARD_NICKNAME_FIELD, DEFAULT_MERCHANT_LOGO, DEFAULT_PRODUCT_IMG, DEFAULT_SDK_LAYOUT, DEFAULT_SHOW_CARD_FORM, }, errors::RouterResponse, get_payment_link_config_value, get_payment_link_config_value_based_on_priority, routes::SessionState, services, types::{ api::payment_link::PaymentLinkResponseExt, domain, storage::{enums as storage_enums, payment_link::PaymentLink}, transformers::{ForeignFrom, ForeignInto}, }, }; pub async fn retrieve_payment_link( state: SessionState, payment_link_id: String, ) -> RouterResponse<api_models::payments::RetrievePaymentLinkResponse> { let db = &*state.store; let payment_link_config = db .find_payment_link_by_payment_link_id(&payment_link_id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?; let session_expiry = payment_link_config.fulfilment_time.unwrap_or_else(|| { common_utils::date_time::now() .saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY)) }); let status = check_payment_link_status(session_expiry); let response = api_models::payments::RetrievePaymentLinkResponse::foreign_from(( payment_link_config, status, )); Ok(services::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] pub async fn form_payment_link_data( state: &SessionState, merchant_context: domain::MerchantContext, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, ) -> RouterResult<(PaymentLink, PaymentLinkData, PaymentLinkConfig)> { todo!() } #[cfg(feature = "v1")] pub async fn form_payment_link_data( state: &SessionState, merchant_context: domain::MerchantContext, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, ) -> RouterResult<(PaymentLink, PaymentLinkData, PaymentLinkConfig)> { let db = &*state.store; let key_manager_state = &state.into(); let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(state).into(), &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_link_id = payment_intent .payment_link_id .get_required_value("payment_link_id") .change_context(errors::ApiErrorResponse::PaymentLinkNotFound)?; let merchant_name_from_merchant_account = merchant_context .get_merchant_account() .merchant_name .clone() .map(|merchant_name| merchant_name.into_inner().peek().to_owned()) .unwrap_or_default(); let payment_link = db .find_payment_link_by_payment_link_id(&payment_link_id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?; let payment_link_config = if let Some(pl_config_value) = payment_link.payment_link_config.clone() { extract_payment_link_config(pl_config_value)? } else { PaymentLinkConfig { theme: DEFAULT_BACKGROUND_COLOR.to_string(), logo: DEFAULT_MERCHANT_LOGO.to_string(), seller_name: merchant_name_from_merchant_account, sdk_layout: DEFAULT_SDK_LAYOUT.to_owned(), display_sdk_only: DEFAULT_DISPLAY_SDK_ONLY, enabled_saved_payment_method: DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, hide_card_nickname_field: DEFAULT_HIDE_CARD_NICKNAME_FIELD, show_card_form_by_default: DEFAULT_SHOW_CARD_FORM, allowed_domains: DEFAULT_ALLOWED_DOMAINS, transaction_details: None, background_image: None, details_layout: None, branding_visibility: None, payment_button_text: None, custom_message_for_card_terms: None, payment_button_colour: None, skip_status_screen: None, background_colour: None, payment_button_text_colour: None, sdk_ui_rules: None, payment_link_ui_rules: None, enable_button_only_on_form_ready: DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, payment_form_header_text: None, payment_form_label_type: None, show_card_terms: None, is_setup_mandate_flow: None, color_icon_card_cvc_error: None, } }; let profile_id = payment_link .profile_id .clone() .or(payment_intent.profile_id) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Profile id missing in payment link and 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 return_url = if let Some(payment_create_return_url) = payment_intent.return_url.clone() { payment_create_return_url } else { business_profile .return_url .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "return_url", })? }; let (currency, client_secret) = validate_sdk_requirements( payment_intent.currency, payment_intent.client_secret.clone(), )?; let required_conversion_type = StringMajorUnitForCore; let amount = required_conversion_type .convert(payment_intent.amount, currency) .change_context(errors::ApiErrorResponse::AmountConversionFailed { amount_type: "StringMajorUnit", })?; let order_details = validate_order_details(payment_intent.order_details.clone(), currency)?; let session_expiry = payment_link.fulfilment_time.unwrap_or_else(|| { payment_intent .created_at .saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY)) }); // converting first letter of merchant name to upperCase let merchant_name = capitalize_first_char(&payment_link_config.seller_name); let payment_link_status = check_payment_link_status(session_expiry); let is_payment_link_terminal_state = check_payment_link_invalid_conditions( payment_intent.status, &[ storage_enums::IntentStatus::Cancelled, storage_enums::IntentStatus::Failed, storage_enums::IntentStatus::Processing, storage_enums::IntentStatus::RequiresCapture, storage_enums::IntentStatus::RequiresMerchantAction, storage_enums::IntentStatus::Succeeded, storage_enums::IntentStatus::PartiallyCaptured, storage_enums::IntentStatus::RequiresCustomerAction, ], ); 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(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; if is_payment_link_terminal_state || payment_link_status == api_models::payments::PaymentLinkStatus::Expired { let status = match payment_link_status { api_models::payments::PaymentLinkStatus::Active => { logger::info!("displaying status page as the requested payment link has reached terminal state with payment status as {:?}", payment_intent.status); PaymentLinkStatusWrap::IntentStatus(payment_intent.status) } api_models::payments::PaymentLinkStatus::Expired => { if is_payment_link_terminal_state { logger::info!("displaying status page as the requested payment link has reached terminal state with payment status as {:?}", payment_intent.status); PaymentLinkStatusWrap::IntentStatus(payment_intent.status) } else { logger::info!( "displaying status page as the requested payment link has expired" ); PaymentLinkStatusWrap::PaymentLinkStatus( api_models::payments::PaymentLinkStatus::Expired, ) } } }; 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(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_details = api_models::payments::PaymentLinkStatusDetails { amount, currency, payment_id: payment_intent.payment_id, merchant_name, merchant_logo: payment_link_config.logo.clone(), created: payment_link.created_at, status, error_code: payment_attempt.error_code, error_message: payment_attempt.error_message, redirect: false, theme: payment_link_config.theme.clone(), return_url: return_url.clone(), locale: Some(state.clone().locale), transaction_details: payment_link_config.transaction_details.clone(), unified_code: payment_attempt.unified_code, unified_message: payment_attempt.unified_message, capture_method: payment_attempt.capture_method, setup_future_usage_applied: payment_attempt.setup_future_usage_applied, }; return Ok(( payment_link, PaymentLinkData::PaymentLinkStatusDetails(Box::new(payment_details)), payment_link_config, )); }; let payment_link_details = api_models::payments::PaymentLinkDetails { amount, currency, payment_id: payment_intent.payment_id, merchant_name, order_details, return_url, session_expiry, pub_key: merchant_context .get_merchant_account() .publishable_key .to_owned(), client_secret, merchant_logo: payment_link_config.logo.clone(), max_items_visible_after_collapse: 3, theme: payment_link_config.theme.clone(), merchant_description: payment_intent.description, sdk_layout: payment_link_config.sdk_layout.clone(), display_sdk_only: payment_link_config.display_sdk_only, hide_card_nickname_field: payment_link_config.hide_card_nickname_field, show_card_form_by_default: payment_link_config.show_card_form_by_default, locale: Some(state.clone().locale), transaction_details: payment_link_config.transaction_details.clone(), background_image: payment_link_config.background_image.clone(), details_layout: payment_link_config.details_layout, branding_visibility: payment_link_config.branding_visibility, payment_button_text: payment_link_config.payment_button_text.clone(), custom_message_for_card_terms: payment_link_config.custom_message_for_card_terms.clone(), payment_button_colour: payment_link_config.payment_button_colour.clone(), skip_status_screen: payment_link_config.skip_status_screen, background_colour: payment_link_config.background_colour.clone(), payment_button_text_colour: payment_link_config.payment_button_text_colour.clone(), sdk_ui_rules: payment_link_config.sdk_ui_rules.clone(), status: payment_intent.status, enable_button_only_on_form_ready: payment_link_config.enable_button_only_on_form_ready, payment_form_header_text: payment_link_config.payment_form_header_text.clone(), payment_form_label_type: payment_link_config.payment_form_label_type, show_card_terms: payment_link_config.show_card_terms, is_setup_mandate_flow: payment_link_config.is_setup_mandate_flow, color_icon_card_cvc_error: payment_link_config.color_icon_card_cvc_error.clone(), capture_method: payment_attempt.capture_method, setup_future_usage_applied: payment_attempt.setup_future_usage_applied, }; Ok(( payment_link, PaymentLinkData::PaymentLinkDetails(Box::new(payment_link_details)), payment_link_config, )) } pub async fn initiate_secure_payment_link_flow( state: SessionState, merchant_context: domain::MerchantContext, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, request_headers: &header::HeaderMap, ) -> RouterResponse<services::PaymentLinkFormData> { let (payment_link, payment_link_details, payment_link_config) = form_payment_link_data(&state, merchant_context, merchant_id, payment_id).await?; validator::validate_secure_payment_link_render_request( request_headers, &payment_link, &payment_link_config, )?; let css_script = get_payment_link_css_script(&payment_link_config)?; match payment_link_details { PaymentLinkData::PaymentLinkStatusDetails(ref status_details) => { let js_script = get_js_script(&payment_link_details)?; let payment_link_error_data = services::PaymentLinkStatusData { js_script, css_script, }; logger::info!( "payment link data, for building payment link status page {:?}", status_details ); Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_error_data), ))) } PaymentLinkData::PaymentLinkDetails(link_details) => { let secure_payment_link_details = api_models::payments::SecurePaymentLinkDetails { enabled_saved_payment_method: payment_link_config.enabled_saved_payment_method, hide_card_nickname_field: payment_link_config.hide_card_nickname_field, show_card_form_by_default: payment_link_config.show_card_form_by_default, payment_link_details: *link_details.to_owned(), payment_button_text: payment_link_config.payment_button_text, custom_message_for_card_terms: payment_link_config.custom_message_for_card_terms, payment_button_colour: payment_link_config.payment_button_colour, skip_status_screen: payment_link_config.skip_status_screen, background_colour: payment_link_config.background_colour, payment_button_text_colour: payment_link_config.payment_button_text_colour, sdk_ui_rules: payment_link_config.sdk_ui_rules, enable_button_only_on_form_ready: payment_link_config .enable_button_only_on_form_ready, payment_form_header_text: payment_link_config.payment_form_header_text, payment_form_label_type: payment_link_config.payment_form_label_type, show_card_terms: payment_link_config.show_card_terms, color_icon_card_cvc_error: payment_link_config.color_icon_card_cvc_error, }; let payment_details_str = serde_json::to_string(&secure_payment_link_details) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize PaymentLinkData")?; let url_encoded_str = urlencoding::encode(&payment_details_str); let js_script = format!("window.__PAYMENT_DETAILS = '{url_encoded_str}';"); let html_meta_tags = get_meta_tags_html(&link_details); let payment_link_data = services::PaymentLinkFormData { js_script, sdk_url: state.conf.payment_link.sdk_url.clone(), css_script, html_meta_tags, }; let allowed_domains = payment_link_config .allowed_domains .clone() .ok_or(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| { format!( "Invalid list of allowed_domains found - {:?}", payment_link_config.allowed_domains.clone() ) })?; if allowed_domains.is_empty() { return Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| { format!( "Invalid list of allowed_domains found - {:?}", payment_link_config.allowed_domains.clone() ) }); } let link_data = GenericLinks { allowed_domains, data: GenericLinksData::SecurePaymentLink(payment_link_data), locale: DEFAULT_LOCALE.to_string(), }; logger::info!( "payment link data, for building secure payment link {:?}", link_data ); Ok(services::ApplicationResponse::GenericLinkForm(Box::new( link_data, ))) } } } pub async fn initiate_payment_link_flow( state: SessionState, merchant_context: domain::MerchantContext, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, ) -> RouterResponse<services::PaymentLinkFormData> { let (_, payment_details, payment_link_config) = form_payment_link_data(&state, merchant_context, merchant_id, payment_id).await?; let css_script = get_payment_link_css_script(&payment_link_config)?; let js_script = get_js_script(&payment_details)?; match payment_details { PaymentLinkData::PaymentLinkStatusDetails(status_details) => { let payment_link_error_data = services::PaymentLinkStatusData { js_script, css_script, }; logger::info!( "payment link data, for building payment link status page {:?}", status_details ); Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_error_data), ))) } PaymentLinkData::PaymentLinkDetails(payment_details) => { let html_meta_tags = get_meta_tags_html(&payment_details); let payment_link_data = services::PaymentLinkFormData { js_script, sdk_url: state.conf.payment_link.sdk_url.clone(), css_script, html_meta_tags, }; logger::info!( "payment link data, for building open payment link {:?}", payment_link_data ); Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkFormData(payment_link_data), ))) } } } /* The get_js_script function is used to inject dynamic value to payment_link sdk, which is unique to every payment. */ fn get_js_script(payment_details: &PaymentLinkData) -> RouterResult<String> { let payment_details_str = serde_json::to_string(payment_details) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize PaymentLinkData")?; let url_encoded_str = urlencoding::encode(&payment_details_str); Ok(format!("window.__PAYMENT_DETAILS = '{url_encoded_str}';")) } fn camel_to_kebab(s: &str) -> String { let mut result = String::new(); if s.is_empty() { return result; } let chars: Vec<char> = s.chars().collect(); for (i, &ch) in chars.iter().enumerate() { if ch.is_uppercase() { let should_add_dash = i > 0 && (chars.get(i - 1).map(|c| c.is_lowercase()).unwrap_or(false) || (i + 1 < chars.len() && chars.get(i + 1).map(|c| c.is_lowercase()).unwrap_or(false) && chars.get(i - 1).map(|c| c.is_uppercase()).unwrap_or(false))); if should_add_dash { result.push('-'); } result.push(ch.to_ascii_lowercase()); } else { result.push(ch); } } result } fn generate_dynamic_css( rules: &HashMap<String, HashMap<String, String>>, ) -> Result<String, errors::ApiErrorResponse> { if rules.is_empty() { return Ok(String::new()); } let mut css_string = String::new(); css_string.push_str("/* Dynamically Injected UI Rules */\n"); for (selector, styles_map) in rules { if selector.trim().is_empty() { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "CSS selector cannot be empty.".to_string(), }); } css_string.push_str(selector); css_string.push_str(" {\n"); for (prop_camel_case, css_value) in styles_map { let css_property = camel_to_kebab(prop_camel_case); css_string.push_str(" "); css_string.push_str(&css_property); css_string.push_str(": "); css_string.push_str(css_value); css_string.push_str(";\n"); } css_string.push_str("}\n"); } Ok(css_string) } fn get_payment_link_css_script( payment_link_config: &PaymentLinkConfig, ) -> Result<String, errors::ApiErrorResponse> { let custom_rules_css_option = payment_link_config .payment_link_ui_rules .as_ref() .map(generate_dynamic_css) .transpose()?; let color_scheme_css = get_color_scheme_css(payment_link_config); if let Some(custom_rules_css) = custom_rules_css_option { Ok(format!("{color_scheme_css}\n{custom_rules_css}")) } else { Ok(color_scheme_css) } } fn get_color_scheme_css(payment_link_config: &PaymentLinkConfig) -> String { let background_primary_color = payment_link_config .background_colour .clone() .unwrap_or(payment_link_config.theme.clone()); format!( ":root {{ --primary-color: {background_primary_color}; }}" ) } fn get_meta_tags_html(payment_details: &api_models::payments::PaymentLinkDetails) -> String { format!( r#"<meta property="og:title" content="Payment request from {0}"/> <meta property="og:description" content="{1}"/>"#, payment_details.merchant_name.clone(), payment_details .merchant_description .clone() .unwrap_or_default() ) } fn validate_sdk_requirements( currency: Option<api_models::enums::Currency>, client_secret: Option<String>, ) -> Result<(api_models::enums::Currency, String), errors::ApiErrorResponse> { let currency = currency.ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "currency", })?; let client_secret = client_secret.ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "client_secret", })?; Ok((currency, client_secret)) } pub async fn list_payment_link( state: SessionState, merchant: domain::MerchantAccount, constraints: api_models::payments::PaymentLinkListConstraints, ) -> RouterResponse<Vec<api_models::payments::RetrievePaymentLinkResponse>> { let db = state.store.as_ref(); let payment_link = db .list_payment_link_by_merchant_id(merchant.get_id(), constraints) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to retrieve payment link")?; let payment_link_list = future::try_join_all(payment_link.into_iter().map(|payment_link| { api_models::payments::RetrievePaymentLinkResponse::from_db_payment_link(payment_link) })) .await?; Ok(services::ApplicationResponse::Json(payment_link_list)) } pub fn check_payment_link_status( payment_link_expiry: PrimitiveDateTime, ) -> api_models::payments::PaymentLinkStatus { let curr_time = common_utils::date_time::now(); if curr_time > payment_link_expiry { api_models::payments::PaymentLinkStatus::Expired } else { api_models::payments::PaymentLinkStatus::Active } } fn validate_order_details( order_details: Option<Vec<Secret<serde_json::Value>>>, currency: api_models::enums::Currency, ) -> Result< Option<Vec<api_models::payments::OrderDetailsWithStringAmount>>, error_stack::Report<errors::ApiErrorResponse>, > { let required_conversion_type = StringMajorUnitForCore; let order_details = 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<api_models::payments::OrderDetailsWithAmount>, _>>() }) .transpose()?; let updated_order_details = match order_details { Some(mut order_details) => { let mut order_details_amount_string_array: Vec< api_models::payments::OrderDetailsWithStringAmount, > = Vec::new(); for order in order_details.iter_mut() { let mut order_details_amount_string : api_models::payments::OrderDetailsWithStringAmount = Default::default(); if order.product_img_link.is_none() { order_details_amount_string.product_img_link = Some(DEFAULT_PRODUCT_IMG.to_string()) } else { order_details_amount_string .product_img_link .clone_from(&order.product_img_link) }; order_details_amount_string.amount = required_conversion_type .convert(order.amount, currency) .change_context(errors::ApiErrorResponse::AmountConversionFailed { amount_type: "StringMajorUnit", })?; order_details_amount_string.product_name = capitalize_first_char(&order.product_name.clone()); order_details_amount_string.quantity = order.quantity; order_details_amount_string_array.push(order_details_amount_string) } Some(order_details_amount_string_array) } None => None, }; Ok(updated_order_details) } pub fn extract_payment_link_config( pl_config: serde_json::Value, ) -> Result<PaymentLinkConfig, error_stack::Report<errors::ApiErrorResponse>> { serde_json::from_value::<PaymentLinkConfig>(pl_config).change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "payment_link_config", }, ) } pub fn get_payment_link_config_based_on_priority( payment_create_link_config: Option<api_models::payments::PaymentCreatePaymentLinkConfig>, business_link_config: Option<diesel_models::business_profile::BusinessPaymentLinkConfig>, merchant_name: String, default_domain_name: String, payment_link_config_id: Option<String>, ) -> Result<(PaymentLinkConfig, String), error_stack::Report<errors::ApiErrorResponse>> { let (domain_name, business_theme_configs, allowed_domains, branding_visibility) = if let Some(business_config) = business_link_config { ( business_config .domain_name .clone() .map(|d_name| { logger::info!("domain name set to custom domain https://{:?}", d_name); format!("https://{d_name}") }) .unwrap_or_else(|| default_domain_name.clone()), payment_link_config_id .and_then(|id| { business_config .business_specific_configs .as_ref() .and_then(|specific_configs| specific_configs.get(&id).cloned()) }) .or(business_config.default_config), business_config.allowed_domains, business_config.branding_visibility, ) } else { (default_domain_name, None, None, None) }; let ( theme, logo, seller_name, sdk_layout, display_sdk_only, enabled_saved_payment_method, hide_card_nickname_field, show_card_form_by_default, enable_button_only_on_form_ready, ) = get_payment_link_config_value!( payment_create_link_config, business_theme_configs, (theme, DEFAULT_BACKGROUND_COLOR.to_string()), (logo, DEFAULT_MERCHANT_LOGO.to_string()), (seller_name, merchant_name.clone()), (sdk_layout, DEFAULT_SDK_LAYOUT.to_owned()), (display_sdk_only, DEFAULT_DISPLAY_SDK_ONLY), ( enabled_saved_payment_method, DEFAULT_ENABLE_SAVED_PAYMENT_METHOD ), (hide_card_nickname_field, DEFAULT_HIDE_CARD_NICKNAME_FIELD), (show_card_form_by_default, DEFAULT_SHOW_CARD_FORM), ( enable_button_only_on_form_ready, DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY ) ); let ( details_layout, background_image, payment_button_text, custom_message_for_card_terms, payment_button_colour, skip_status_screen, background_colour, payment_button_text_colour, sdk_ui_rules, payment_link_ui_rules, payment_form_header_text, payment_form_label_type, show_card_terms, is_setup_mandate_flow, color_icon_card_cvc_error, ) = get_payment_link_config_value!( payment_create_link_config, business_theme_configs, (details_layout), (background_image, |background_image| background_image .foreign_into()), (payment_button_text), (custom_message_for_card_terms), (payment_button_colour), (skip_status_screen), (background_colour), (payment_button_text_colour), (sdk_ui_rules), (payment_link_ui_rules), (payment_form_header_text), (payment_form_label_type), (show_card_terms), (is_setup_mandate_flow), (color_icon_card_cvc_error), ); let payment_link_config = PaymentLinkConfig { theme, logo, seller_name, sdk_layout, display_sdk_only, enabled_saved_payment_method, hide_card_nickname_field, show_card_form_by_default, allowed_domains, branding_visibility, skip_status_screen, transaction_details: payment_create_link_config.as_ref().and_then( |payment_link_config| payment_link_config.theme_config.transaction_details.clone(), ), details_layout, background_image, payment_button_text, custom_message_for_card_terms, payment_button_colour, background_colour, payment_button_text_colour, sdk_ui_rules, payment_link_ui_rules, enable_button_only_on_form_ready, payment_form_header_text, payment_form_label_type, show_card_terms, is_setup_mandate_flow, color_icon_card_cvc_error, }; Ok((payment_link_config, domain_name)) } fn capitalize_first_char(s: &str) -> String { if let Some(first_char) = s.chars().next() { let capitalized = first_char.to_uppercase(); let mut result = capitalized.to_string(); if let Some(remaining) = s.get(1..) { result.push_str(remaining); } result } else { s.to_owned() } } fn check_payment_link_invalid_conditions( intent_status: storage_enums::IntentStatus, not_allowed_statuses: &[storage_enums::IntentStatus], ) -> bool { not_allowed_statuses.contains(&intent_status) } #[cfg(feature = "v2")] pub async fn get_payment_link_status( _state: SessionState, _merchant_context: domain::MerchantContext, _merchant_id: common_utils::id_type::MerchantId, _payment_id: common_utils::id_type::PaymentId, ) -> RouterResponse<services::PaymentLinkFormData> { todo!() } #[cfg(feature = "v1")] pub async fn get_payment_link_status( state: SessionState, merchant_context: domain::MerchantContext, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, ) -> RouterResponse<services::PaymentLinkFormData> { let db = &*state.store; let key_manager_state = &(&state).into(); 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(), merchant_context.get_merchant_account().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(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_link_id = payment_intent .payment_link_id .get_required_value("payment_link_id") .change_context(errors::ApiErrorResponse::PaymentLinkNotFound)?; let merchant_name_from_merchant_account = merchant_context .get_merchant_account() .merchant_name .clone() .map(|merchant_name| merchant_name.into_inner().peek().to_owned()) .unwrap_or_default(); let payment_link = db .find_payment_link_by_payment_link_id(&payment_link_id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?; let payment_link_config = if let Some(pl_config_value) = payment_link.payment_link_config { extract_payment_link_config(pl_config_value)? } else { PaymentLinkConfig { theme: DEFAULT_BACKGROUND_COLOR.to_string(), logo: DEFAULT_MERCHANT_LOGO.to_string(), seller_name: merchant_name_from_merchant_account, sdk_layout: DEFAULT_SDK_LAYOUT.to_owned(), display_sdk_only: DEFAULT_DISPLAY_SDK_ONLY, enabled_saved_payment_method: DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, hide_card_nickname_field: DEFAULT_HIDE_CARD_NICKNAME_FIELD, show_card_form_by_default: DEFAULT_SHOW_CARD_FORM, allowed_domains: DEFAULT_ALLOWED_DOMAINS, transaction_details: None, background_image: None, details_layout: None, branding_visibility: None, payment_button_text: None, custom_message_for_card_terms: None, payment_button_colour: None, skip_status_screen: None, background_colour: None, payment_button_text_colour: None, sdk_ui_rules: None, payment_link_ui_rules: None, enable_button_only_on_form_ready: DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, payment_form_header_text: None, payment_form_label_type: None, show_card_terms: None, is_setup_mandate_flow: None, color_icon_card_cvc_error: None, } }; let currency = payment_intent .currency .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "currency", })?; let required_conversion_type = StringMajorUnitForCore; let amount = required_conversion_type .convert(payment_attempt.get_total_amount(), currency) .change_context(errors::ApiErrorResponse::AmountConversionFailed { amount_type: "StringMajorUnit", })?; // converting first letter of merchant name to upperCase let merchant_name = capitalize_first_char(&payment_link_config.seller_name); let css_script = get_color_scheme_css(&payment_link_config); let profile_id = payment_link .profile_id .or(payment_intent.profile_id) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Profile id missing in payment link and 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 return_url = if let Some(payment_create_return_url) = payment_intent.return_url.clone() { payment_create_return_url } else { business_profile .return_url .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "return_url", })? }; let (unified_code, unified_message) = if let Some((code, message)) = payment_attempt .unified_code .as_ref() .zip(payment_attempt.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 = helpers::get_unified_translation( &state, unified_code.to_owned(), unified_message.to_owned(), state.locale.clone(), ) .await .or(Some(unified_message)); let payment_details = api_models::payments::PaymentLinkStatusDetails { amount, currency, payment_id: payment_intent.payment_id, merchant_name, merchant_logo: payment_link_config.logo.clone(), created: payment_link.created_at, status: PaymentLinkStatusWrap::IntentStatus(payment_intent.status), error_code: payment_attempt.error_code, error_message: payment_attempt.error_message, redirect: true, theme: payment_link_config.theme.clone(), return_url, locale: Some(state.locale.clone()), transaction_details: payment_link_config.transaction_details, unified_code: Some(unified_code), unified_message: unified_translated_message, capture_method: payment_attempt.capture_method, setup_future_usage_applied: payment_attempt.setup_future_usage_applied, }; let js_script = get_js_script(&PaymentLinkData::PaymentLinkStatusDetails(Box::new( payment_details, )))?; let payment_link_status_data = services::PaymentLinkStatusData { js_script, css_script, }; Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_status_data), ))) } </file>
{ "crate": "router", "file": "crates/router/src/core/payment_link.rs", "files": null, "module": null, "num_files": null, "token_count": 8028 }
large_file_972243027068960646
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/recon.rs </path> <file> use api_models::recon as recon_api; #[cfg(feature = "email")] use common_utils::{ext_traits::AsyncExt, types::user::ThemeLineage}; use error_stack::ResultExt; #[cfg(feature = "email")] use masking::{ExposeInterface, PeekInterface, Secret}; #[cfg(feature = "email")] use crate::{ consts, services::email::types as email_types, types::domain, utils::user::theme as theme_utils, }; use crate::{ core::errors::{self, RouterResponse, UserErrors, UserResponse}, services::{api as service_api, authentication}, types::{ api::{self as api_types, enums}, storage, transformers::ForeignTryFrom, }, utils::user as user_utils, SessionState, }; #[allow(unused_variables)] pub async fn send_recon_request( state: SessionState, auth_data: authentication::AuthenticationDataWithUser, ) -> RouterResponse<recon_api::ReconStatusResponse> { #[cfg(not(feature = "email"))] return Ok(service_api::ApplicationResponse::Json( recon_api::ReconStatusResponse { recon_status: enums::ReconStatus::NotRequested, }, )); #[cfg(feature = "email")] { let user_in_db = &auth_data.user; let merchant_id = auth_data.merchant_account.get_id().clone(); let theme = theme_utils::get_most_specific_theme_using_lineage( &state.clone(), ThemeLineage::Merchant { tenant_id: state.tenant.tenant_id.clone(), org_id: auth_data.merchant_account.get_org_id().clone(), merchant_id: merchant_id.clone(), }, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!( "Failed to fetch theme for merchant_id = {merchant_id:?}", ))?; let user_email = user_in_db.email.clone(); let email_contents = email_types::ProFeatureRequest { feature_name: consts::RECON_FEATURE_TAG.to_string(), merchant_id: merchant_id.clone(), user_name: domain::UserName::new(user_in_db.name.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to form username")?, user_email: domain::UserEmail::from_pii_email(user_email.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert recipient's email to UserEmail")?, recipient_email: domain::UserEmail::from_pii_email( state.conf.email.recon_recipient_email.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert recipient's email to UserEmail")?, subject: format!( "{} {}", consts::EMAIL_SUBJECT_DASHBOARD_FEATURE_REQUEST, user_email.expose().peek() ), theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), theme_config: theme .map(|theme| theme.email_config()) .unwrap_or(state.conf.theme.email_config.clone()), }; state .email_client .compose_and_send_email( user_utils::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to compose and send email for ProFeatureRequest [Recon]") .async_and_then(|_| async { let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate { recon_status: enums::ReconStatus::Requested, }; let db = &*state.store; let key_manager_state = &(&state).into(); let response = db .update_merchant( key_manager_state, auth_data.merchant_account, updated_merchant_account, &auth_data.key_store, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("Failed while updating merchant's recon status: {merchant_id:?}") })?; Ok(service_api::ApplicationResponse::Json( recon_api::ReconStatusResponse { recon_status: response.recon_status, }, )) }) .await } } pub async fn generate_recon_token( state: SessionState, user_with_role: authentication::UserFromTokenWithRoleInfo, ) -> RouterResponse<recon_api::ReconTokenResponse> { let user = user_with_role.user; let token = authentication::ReconToken::new_token( user.user_id.clone(), user.merchant_id.clone(), &state.conf, user.org_id.clone(), user.profile_id.clone(), user.tenant_id, user_with_role.role_info, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed to create recon token for params [user_id, org_id, mid, pid] [{}, {:?}, {:?}, {:?}]", user.user_id, user.org_id, user.merchant_id, user.profile_id, ) })?; Ok(service_api::ApplicationResponse::Json( recon_api::ReconTokenResponse { token: token.into(), }, )) } pub async fn recon_merchant_account_update( state: SessionState, auth: authentication::AuthenticationData, req: recon_api::ReconUpdateMerchantRequest, ) -> RouterResponse<api_types::MerchantAccountResponse> { let db = &*state.store; let key_manager_state = &(&state).into(); let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate { recon_status: req.recon_status, }; let merchant_id = auth.merchant_account.get_id().clone(); let updated_merchant_account = db .update_merchant( key_manager_state, auth.merchant_account.clone(), updated_merchant_account, &auth.key_store, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("Failed while updating merchant's recon status: {merchant_id:?}") })?; #[cfg(feature = "email")] { let user_email = &req.user_email.clone(); let theme = theme_utils::get_most_specific_theme_using_lineage( &state.clone(), ThemeLineage::Merchant { tenant_id: state.tenant.tenant_id.clone(), org_id: auth.merchant_account.get_org_id().clone(), merchant_id: merchant_id.clone(), }, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!( "Failed to fetch theme for merchant_id = {merchant_id:?}", ))?; let email_contents = email_types::ReconActivation { recipient_email: domain::UserEmail::from_pii_email(user_email.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to convert recipient's email to UserEmail from pii::Email", )?, user_name: domain::UserName::new(Secret::new("HyperSwitch User".to_string())) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to form username")?, subject: consts::EMAIL_SUBJECT_APPROVAL_RECON_REQUEST, theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), theme_config: theme .map(|theme| theme.email_config()) .unwrap_or(state.conf.theme.email_config.clone()), }; if req.recon_status == enums::ReconStatus::Active { let _ = state .email_client .compose_and_send_email( user_utils::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) .await .inspect_err(|err| { router_env::logger::error!( "Failed to compose and send email notifying them of recon activation: {}", err ) }) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to compose and send email for ReconActivation"); } } Ok(service_api::ApplicationResponse::Json( api_types::MerchantAccountResponse::foreign_try_from(updated_merchant_account) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_account", })?, )) } pub async fn verify_recon_token( state: SessionState, user_with_role: authentication::UserFromTokenWithRoleInfo, ) -> UserResponse<recon_api::VerifyTokenResponse> { let user = user_with_role.user; let user_in_db = user .get_user_from_db(&state) .await .attach_printable_lazy(|| { format!( "Failed to fetch the user from DB for user_id - {}", user.user_id ) })?; let acl = user_with_role.role_info.get_recon_acl(); let optional_acl_str = serde_json::to_string(&acl) .inspect_err(|err| router_env::logger::error!("Failed to serialize acl to string: {}", err)) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to serialize acl to string. Using empty ACL") .ok(); Ok(service_api::ApplicationResponse::Json( recon_api::VerifyTokenResponse { merchant_id: user.merchant_id.to_owned(), user_email: user_in_db.0.email, acl: optional_acl_str, }, )) } </file>
{ "crate": "router", "file": "crates/router/src/core/recon.rs", "files": null, "module": null, "num_files": null, "token_count": 2055 }
large_file_51776309640133725
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/api_keys.rs </path> <file> 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) } } </file>
{ "crate": "router", "file": "crates/router/src/core/api_keys.rs", "files": null, "module": null, "num_files": null, "token_count": 4679 }
large_file_-2988524368866135881
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/errors.rs </path> <file> 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, } </file>
{ "crate": "router", "file": "crates/router/src/core/errors.rs", "files": null, "module": null, "num_files": null, "token_count": 4143 }
large_file_4352363565840316323
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/customers.rs </path> <file> 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(())) } </file>
{ "crate": "router", "file": "crates/router/src/core/customers.rs", "files": null, "module": null, "num_files": null, "token_count": 10763 }
large_file_-4455436288523738432
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/revenue_recovery.rs </path> <file> pub mod api; pub mod transformers; pub mod types; use std::marker::PhantomData; use api_models::{ enums, payments::{self as api_payments, PaymentsGetIntentRequest, PaymentsResponse}, process_tracker::revenue_recovery, webhooks, }; use common_utils::{ self, errors::CustomResult, ext_traits::{AsyncExt, OptionExt, ValueExt}, id_type, }; use diesel_models::{enums as diesel_enum, process_tracker::business_status}; use error_stack::{self, report, ResultExt}; use hyperswitch_domain_models::{ merchant_context, payments::{PaymentIntent, PaymentIntentData, PaymentStatusData}, revenue_recovery as domain_revenue_recovery, ApiModelToDieselModelConvertor, }; use scheduler::errors as sch_errors; use crate::{ core::{ errors::{self, RouterResponse, RouterResult, StorageErrorExt}, payments::{ self, operations::{GetTrackerResponse, Operation}, transformers::GenerateResponse, }, revenue_recovery::types::RevenueRecoveryOutgoingWebhook, }, db::StorageInterface, logger, routes::{app::ReqState, metrics, SessionState}, services::ApplicationResponse, types::{ api as router_api_types, domain, storage::{self, revenue_recovery as pcr}, transformers::{ForeignFrom, ForeignInto}, }, workflows::revenue_recovery as revenue_recovery_workflow, }; pub const CALCULATE_WORKFLOW: &str = "CALCULATE_WORKFLOW"; pub const PSYNC_WORKFLOW: &str = "PSYNC_WORKFLOW"; pub const EXECUTE_WORKFLOW: &str = "EXECUTE_WORKFLOW"; #[allow(clippy::too_many_arguments)] pub async fn upsert_calculate_pcr_task( billing_connector_account: &domain::MerchantConnectorAccount, state: &SessionState, merchant_context: &domain::MerchantContext, recovery_intent_from_payment_intent: &domain_revenue_recovery::RecoveryPaymentIntent, business_profile: &domain::Profile, intent_retry_count: u16, payment_attempt_id: Option<id_type::GlobalAttemptId>, runner: storage::ProcessTrackerRunner, revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType, ) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> { router_env::logger::info!("Starting calculate_job..."); let task = "CALCULATE_WORKFLOW"; let db = &*state.store; let payment_id = &recovery_intent_from_payment_intent.payment_id; // Create process tracker ID in the format: CALCULATE_WORKFLOW_{payment_intent_id} let process_tracker_id = format!("{runner}_{task}_{}", payment_id.get_string_repr()); // Scheduled time is now because this will be the first entry in // process tracker and we dont want to wait let schedule_time = common_utils::date_time::now(); let payment_attempt_id = payment_attempt_id .ok_or(error_stack::report!( errors::RevenueRecoveryError::PaymentAttemptIdNotFound )) .attach_printable("payment attempt id is required for calculate workflow tracking")?; // Check if a process tracker entry already exists for this payment intent let existing_entry = db .as_scheduler() .find_process_by_id(&process_tracker_id) .await .change_context(errors::RevenueRecoveryError::ProcessTrackerResponseError) .attach_printable( "Failed to check for existing calculate workflow process tracker entry", )?; match existing_entry { Some(existing_process) => { router_env::logger::error!( "Found existing CALCULATE_WORKFLOW task with id: {}", existing_process.id ); } None => { // No entry exists - create a new one router_env::logger::info!( "No existing CALCULATE_WORKFLOW task found for payment_intent_id: {}, creating new entry scheduled for 1 hour from now", payment_id.get_string_repr() ); // Create tracking data let calculate_workflow_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData { billing_mca_id: billing_connector_account.get_id(), global_payment_id: payment_id.clone(), merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), profile_id: business_profile.get_id().to_owned(), payment_attempt_id, revenue_recovery_retry, invoice_scheduled_time: None, }; let tag = ["PCR"]; let task = "CALCULATE_WORKFLOW"; let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, calculate_workflow_tracking_data, Some(1), schedule_time, common_types::consts::API_VERSION, ) .change_context(errors::RevenueRecoveryError::ProcessTrackerCreationError) .attach_printable("Failed to construct calculate workflow process tracker entry")?; // Insert into process tracker with status New db.as_scheduler() .insert_process(process_tracker_entry) .await .change_context(errors::RevenueRecoveryError::ProcessTrackerResponseError) .attach_printable( "Failed to enter calculate workflow process_tracker_entry in DB", )?; router_env::logger::info!( "Successfully created new CALCULATE_WORKFLOW task for payment_intent_id: {}", payment_id.get_string_repr() ); metrics::TASKS_ADDED_COUNT.add( 1, router_env::metric_attributes!(("flow", "CalculateWorkflow")), ); } } Ok(webhooks::WebhookResponseTracker::Payment { payment_id: payment_id.clone(), status: recovery_intent_from_payment_intent.status, }) } pub async fn perform_execute_payment( state: &SessionState, execute_task_process: &storage::ProcessTracker, profile: &domain::Profile, merchant_context: domain::MerchantContext, tracking_data: &pcr::RevenueRecoveryWorkflowTrackingData, revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData, payment_intent: &PaymentIntent, ) -> Result<(), sch_errors::ProcessTrackerError> { let db = &*state.store; let mut revenue_recovery_metadata = payment_intent .feature_metadata .as_ref() .and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone()) .get_required_value("Payment Revenue Recovery Metadata")? .convert_back(); let decision = types::Decision::get_decision_based_on_params( state, payment_intent.status, revenue_recovery_metadata .payment_connector_transmission .unwrap_or_default(), payment_intent.active_attempt_id.clone(), revenue_recovery_payment_data, &tracking_data.global_payment_id, ) .await?; // TODO decide if its a global failure or is it requeueable error match decision { types::Decision::Execute => { let connector_customer_id = revenue_recovery_metadata.get_connector_customer_id(); let last_token_used = payment_intent .feature_metadata .as_ref() .and_then(|fm| fm.payment_revenue_recovery_metadata.as_ref()) .map(|rr| { rr.billing_connector_payment_details .payment_processor_token .clone() }); let processor_token = storage::revenue_recovery_redis_operation::RedisTokenManager::get_token_based_on_retry_type( state, &connector_customer_id, tracking_data.revenue_recovery_retry, last_token_used.as_deref(), ) .await .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "Failed to fetch token details from redis".to_string(), })? .ok_or(errors::ApiErrorResponse::GenericNotFoundError { message: "Failed to fetch token details from redis".to_string(), })?; logger::info!("Token fetched from redis success"); let card_info = api_models::payments::AdditionalCardInfo::foreign_from(&processor_token); // record attempt call let record_attempt = api::record_internal_attempt_api( state, payment_intent, revenue_recovery_payment_data, &revenue_recovery_metadata, card_info, &processor_token .payment_processor_token_details .payment_processor_token, ) .await; match record_attempt { Ok(record_attempt_response) => { let action = Box::pin(types::Action::execute_payment( state, revenue_recovery_payment_data.merchant_account.get_id(), payment_intent, execute_task_process, profile, merchant_context, revenue_recovery_payment_data, &revenue_recovery_metadata, &record_attempt_response.id, )) .await?; Box::pin(action.execute_payment_task_response_handler( state, payment_intent, execute_task_process, revenue_recovery_payment_data, &mut revenue_recovery_metadata, )) .await?; } Err(err) => { logger::error!("Error while recording attempt: {:?}", err); let pt_update = storage::ProcessTrackerUpdate::StatusUpdate { status: enums::ProcessTrackerStatus::Pending, business_status: Some(String::from( business_status::EXECUTE_WORKFLOW_REQUEUE, )), }; db.as_scheduler() .update_process(execute_task_process.clone(), pt_update) .await?; } } } types::Decision::Psync(attempt_status, attempt_id) => { // find if a psync task is already present let task = PSYNC_WORKFLOW; let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; let process_tracker_id = attempt_id.get_psync_revenue_recovery_id(task, runner); let psync_process = db.find_process_by_id(&process_tracker_id).await?; match psync_process { Some(_) => { let pcr_status: types::RevenueRecoveryPaymentsAttemptStatus = attempt_status.foreign_into(); pcr_status .update_pt_status_based_on_attempt_status_for_execute_payment( db, execute_task_process, ) .await?; } None => { // insert new psync task insert_psync_pcr_task_to_pt( revenue_recovery_payment_data.billing_mca.get_id().clone(), db, revenue_recovery_payment_data .merchant_account .get_id() .clone(), payment_intent.get_id().clone(), revenue_recovery_payment_data.profile.get_id().clone(), attempt_id.clone(), storage::ProcessTrackerRunner::PassiveRecoveryWorkflow, tracking_data.revenue_recovery_retry, ) .await?; // finish the current task db.as_scheduler() .finish_process_with_business_status( execute_task_process.clone(), business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC, ) .await?; } }; } types::Decision::ReviewForSuccessfulPayment => { // Finish the current task since the payment was a success // And mark it as review as it might have happened through the external system db.finish_process_with_business_status( execute_task_process.clone(), business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_REVIEW, ) .await?; } types::Decision::ReviewForFailedPayment(triggered_by) => { match triggered_by { enums::TriggeredBy::Internal => { // requeue the current tasks to update the fields for rescheduling a payment let pt_update = storage::ProcessTrackerUpdate::StatusUpdate { status: enums::ProcessTrackerStatus::Pending, business_status: Some(String::from( business_status::EXECUTE_WORKFLOW_REQUEUE, )), }; db.as_scheduler() .update_process(execute_task_process.clone(), pt_update) .await?; } enums::TriggeredBy::External => { logger::debug!("Failed Payment Attempt Triggered By External"); // Finish the current task since the payment was a failure by an external source db.as_scheduler() .finish_process_with_business_status( execute_task_process.clone(), business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_REVIEW, ) .await?; } }; } types::Decision::InvalidDecision => { db.finish_process_with_business_status( execute_task_process.clone(), business_status::EXECUTE_WORKFLOW_COMPLETE, ) .await?; logger::warn!("Abnormal State Identified") } } Ok(()) } #[allow(clippy::too_many_arguments)] async fn insert_psync_pcr_task_to_pt( billing_mca_id: id_type::MerchantConnectorAccountId, db: &dyn StorageInterface, merchant_id: id_type::MerchantId, payment_id: id_type::GlobalPaymentId, profile_id: id_type::ProfileId, payment_attempt_id: id_type::GlobalAttemptId, runner: storage::ProcessTrackerRunner, revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType, ) -> RouterResult<storage::ProcessTracker> { let task = PSYNC_WORKFLOW; let process_tracker_id = payment_attempt_id.get_psync_revenue_recovery_id(task, runner); let schedule_time = common_utils::date_time::now(); let psync_workflow_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData { billing_mca_id, global_payment_id: payment_id, merchant_id, profile_id, payment_attempt_id, revenue_recovery_retry, invoice_scheduled_time: Some(schedule_time), }; let tag = ["REVENUE_RECOVERY"]; let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, psync_workflow_tracking_data, None, schedule_time, common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct delete tokenized data process tracker task")?; let response = db .insert_process(process_tracker_entry) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct delete tokenized data process tracker task")?; metrics::TASKS_ADDED_COUNT.add( 1, router_env::metric_attributes!(("flow", "RevenueRecoveryPsync")), ); Ok(response) } pub async fn perform_payments_sync( state: &SessionState, process: &storage::ProcessTracker, profile: &domain::Profile, merchant_context: domain::MerchantContext, tracking_data: &pcr::RevenueRecoveryWorkflowTrackingData, revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData, payment_intent: &PaymentIntent, ) -> Result<(), errors::ProcessTrackerError> { let psync_data = api::call_psync_api( state, &tracking_data.global_payment_id, revenue_recovery_payment_data, true, true, ) .await?; let payment_attempt = psync_data.payment_attempt.clone(); let mut revenue_recovery_metadata = payment_intent .feature_metadata .as_ref() .and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone()) .get_required_value("Payment Revenue Recovery Metadata")? .convert_back(); let pcr_status: types::RevenueRecoveryPaymentsAttemptStatus = payment_attempt.status.foreign_into(); let new_revenue_recovery_payment_data = &pcr::RevenueRecoveryPaymentData { psync_data: Some(psync_data), ..revenue_recovery_payment_data.clone() }; Box::pin( pcr_status.update_pt_status_based_on_attempt_status_for_payments_sync( state, payment_intent, process.clone(), profile, merchant_context, new_revenue_recovery_payment_data, payment_attempt, &mut revenue_recovery_metadata, ), ) .await?; Ok(()) } pub async fn perform_calculate_workflow( state: &SessionState, process: &storage::ProcessTracker, profile: &domain::Profile, merchant_context: domain::MerchantContext, tracking_data: &pcr::RevenueRecoveryWorkflowTrackingData, revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData, payment_intent: &PaymentIntent, ) -> Result<(), sch_errors::ProcessTrackerError> { let db = &*state.store; let merchant_id = revenue_recovery_payment_data.merchant_account.get_id(); let profile_id = revenue_recovery_payment_data.profile.get_id(); let billing_mca_id = revenue_recovery_payment_data.billing_mca.get_id(); let mut event_type: Option<common_enums::EventType> = None; logger::info!( process_id = %process.id, payment_id = %tracking_data.global_payment_id.get_string_repr(), "Starting CALCULATE_WORKFLOW..." ); // 1. Extract connector_customer_id and token_list from tracking_data let connector_customer_id = payment_intent .extract_connector_customer_id_from_payment_intent() .change_context(errors::RecoveryError::ValueNotFound) .attach_printable("Failed to extract customer ID from payment intent")?; let merchant_context_from_revenue_recovery_payment_data = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( revenue_recovery_payment_data.merchant_account.clone(), revenue_recovery_payment_data.key_store.clone(), ))); let retry_algorithm_type = match profile .revenue_recovery_retry_algorithm_type .filter(|retry_type| *retry_type != common_enums::RevenueRecoveryAlgorithmType::Monitoring) // ignore Monitoring in profile .unwrap_or(tracking_data.revenue_recovery_retry) // fallback to tracking_data { common_enums::RevenueRecoveryAlgorithmType::Smart => common_enums::RevenueRecoveryAlgorithmType::Smart, common_enums::RevenueRecoveryAlgorithmType::Cascading => common_enums::RevenueRecoveryAlgorithmType::Cascading, common_enums::RevenueRecoveryAlgorithmType::Monitoring => { return Err(sch_errors::ProcessTrackerError::ProcessUpdateFailed); } }; // External Payments which enter the calculate workflow for the first time will have active attempt id as None // Then we dont need to send an webhook to the merchant as its not a failure from our side. // Thus we dont need to a payment get call for such payments. let active_payment_attempt_id = payment_intent.active_attempt_id.as_ref(); let payments_response = get_payment_response_using_payment_get_operation( state, &tracking_data.global_payment_id, revenue_recovery_payment_data, &merchant_context_from_revenue_recovery_payment_data, active_payment_attempt_id, ) .await?; // 2. Get best available token let best_time_to_schedule = match revenue_recovery_workflow::get_token_with_schedule_time_based_on_retry_algorithm_type( state, &connector_customer_id, payment_intent, retry_algorithm_type, process.retry_count, ) .await { Ok(token_opt) => token_opt, Err(e) => { logger::error!( error = ?e, connector_customer_id = %connector_customer_id, "Failed to get best PSP token" ); None } }; match best_time_to_schedule { Some(scheduled_time) => { logger::info!( process_id = %process.id, connector_customer_id = %connector_customer_id, "Found best available token, creating EXECUTE_WORKFLOW task" ); // reset active attmept id and payment connector transmission before going to execute workflow let _ = Box::pin(reset_connector_transmission_and_active_attempt_id_before_pushing_to_execute_workflow( state, payment_intent, revenue_recovery_payment_data, active_payment_attempt_id )).await?; // 3. If token found: create EXECUTE_WORKFLOW task and finish CALCULATE_WORKFLOW insert_execute_pcr_task_to_pt( &tracking_data.billing_mca_id, state, &tracking_data.merchant_id, payment_intent, &tracking_data.profile_id, &tracking_data.payment_attempt_id, storage::ProcessTrackerRunner::PassiveRecoveryWorkflow, retry_algorithm_type, scheduled_time, ) .await?; db.as_scheduler() .finish_process_with_business_status( process.clone(), business_status::CALCULATE_WORKFLOW_SCHEDULED, ) .await .map_err(|e| { logger::error!( process_id = %process.id, error = ?e, "Failed to update CALCULATE_WORKFLOW status to complete" ); sch_errors::ProcessTrackerError::ProcessUpdateFailed })?; logger::info!( process_id = %process.id, connector_customer_id = %connector_customer_id, "CALCULATE_WORKFLOW completed successfully" ); } None => { let scheduled_token = match storage::revenue_recovery_redis_operation:: RedisTokenManager::get_payment_processor_token_with_schedule_time(state, &connector_customer_id) .await { Ok(scheduled_token_opt) => scheduled_token_opt, Err(e) => { logger::error!( error = ?e, connector_customer_id = %connector_customer_id, "Failed to get PSP token status" ); None } }; match scheduled_token { Some(scheduled_token) => { // Update scheduled time to scheduled time + 15 minutes // here scheduled_time is the wait time 15 minutes is a buffer time that we are adding logger::info!( process_id = %process.id, connector_customer_id = %connector_customer_id, "No token but time available, rescheduling for scheduled time + 15 mins" ); update_calculate_job_schedule_time( db, process, time::Duration::seconds( state .conf .revenue_recovery .recovery_timestamp .job_schedule_buffer_time_in_seconds, ), scheduled_token.scheduled_at, &connector_customer_id, ) .await?; } None => { let hard_decline_flag = storage::revenue_recovery_redis_operation:: RedisTokenManager::are_all_tokens_hard_declined( state, &connector_customer_id ) .await .ok() .unwrap_or(false); match hard_decline_flag { false => { logger::info!( process_id = %process.id, connector_customer_id = %connector_customer_id, "Hard decline flag is false, rescheduling for scheduled time + 15 mins" ); update_calculate_job_schedule_time( db, process, time::Duration::seconds( state .conf .revenue_recovery .recovery_timestamp .job_schedule_buffer_time_in_seconds, ), Some(common_utils::date_time::now()), &connector_customer_id, ) .await?; } true => { // Finish calculate workflow with CALCULATE_WORKFLOW_FINISH logger::info!( process_id = %process.id, connector_customer_id = %connector_customer_id, "No token available, finishing CALCULATE_WORKFLOW" ); db.as_scheduler() .finish_process_with_business_status( process.clone(), business_status::CALCULATE_WORKFLOW_FINISH, ) .await .map_err(|e| { logger::error!( process_id = %process.id, error = ?e, "Failed to finish CALCULATE_WORKFLOW" ); sch_errors::ProcessTrackerError::ProcessUpdateFailed })?; event_type = Some(common_enums::EventType::PaymentFailed); logger::info!( process_id = %process.id, connector_customer_id = %connector_customer_id, "CALCULATE_WORKFLOW finished successfully" ); } } } } } } let _outgoing_webhook = event_type.and_then(|event_kind| { payments_response.map(|resp| Some((event_kind, resp))) }) .flatten() .async_map(|(event_kind, response)| async move { let _ = RevenueRecoveryOutgoingWebhook::send_outgoing_webhook_based_on_revenue_recovery_status( state, common_enums::EventClass::Payments, event_kind, payment_intent, &merchant_context, profile, tracking_data.payment_attempt_id.get_string_repr().to_string(), response ) .await .map_err(|e| { logger::error!( error = ?e, "Failed to send outgoing webhook" ); e }) .ok(); } ).await; Ok(()) } /// Update the schedule time for a CALCULATE_WORKFLOW process tracker async fn update_calculate_job_schedule_time( db: &dyn StorageInterface, process: &storage::ProcessTracker, additional_time: time::Duration, base_time: Option<time::PrimitiveDateTime>, connector_customer_id: &str, ) -> Result<(), sch_errors::ProcessTrackerError> { let now = common_utils::date_time::now(); let new_schedule_time = base_time.filter(|&t| t > now).unwrap_or(now) + additional_time; logger::info!( new_schedule_time = %new_schedule_time, process_id = %process.id, connector_customer_id = %connector_customer_id, "Rescheduling Calculate Job at " ); let pt_update = storage::ProcessTrackerUpdate::Update { name: Some("CALCULATE_WORKFLOW".to_string()), retry_count: Some(process.clone().retry_count), schedule_time: Some(new_schedule_time), tracking_data: Some(process.clone().tracking_data), business_status: Some(String::from(business_status::PENDING)), status: Some(common_enums::ProcessTrackerStatus::Pending), updated_at: Some(common_utils::date_time::now()), }; db.as_scheduler() .update_process(process.clone(), pt_update) .await .map_err(|e| { logger::error!( process_id = %process.id, error = ?e, "Failed to reschedule CALCULATE_WORKFLOW" ); sch_errors::ProcessTrackerError::ProcessUpdateFailed })?; logger::info!( process_id = %process.id, connector_customer_id = %connector_customer_id, new_schedule_time = %new_schedule_time, additional_time = ?additional_time, "CALCULATE_WORKFLOW rescheduled successfully" ); Ok(()) } /// Insert Execute PCR Task to Process Tracker #[allow(clippy::too_many_arguments)] async fn insert_execute_pcr_task_to_pt( billing_mca_id: &id_type::MerchantConnectorAccountId, state: &SessionState, merchant_id: &id_type::MerchantId, payment_intent: &PaymentIntent, profile_id: &id_type::ProfileId, payment_attempt_id: &id_type::GlobalAttemptId, runner: storage::ProcessTrackerRunner, revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType, schedule_time: time::PrimitiveDateTime, ) -> Result<storage::ProcessTracker, sch_errors::ProcessTrackerError> { let task = "EXECUTE_WORKFLOW"; let payment_id = payment_intent.id.clone(); let process_tracker_id = format!("{runner}_{task}_{}", payment_id.get_string_repr()); // Check if a process tracker entry already exists for this payment intent let existing_entry = state .store .find_process_by_id(&process_tracker_id) .await .map_err(|e| { logger::error!( payment_id = %payment_id.get_string_repr(), process_tracker_id = %process_tracker_id, error = ?e, "Failed to check for existing execute workflow process tracker entry" ); sch_errors::ProcessTrackerError::ProcessUpdateFailed })?; match existing_entry { Some(existing_process) if existing_process.business_status == business_status::EXECUTE_WORKFLOW_FAILURE || existing_process.business_status == business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC => { // Entry exists with EXECUTE_WORKFLOW_COMPLETE status - update it logger::info!( payment_id = %payment_id.get_string_repr(), process_tracker_id = %process_tracker_id, current_retry_count = %existing_process.retry_count, "Found existing EXECUTE_WORKFLOW task with COMPLETE status, updating to PENDING with incremented retry count" ); let mut tracking_data: pcr::RevenueRecoveryWorkflowTrackingData = serde_json::from_value(existing_process.tracking_data.clone()) .change_context(errors::RecoveryError::ValueNotFound) .attach_printable( "Failed to deserialize the tracking data from process tracker", )?; tracking_data.revenue_recovery_retry = revenue_recovery_retry; let tracking_data_json = serde_json::to_value(&tracking_data) .change_context(errors::RecoveryError::ValueNotFound) .attach_printable("Failed to serialize the tracking data to json")?; let pt_update = storage::ProcessTrackerUpdate::Update { name: Some(task.to_string()), retry_count: Some(existing_process.clone().retry_count + 1), schedule_time: Some(schedule_time), tracking_data: Some(tracking_data_json), business_status: Some(String::from(business_status::PENDING)), status: Some(enums::ProcessTrackerStatus::Pending), updated_at: Some(common_utils::date_time::now()), }; let updated_process = state .store .update_process(existing_process, pt_update) .await .map_err(|e| { logger::error!( payment_id = %payment_id.get_string_repr(), process_tracker_id = %process_tracker_id, error = ?e, "Failed to update existing execute workflow process tracker entry" ); sch_errors::ProcessTrackerError::ProcessUpdateFailed })?; logger::info!( payment_id = %payment_id.get_string_repr(), process_tracker_id = %process_tracker_id, new_retry_count = %updated_process.retry_count, "Successfully updated existing EXECUTE_WORKFLOW task" ); Ok(updated_process) } Some(existing_process) => { // Entry exists but business status is not EXECUTE_WORKFLOW_COMPLETE logger::info!( payment_id = %payment_id.get_string_repr(), process_tracker_id = %process_tracker_id, current_business_status = %existing_process.business_status, ); Ok(existing_process) } None => { // No entry exists - create a new one logger::info!( payment_id = %payment_id.get_string_repr(), process_tracker_id = %process_tracker_id, "No existing EXECUTE_WORKFLOW task found, creating new entry" ); let execute_workflow_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData { billing_mca_id: billing_mca_id.clone(), global_payment_id: payment_id.clone(), merchant_id: merchant_id.clone(), profile_id: profile_id.clone(), payment_attempt_id: payment_attempt_id.clone(), revenue_recovery_retry, invoice_scheduled_time: Some(schedule_time), }; let tag = ["PCR"]; let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id.clone(), task, runner, tag, execute_workflow_tracking_data, Some(1), schedule_time, common_types::consts::API_VERSION, ) .map_err(|e| { logger::error!( payment_id = %payment_id.get_string_repr(), error = ?e, "Failed to construct execute workflow process tracker entry" ); sch_errors::ProcessTrackerError::ProcessUpdateFailed })?; let response = state .store .insert_process(process_tracker_entry) .await .map_err(|e| { logger::error!( payment_id = %payment_id.get_string_repr(), error = ?e, "Failed to insert execute workflow process tracker entry" ); sch_errors::ProcessTrackerError::ProcessUpdateFailed })?; metrics::TASKS_ADDED_COUNT.add( 1, router_env::metric_attributes!(("flow", "RevenueRecoveryExecute")), ); logger::info!( payment_id = %payment_id.get_string_repr(), process_tracker_id = %response.id, "Successfully created new EXECUTE_WORKFLOW task" ); Ok(response) } } } pub async fn retrieve_revenue_recovery_process_tracker( state: SessionState, id: id_type::GlobalPaymentId, ) -> RouterResponse<revenue_recovery::RevenueRecoveryResponse> { let db = &*state.store; let task = EXECUTE_WORKFLOW; let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; let process_tracker_id = id.get_execute_revenue_recovery_id(task, runner); let process_tracker = db .find_process_by_id(&process_tracker_id) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound) .attach_printable("error retrieving the process tracker id")? .get_required_value("Process Tracker") .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "Entry For the following id doesn't exists".to_owned(), })?; let tracking_data = process_tracker .tracking_data .clone() .parse_value::<pcr::RevenueRecoveryWorkflowTrackingData>("PCRWorkflowTrackingData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to deserialize Pcr Workflow Tracking Data")?; let psync_task = PSYNC_WORKFLOW; let process_tracker_id_for_psync = tracking_data .payment_attempt_id .get_psync_revenue_recovery_id(psync_task, runner); let process_tracker_for_psync = db .find_process_by_id(&process_tracker_id_for_psync) .await .map_err(|e| { logger::error!("Error while retrieving psync task : {:?}", e); }) .ok() .flatten(); let schedule_time_for_psync = process_tracker_for_psync.and_then(|pt| pt.schedule_time); let response = revenue_recovery::RevenueRecoveryResponse { id: process_tracker.id, name: process_tracker.name, schedule_time_for_payment: process_tracker.schedule_time, schedule_time_for_psync, status: process_tracker.status, business_status: process_tracker.business_status, }; Ok(ApplicationResponse::Json(response)) } pub async fn resume_revenue_recovery_process_tracker( state: SessionState, id: id_type::GlobalPaymentId, request_retrigger: revenue_recovery::RevenueRecoveryRetriggerRequest, ) -> RouterResponse<revenue_recovery::RevenueRecoveryResponse> { let db = &*state.store; let task = request_retrigger.revenue_recovery_task; let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; let process_tracker_id = id.get_execute_revenue_recovery_id(&task, runner); let process_tracker = db .find_process_by_id(&process_tracker_id) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound) .attach_printable("error retrieving the process tracker id")? .get_required_value("Process Tracker") .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "Entry For the following id doesn't exists".to_owned(), })?; let tracking_data = process_tracker .tracking_data .clone() .parse_value::<pcr::RevenueRecoveryWorkflowTrackingData>("PCRWorkflowTrackingData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to deserialize Pcr Workflow Tracking Data")?; //Call payment intent to check the status let request = PaymentsGetIntentRequest { id: id.clone() }; let revenue_recovery_payment_data = revenue_recovery_workflow::extract_data_and_perform_action(&state, &tracking_data) .await .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "Failed to extract the revenue recovery data".to_owned(), })?; let merchant_context_from_revenue_recovery_payment_data = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( revenue_recovery_payment_data.merchant_account.clone(), revenue_recovery_payment_data.key_store.clone(), ))); let create_intent_response = payments::payments_intent_core::< router_api_types::PaymentGetIntent, router_api_types::payments::PaymentsIntentResponse, _, _, PaymentIntentData<router_api_types::PaymentGetIntent>, >( state.clone(), state.get_req_state(), merchant_context_from_revenue_recovery_payment_data, revenue_recovery_payment_data.profile.clone(), payments::operations::PaymentGetIntent, request, tracking_data.global_payment_id.clone(), hyperswitch_domain_models::payments::HeaderPayload::default(), ) .await?; let response = create_intent_response .get_json_body() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unexpected response from payments core")?; match response.status { enums::IntentStatus::Failed => { let pt_update = storage::ProcessTrackerUpdate::Update { name: process_tracker.name.clone(), tracking_data: Some(process_tracker.tracking_data.clone()), business_status: Some(request_retrigger.business_status.clone()), status: Some(request_retrigger.status), updated_at: Some(common_utils::date_time::now()), retry_count: Some(process_tracker.retry_count + 1), schedule_time: Some(request_retrigger.schedule_time.unwrap_or( common_utils::date_time::now().saturating_add(time::Duration::seconds(600)), )), }; let updated_pt = db .update_process(process_tracker, pt_update) .await .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "Failed to update the process tracker".to_owned(), })?; let response = revenue_recovery::RevenueRecoveryResponse { id: updated_pt.id, name: updated_pt.name, schedule_time_for_payment: updated_pt.schedule_time, schedule_time_for_psync: None, status: updated_pt.status, business_status: updated_pt.business_status, }; Ok(ApplicationResponse::Json(response)) } enums::IntentStatus::Succeeded | enums::IntentStatus::Cancelled | enums::IntentStatus::CancelledPostCapture | enums::IntentStatus::Processing | enums::IntentStatus::RequiresCustomerAction | enums::IntentStatus::RequiresMerchantAction | enums::IntentStatus::RequiresPaymentMethod | enums::IntentStatus::RequiresConfirmation | enums::IntentStatus::RequiresCapture | enums::IntentStatus::PartiallyCaptured | enums::IntentStatus::PartiallyCapturedAndCapturable | enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | enums::IntentStatus::Conflicted | enums::IntentStatus::Expired => Err(report!(errors::ApiErrorResponse::NotSupported { message: "Invalid Payment Status ".to_owned(), })), } } pub async fn get_payment_response_using_payment_get_operation( state: &SessionState, payment_intent_id: &id_type::GlobalPaymentId, revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData, merchant_context: &domain::MerchantContext, active_payment_attempt_id: Option<&id_type::GlobalAttemptId>, ) -> Result<Option<ApplicationResponse<PaymentsResponse>>, sch_errors::ProcessTrackerError> { match active_payment_attempt_id { Some(_) => { let payment_response = api::call_psync_api( state, payment_intent_id, revenue_recovery_payment_data, false, false, ) .await?; let payments_response = payment_response.generate_response( state, None, None, None, merchant_context, &revenue_recovery_payment_data.profile, None, )?; Ok(Some(payments_response)) } None => Ok(None), } } // This function can be implemented to reset the connector transmission and active attempt ID // before pushing to the execute workflow. pub async fn reset_connector_transmission_and_active_attempt_id_before_pushing_to_execute_workflow( state: &SessionState, payment_intent: &PaymentIntent, revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData, active_payment_attempt_id: Option<&id_type::GlobalAttemptId>, ) -> Result<Option<()>, sch_errors::ProcessTrackerError> { let mut revenue_recovery_metadata = payment_intent .feature_metadata .as_ref() .and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone()) .get_required_value("Payment Revenue Recovery Metadata")? .convert_back(); match active_payment_attempt_id { Some(_) => { // update the connector payment transmission field to Unsuccessful and unset active attempt id revenue_recovery_metadata.set_payment_transmission_field_for_api_request( enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful, ); let payment_update_req = api_payments::PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api( payment_intent .feature_metadata .clone() .unwrap_or_default() .convert_back() .set_payment_revenue_recovery_metadata_using_api( revenue_recovery_metadata.clone(), ), enums::UpdateActiveAttempt::Unset, ); logger::info!( "Call made to payments update intent api , with the request body {:?}", payment_update_req ); api::update_payment_intent_api( state, payment_intent.id.clone(), revenue_recovery_payment_data, payment_update_req, ) .await .change_context(errors::RecoveryError::PaymentCallFailed)?; Ok(Some(())) } None => Ok(None), } } </file>
{ "crate": "router", "file": "crates/router/src/core/revenue_recovery.rs", "files": null, "module": null, "num_files": null, "token_count": 8950 }
large_file_1953649066690036573
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/debit_routing.rs </path> <file> 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) } </file>
{ "crate": "router", "file": "crates/router/src/core/debit_routing.rs", "files": null, "module": null, "num_files": null, "token_count": 5647 }
large_file_564289083561968559
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/relay.rs </path> <file> use std::marker::PhantomData; use api_models::relay as relay_api_models; use async_trait::async_trait; use common_enums::RelayStatus; use common_utils::{ self, fp_utils, id_type::{self, GenerateId}, }; use error_stack::ResultExt; use hyperswitch_domain_models::relay; use super::errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt}; use crate::{ core::payments, routes::SessionState, services, types::{ api::{self}, domain, }, utils::OptionExt, }; pub mod utils; pub trait Validate { type Error: error_stack::Context; fn validate(&self) -> Result<(), Self::Error>; } impl Validate for relay_api_models::RelayRefundRequestData { type Error = errors::ApiErrorResponse; fn validate(&self) -> Result<(), Self::Error> { fp_utils::when(self.amount.get_amount_as_i64() <= 0, || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Amount should be greater than 0".to_string(), }) })?; Ok(()) } } #[async_trait] pub trait RelayInterface { type Request: Validate; fn validate_relay_request(req: &Self::Request) -> RouterResult<()> { req.validate() .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "Invalid relay request".to_string(), }) } fn get_domain_models( relay_request: RelayRequestInner<Self>, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, ) -> relay::Relay; async fn process_relay( state: &SessionState, merchant_context: domain::MerchantContext, connector_account: domain::MerchantConnectorAccount, relay_record: &relay::Relay, ) -> RouterResult<relay::RelayUpdate>; fn generate_response(value: relay::Relay) -> RouterResult<api_models::relay::RelayResponse>; } pub struct RelayRequestInner<T: RelayInterface + ?Sized> { pub connector_resource_id: String, pub connector_id: id_type::MerchantConnectorAccountId, pub relay_type: PhantomData<T>, pub data: T::Request, } impl RelayRequestInner<RelayRefund> { pub fn from_relay_request(relay_request: relay_api_models::RelayRequest) -> RouterResult<Self> { match relay_request.data { Some(relay_api_models::RelayData::Refund(ref_data)) => Ok(Self { connector_resource_id: relay_request.connector_resource_id, connector_id: relay_request.connector_id, relay_type: PhantomData, data: ref_data, }), None => Err(errors::ApiErrorResponse::InvalidRequestData { message: "Relay data is required for relay type refund".to_string(), })?, } } } pub struct RelayRefund; #[async_trait] impl RelayInterface for RelayRefund { type Request = relay_api_models::RelayRefundRequestData; fn get_domain_models( relay_request: RelayRequestInner<Self>, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, ) -> relay::Relay { let relay_id = id_type::RelayId::generate(); let relay_refund: relay::RelayRefundData = relay_request.data.into(); relay::Relay { id: relay_id.clone(), connector_resource_id: relay_request.connector_resource_id.clone(), connector_id: relay_request.connector_id.clone(), profile_id: profile_id.clone(), merchant_id: merchant_id.clone(), relay_type: common_enums::RelayType::Refund, request_data: Some(relay::RelayData::Refund(relay_refund)), status: RelayStatus::Created, connector_reference_id: None, error_code: None, error_message: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), response_data: None, } } async fn process_relay( state: &SessionState, merchant_context: domain::MerchantContext, connector_account: domain::MerchantConnectorAccount, relay_record: &relay::Relay, ) -> RouterResult<relay::RelayUpdate> { let connector_id = &relay_record.connector_id; let merchant_id = merchant_context.get_merchant_account().get_id(); let connector_name = &connector_account.get_connector_name_as_string(); let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, Some(connector_id.clone()), )?; let connector_integration: services::BoxedRefundConnectorIntegrationInterface< api::Execute, hyperswitch_domain_models::router_request_types::RefundsData, hyperswitch_domain_models::router_response_types::RefundsResponseData, > = connector_data.connector.get_connector_integration(); let router_data = utils::construct_relay_refund_router_data( state, merchant_id, &connector_account, relay_record, ) .await?; let router_data_res = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_refund_failed_response()?; let relay_update = relay::RelayUpdate::from(router_data_res.response); Ok(relay_update) } fn generate_response(value: relay::Relay) -> RouterResult<api_models::relay::RelayResponse> { let error = value .error_code .zip(value.error_message) .map( |(error_code, error_message)| api_models::relay::RelayError { code: error_code, message: error_message, }, ); let data = api_models::relay::RelayData::from(value.request_data.get_required_value("RelayData")?); Ok(api_models::relay::RelayResponse { id: value.id, status: value.status, error, connector_resource_id: value.connector_resource_id, connector_id: value.connector_id, profile_id: value.profile_id, relay_type: value.relay_type, data: Some(data), connector_reference_id: value.connector_reference_id, }) } } pub async fn relay_flow_decider( state: SessionState, merchant_context: domain::MerchantContext, profile_id_optional: Option<id_type::ProfileId>, request: relay_api_models::RelayRequest, ) -> RouterResponse<relay_api_models::RelayResponse> { let relay_flow_request = match request.relay_type { common_enums::RelayType::Refund => { RelayRequestInner::<RelayRefund>::from_relay_request(request)? } }; relay( state, merchant_context, profile_id_optional, relay_flow_request, ) .await } pub async fn relay<T: RelayInterface>( state: SessionState, merchant_context: domain::MerchantContext, profile_id_optional: Option<id_type::ProfileId>, req: RelayRequestInner<T>, ) -> RouterResponse<relay_api_models::RelayResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let connector_id = &req.connector_id; let profile_id_from_auth_layer = profile_id_optional.get_required_value("ProfileId")?; let profile = db .find_business_profile_by_merchant_id_profile_id( key_manager_state, merchant_context.get_merchant_key_store(), merchant_id, &profile_id_from_auth_layer, ) .await .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id_from_auth_layer.get_string_repr().to_owned(), })?; #[cfg(feature = "v1")] let connector_account = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_id, connector_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: connector_id.get_string_repr().to_string(), })?; #[cfg(feature = "v2")] let connector_account = db .find_merchant_connector_account_by_id( key_manager_state, connector_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: connector_id.get_string_repr().to_string(), })?; T::validate_relay_request(&req.data)?; let relay_domain = T::get_domain_models(req, merchant_id, profile.get_id()); let relay_record = db .insert_relay( key_manager_state, merchant_context.get_merchant_key_store(), relay_domain, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to insert a relay record in db")?; let relay_response = T::process_relay( &state, merchant_context.clone(), connector_account, &relay_record, ) .await .attach_printable("Failed to process relay")?; let relay_update_record = db .update_relay( key_manager_state, merchant_context.get_merchant_key_store(), relay_record, relay_response, ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; let response = T::generate_response(relay_update_record) .attach_printable("Failed to generate relay response")?; Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) } pub async fn relay_retrieve( state: SessionState, merchant_context: domain::MerchantContext, profile_id_optional: Option<id_type::ProfileId>, req: relay_api_models::RelayRetrieveRequest, ) -> RouterResponse<relay_api_models::RelayResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let relay_id = &req.id; let profile_id_from_auth_layer = profile_id_optional.get_required_value("ProfileId")?; db.find_business_profile_by_merchant_id_profile_id( key_manager_state, merchant_context.get_merchant_key_store(), merchant_id, &profile_id_from_auth_layer, ) .await .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id_from_auth_layer.get_string_repr().to_owned(), })?; let relay_record_result = db .find_relay_by_id( key_manager_state, merchant_context.get_merchant_key_store(), relay_id, ) .await; let relay_record = match relay_record_result { Err(error) => { if error.current_context().is_db_not_found() { Err(error).change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "relay not found".to_string(), })? } else { Err(error) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while fetch relay record")? } } Ok(relay) => relay, }; #[cfg(feature = "v1")] let connector_account = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_id, &relay_record.connector_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: relay_record.connector_id.get_string_repr().to_string(), })?; #[cfg(feature = "v2")] let connector_account = db .find_merchant_connector_account_by_id( key_manager_state, &relay_record.connector_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: relay_record.connector_id.get_string_repr().to_string(), })?; let relay_response = match relay_record.relay_type { common_enums::RelayType::Refund => { if should_call_connector_for_relay_refund_status(&relay_record, req.force_sync) { let relay_response = sync_relay_refund_with_gateway( &state, &merchant_context, &relay_record, connector_account, ) .await?; db.update_relay( key_manager_state, merchant_context.get_merchant_key_store(), relay_record, relay_response, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update the relay record")? } else { relay_record } } }; let response = relay_api_models::RelayResponse::from(relay_response); Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) } fn should_call_connector_for_relay_refund_status(relay: &relay::Relay, force_sync: bool) -> bool { // This allows refund sync at connector level if force_sync is enabled, or // check if the refund is in terminal state !matches!(relay.status, RelayStatus::Failure | RelayStatus::Success) && force_sync } pub async fn sync_relay_refund_with_gateway( state: &SessionState, merchant_context: &domain::MerchantContext, relay_record: &relay::Relay, connector_account: domain::MerchantConnectorAccount, ) -> RouterResult<relay::RelayUpdate> { let connector_id = &relay_record.connector_id; let merchant_id = merchant_context.get_merchant_account().get_id(); #[cfg(feature = "v1")] let connector_name = &connector_account.connector_name; #[cfg(feature = "v2")] let connector_name = &connector_account.connector_name.to_string(); let connector_data: api::ConnectorData = api::ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, Some(connector_id.clone()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector")?; let router_data = utils::construct_relay_refund_router_data( state, merchant_id, &connector_account, relay_record, ) .await?; let connector_integration: services::BoxedRefundConnectorIntegrationInterface< api::RSync, hyperswitch_domain_models::router_request_types::RefundsData, hyperswitch_domain_models::router_response_types::RefundsResponseData, > = connector_data.connector.get_connector_integration(); let router_data_res = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_refund_failed_response()?; let relay_response = relay::RelayUpdate::from(router_data_res.response); Ok(relay_response) } </file>
{ "crate": "router", "file": "crates/router/src/core/relay.rs", "files": null, "module": null, "num_files": null, "token_count": 3316 }
large_file_7656719349271886461
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/mandate.rs </path> <file> pub mod helpers; pub mod utils; use api_models::payments; use common_types::payments as common_payments_types; use common_utils::{ext_traits::Encode, id_type}; use diesel_models::enums as storage_enums; use error_stack::{report, ResultExt}; use futures::future; use router_env::{instrument, logger, tracing}; use super::payments::helpers as payment_helper; use crate::{ core::{ errors::{self, RouterResponse, StorageErrorExt}, payments::CallConnectorAction, }, db::StorageInterface, routes::{metrics, SessionState}, services, types::{ self, api::{ mandates::{self, MandateResponseExt}, ConnectorData, GetToken, }, domain, storage::{self, enums::MerchantStorageScheme}, transformers::ForeignFrom, }, utils::OptionExt, }; #[instrument(skip(state))] pub async fn get_mandate( state: SessionState, merchant_context: domain::MerchantContext, req: mandates::MandateId, ) -> RouterResponse<mandates::MandateResponse> { let mandate = state .store .as_ref() .find_mandate_by_merchant_id_mandate_id( merchant_context.get_merchant_account().get_id(), &req.mandate_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; Ok(services::ApplicationResponse::Json( mandates::MandateResponse::from_db_mandate( &state, merchant_context.get_merchant_key_store().clone(), mandate, merchant_context.get_merchant_account(), ) .await?, )) } #[cfg(feature = "v1")] #[instrument(skip(state))] pub async fn revoke_mandate( state: SessionState, merchant_context: domain::MerchantContext, req: mandates::MandateId, ) -> RouterResponse<mandates::MandateRevokedResponse> { let db = state.store.as_ref(); let mandate = db .find_mandate_by_merchant_id_mandate_id( merchant_context.get_merchant_account().get_id(), &req.mandate_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; match mandate.mandate_status { common_enums::MandateStatus::Active | common_enums::MandateStatus::Inactive | common_enums::MandateStatus::Pending => { let profile_id = helpers::get_profile_id_for_mandate(&state, &merchant_context, mandate.clone()) .await?; let merchant_connector_account = payment_helper::get_merchant_connector_account( &state, merchant_context.get_merchant_account().get_id(), None, merchant_context.get_merchant_key_store(), &profile_id, &mandate.connector.clone(), mandate.merchant_connector_id.as_ref(), ) .await?; let connector_data = ConnectorData::get_connector_by_name( &state.conf.connectors, &mandate.connector, GetToken::Connector, mandate.merchant_connector_id.clone(), )?; let connector_integration: services::BoxedMandateRevokeConnectorIntegrationInterface< types::api::MandateRevoke, types::MandateRevokeRequestData, types::MandateRevokeResponseData, > = connector_data.connector.get_connector_integration(); let router_data = utils::construct_mandate_revoke_router_data( &state, merchant_connector_account, &merchant_context, mandate.clone(), ) .await?; let response = services::execute_connector_processing_step( &state, connector_integration, &router_data, CallConnectorAction::Trigger, None, None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; match response.response { Ok(_) => { let update_mandate = db .update_mandate_by_merchant_id_mandate_id( merchant_context.get_merchant_account().get_id(), &req.mandate_id, storage::MandateUpdate::StatusUpdate { mandate_status: storage::enums::MandateStatus::Revoked, }, mandate, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; Ok(services::ApplicationResponse::Json( mandates::MandateRevokedResponse { mandate_id: update_mandate.mandate_id, status: update_mandate.mandate_status, error_code: None, error_message: None, }, )) } Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: mandate.connector, status_code: err.status_code, reason: err.reason, } .into()), } } common_enums::MandateStatus::Revoked => { Err(errors::ApiErrorResponse::MandateValidationFailed { reason: "Mandate has already been revoked".to_string(), } .into()) } } } #[instrument(skip(db))] pub async fn update_connector_mandate_id( db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, mandate_ids_opt: Option<String>, payment_method_id: Option<String>, resp: Result<types::PaymentsResponseData, types::ErrorResponse>, storage_scheme: MerchantStorageScheme, ) -> RouterResponse<mandates::MandateResponse> { let mandate_details = Option::foreign_from(resp); let connector_mandate_id = mandate_details .clone() .map(|md| { md.encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .map(masking::Secret::new) }) .transpose()?; //Ignore updation if the payment_attempt mandate_id or connector_mandate_id is not present if let Some((mandate_id, connector_id)) = mandate_ids_opt.zip(connector_mandate_id) { let mandate = db .find_mandate_by_merchant_id_mandate_id(merchant_id, &mandate_id, storage_scheme) .await .change_context(errors::ApiErrorResponse::MandateNotFound)?; let update_mandate_details = match payment_method_id { Some(pmd_id) => storage::MandateUpdate::ConnectorMandateIdUpdate { connector_mandate_id: mandate_details .and_then(|mandate_reference| mandate_reference.connector_mandate_id), connector_mandate_ids: Some(connector_id), payment_method_id: pmd_id, original_payment_id: None, }, None => storage::MandateUpdate::ConnectorReferenceUpdate { connector_mandate_ids: Some(connector_id), }, }; // only update the connector_mandate_id if existing is none if mandate.connector_mandate_id.is_none() { db.update_mandate_by_merchant_id_mandate_id( merchant_id, &mandate_id, update_mandate_details, mandate, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::MandateUpdateFailed)?; } } Ok(services::ApplicationResponse::StatusOk) } #[cfg(feature = "v1")] #[instrument(skip(state))] pub async fn get_customer_mandates( state: SessionState, merchant_context: domain::MerchantContext, customer_id: id_type::CustomerId, ) -> RouterResponse<Vec<mandates::MandateResponse>> { let mandates = state .store .find_mandate_by_merchant_id_customer_id( merchant_context.get_merchant_account().get_id(), &customer_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while finding mandate: merchant_id: {:?}, customer_id: {:?}", merchant_context.get_merchant_account().get_id(), customer_id, ) })?; if mandates.is_empty() { Err(report!(errors::ApiErrorResponse::MandateNotFound).attach_printable("No Mandate found")) } else { let mut response_vec = Vec::with_capacity(mandates.len()); for mandate in mandates { response_vec.push( mandates::MandateResponse::from_db_mandate( &state, merchant_context.get_merchant_key_store().clone(), mandate, merchant_context.get_merchant_account(), ) .await?, ); } Ok(services::ApplicationResponse::Json(response_vec)) } } fn get_insensitive_payment_method_data_if_exists<F, FData>( router_data: &types::RouterData<F, FData, types::PaymentsResponseData>, ) -> Option<domain::PaymentMethodData> where FData: MandateBehaviour, { match &router_data.request.get_payment_method_data() { domain::PaymentMethodData::Card(_) => None, _ => Some(router_data.request.get_payment_method_data()), } } pub async fn mandate_procedure<F, FData>( state: &SessionState, resp: &types::RouterData<F, FData, types::PaymentsResponseData>, customer_id: &Option<id_type::CustomerId>, pm_id: Option<String>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, storage_scheme: MerchantStorageScheme, payment_id: &id_type::PaymentId, ) -> errors::RouterResult<Option<String>> where FData: MandateBehaviour, { let Ok(ref response) = resp.response else { return Ok(None); }; match resp.request.get_mandate_id() { Some(mandate_id) => { let Some(ref mandate_id) = mandate_id.mandate_id else { return Ok(None); }; let orig_mandate = state .store .find_mandate_by_merchant_id_mandate_id( &resp.merchant_id, mandate_id, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; let mandate = match orig_mandate.mandate_type { storage_enums::MandateType::SingleUse => state .store .update_mandate_by_merchant_id_mandate_id( &resp.merchant_id, mandate_id, storage::MandateUpdate::StatusUpdate { mandate_status: storage_enums::MandateStatus::Revoked, }, orig_mandate, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::MandateUpdateFailed), storage_enums::MandateType::MultiUse => state .store .update_mandate_by_merchant_id_mandate_id( &resp.merchant_id, mandate_id, storage::MandateUpdate::CaptureAmountUpdate { amount_captured: Some( orig_mandate.amount_captured.unwrap_or(0) + resp.request.get_amount(), ), }, orig_mandate, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::MandateUpdateFailed), }?; metrics::SUBSEQUENT_MANDATE_PAYMENT.add( 1, router_env::metric_attributes!(("connector", mandate.connector)), ); Ok(Some(mandate_id.clone())) } None => { let Some(_mandate_details) = resp.request.get_setup_mandate_details() else { return Ok(None); }; let (mandate_reference, network_txn_id) = match &response { types::PaymentsResponseData::TransactionResponse { mandate_reference, network_txn_id, .. } => (mandate_reference.clone(), network_txn_id.clone()), _ => (Box::new(None), None), }; let mandate_ids = (*mandate_reference) .as_ref() .map(|md| { md.encode_to_value() .change_context(errors::ApiErrorResponse::MandateSerializationFailed) .map(masking::Secret::new) }) .transpose()?; let Some(new_mandate_data) = payment_helper::generate_mandate( resp.merchant_id.clone(), payment_id.to_owned(), resp.connector.clone(), resp.request.get_setup_mandate_details().cloned(), customer_id, pm_id.get_required_value("payment_method_id")?, mandate_ids, network_txn_id, get_insensitive_payment_method_data_if_exists(resp), *mandate_reference, merchant_connector_id, )? else { return Ok(None); }; let connector = new_mandate_data.connector.clone(); logger::debug!("{:?}", new_mandate_data); let res_mandate_id = new_mandate_data.mandate_id.clone(); state .store .insert_mandate(new_mandate_data, storage_scheme) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateMandate)?; metrics::MANDATE_COUNT.add(1, router_env::metric_attributes!(("connector", connector))); Ok(Some(res_mandate_id)) } } } #[instrument(skip(state))] pub async fn retrieve_mandates_list( state: SessionState, merchant_context: domain::MerchantContext, constraints: api_models::mandates::MandateListConstraints, ) -> RouterResponse<Vec<api_models::mandates::MandateResponse>> { let mandates = state .store .as_ref() .find_mandates_by_merchant_id( merchant_context.get_merchant_account().get_id(), constraints, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to retrieve mandates")?; let mandates_list = future::try_join_all(mandates.into_iter().map(|mandate| { mandates::MandateResponse::from_db_mandate( &state, merchant_context.get_merchant_key_store().clone(), mandate, merchant_context.get_merchant_account(), ) })) .await?; Ok(services::ApplicationResponse::Json(mandates_list)) } impl ForeignFrom<Result<types::PaymentsResponseData, types::ErrorResponse>> for Option<types::MandateReference> { fn foreign_from(resp: Result<types::PaymentsResponseData, types::ErrorResponse>) -> Self { match resp { Ok(types::PaymentsResponseData::TransactionResponse { mandate_reference, .. }) => *mandate_reference, _ => None, } } } pub trait MandateBehaviour { fn get_amount(&self) -> i64; fn get_setup_future_usage(&self) -> Option<diesel_models::enums::FutureUsage>; fn get_mandate_id(&self) -> Option<&payments::MandateIds>; fn set_mandate_id(&mut self, new_mandate_id: Option<payments::MandateIds>); fn get_payment_method_data(&self) -> domain::payments::PaymentMethodData; fn get_setup_mandate_details( &self, ) -> Option<&hyperswitch_domain_models::mandates::MandateData>; fn get_customer_acceptance(&self) -> Option<common_payments_types::CustomerAcceptance>; } </file>
{ "crate": "router", "file": "crates/router/src/core/mandate.rs", "files": null, "module": null, "num_files": null, "token_count": 3372 }
large_file_-4760972344624492020
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/api_locking.rs </path> <file> 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>; } </file>
{ "crate": "router", "file": "crates/router/src/core/api_locking.rs", "files": null, "module": null, "num_files": null, "token_count": 2082 }
large_file_-5860647510392330823
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/pm_auth.rs </path> <file> use std::{collections::HashMap, str::FromStr}; use api_models::{ enums, payment_methods::{self, BankAccountAccessCreds}, }; use common_enums::{enums::MerchantStorageScheme, PaymentMethodType}; use hex; pub mod helpers; pub mod transformers; use common_utils::{ consts, crypto::{HmacSha256, SignMessage}, ext_traits::{AsyncExt, ValueExt}, generate_id, types::{self as util_types, AmountConvertor}, }; use error_stack::ResultExt; use helpers::PaymentAuthConnectorDataExt; use hyperswitch_domain_models::payments::PaymentIntent; use masking::{ExposeInterface, PeekInterface, Secret}; use pm_auth::{ connector::plaid::transformers::PlaidAuthType, types::{ self as pm_auth_types, api::{ auth_service::{BankAccountCredentials, ExchangeToken, LinkToken}, BoxedConnectorIntegration, PaymentAuthConnectorData, }, }, }; use crate::{ core::{ errors::{self, ApiErrorResponse, RouterResponse, RouterResult, StorageErrorExt}, payment_methods::cards, payments::helpers as oss_helpers, pm_auth::helpers as pm_auth_helpers, }, db::StorageInterface, logger, routes::SessionState, services::{pm_auth as pm_auth_services, ApplicationResponse}, types::{self, domain, storage, transformers::ForeignTryFrom}, }; #[cfg(feature = "v1")] pub async fn create_link_token( state: SessionState, merchant_context: domain::MerchantContext, payload: api_models::pm_auth::LinkTokenCreateRequest, headers: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResponse<api_models::pm_auth::LinkTokenCreateResponse> { let db = &*state.store; let redis_conn = db .get_redis_conn() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let pm_auth_key = payload.payment_id.get_pm_auth_key(); redis_conn .exists::<Vec<u8>>(&pm_auth_key.as_str().into()) .await .change_context(ApiErrorResponse::InvalidRequestData { message: "Incorrect payment_id provided in request".to_string(), }) .attach_printable("Corresponding pm_auth_key does not exist in redis")? .then_some(()) .ok_or(ApiErrorResponse::InvalidRequestData { message: "Incorrect payment_id provided in request".to_string(), }) .attach_printable("Corresponding pm_auth_key does not exist in redis")?; let pm_auth_configs = redis_conn .get_and_deserialize_key::<Vec<api_models::pm_auth::PaymentMethodAuthConnectorChoice>>( &pm_auth_key.as_str().into(), "Vec<PaymentMethodAuthConnectorChoice>", ) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get payment method auth choices from redis")?; let selected_config = pm_auth_configs .into_iter() .find(|config| { config.payment_method == payload.payment_method && config.payment_method_type == payload.payment_method_type }) .ok_or(ApiErrorResponse::GenericNotFoundError { message: "payment method auth connector name not found".to_string(), })?; let connector_name = selected_config.connector_name.as_str(); let connector = PaymentAuthConnectorData::get_connector_by_name(connector_name)?; let connector_integration: BoxedConnectorIntegration< '_, LinkToken, pm_auth_types::LinkTokenRequest, pm_auth_types::LinkTokenResponse, > = connector.connector.get_connector_integration(); let payment_intent = oss_helpers::verify_payment_intent_time_and_client_secret( &state, &merchant_context, payload.client_secret, ) .await?; let billing_country = payment_intent .as_ref() .async_map(|pi| async { oss_helpers::get_address_by_id( &state, pi.billing_address_id.clone(), merchant_context.get_merchant_key_store(), &pi.payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await }) .await .transpose()? .flatten() .and_then(|address| address.country) .map(|country| country.to_string()); #[cfg(feature = "v1")] let merchant_connector_account = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( &(&state).into(), merchant_context.get_merchant_account().get_id(), &selected_config.mca_id, merchant_context.get_merchant_key_store(), ) .await .change_context(ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_context .get_merchant_account() .get_id() .get_string_repr() .to_owned(), })?; #[cfg(feature = "v2")] let merchant_connector_account = { let _ = billing_country; todo!() }; let auth_type = helpers::get_connector_auth_type(merchant_connector_account)?; let router_data = pm_auth_types::LinkTokenRouterData { flow: std::marker::PhantomData, merchant_id: Some(merchant_context.get_merchant_account().get_id().clone()), connector: Some(connector_name.to_string()), request: pm_auth_types::LinkTokenRequest { client_name: "HyperSwitch".to_string(), country_codes: Some(vec![billing_country.ok_or( ApiErrorResponse::MissingRequiredField { field_name: "billing_country", }, )?]), language: payload.language, user_info: payment_intent.and_then(|pi| pi.customer_id), client_platform: headers .as_ref() .and_then(|header| header.x_client_platform.clone()), android_package_name: headers.as_ref().and_then(|header| header.x_app_id.clone()), redirect_uri: headers .as_ref() .and_then(|header| header.x_redirect_uri.clone()), }, response: Ok(pm_auth_types::LinkTokenResponse { link_token: "".to_string(), }), connector_http_status_code: None, connector_auth_type: auth_type, }; let connector_resp = pm_auth_services::execute_connector_processing_step( &state, connector_integration, &router_data, &connector.connector_name, ) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed while calling link token creation connector api")?; let link_token_resp = connector_resp .response .map_err(|err| ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: connector.connector_name.to_string(), status_code: err.status_code, reason: err.reason, })?; let response = api_models::pm_auth::LinkTokenCreateResponse { link_token: link_token_resp.link_token, connector: connector.connector_name.to_string(), }; Ok(ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] pub async fn create_link_token( _state: SessionState, _merchant_context: domain::MerchantContext, _payload: api_models::pm_auth::LinkTokenCreateRequest, _headers: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResponse<api_models::pm_auth::LinkTokenCreateResponse> { todo!() } impl ForeignTryFrom<&types::ConnectorAuthType> for PlaidAuthType { type Error = errors::ConnectorError; fn foreign_try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::BodyKey { api_key, key1 } => { Ok::<Self, errors::ConnectorError>(Self { client_id: api_key.to_owned(), secret: key1.to_owned(), }) } _ => Err(errors::ConnectorError::FailedToObtainAuthType), } } } pub async fn exchange_token_core( state: SessionState, merchant_context: domain::MerchantContext, payload: api_models::pm_auth::ExchangeTokenCreateRequest, ) -> RouterResponse<()> { let db = &*state.store; let config = get_selected_config_from_redis(db, &payload).await?; let connector_name = config.connector_name.as_str(); let connector = PaymentAuthConnectorData::get_connector_by_name(connector_name)?; #[cfg(feature = "v1")] let merchant_connector_account = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( &(&state).into(), merchant_context.get_merchant_account().get_id(), &config.mca_id, merchant_context.get_merchant_key_store(), ) .await .change_context(ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_context .get_merchant_account() .get_id() .get_string_repr() .to_owned(), })?; #[cfg(feature = "v2")] let merchant_connector_account: domain::MerchantConnectorAccount = { let _ = merchant_context.get_merchant_account(); let _ = connector; let _ = merchant_context.get_merchant_key_store(); todo!() }; let auth_type = helpers::get_connector_auth_type(merchant_connector_account.clone())?; let access_token = get_access_token_from_exchange_api( &connector, connector_name, &payload, &auth_type, &state, ) .await?; let bank_account_details_resp = get_bank_account_creds( connector, &merchant_context, connector_name, &access_token, auth_type, &state, None, ) .await?; Box::pin(store_bank_details_in_payment_methods( payload, merchant_context, state, bank_account_details_resp, (connector_name, access_token), merchant_connector_account.get_id(), )) .await?; Ok(ApplicationResponse::StatusOk) } #[cfg(feature = "v1")] async fn store_bank_details_in_payment_methods( payload: api_models::pm_auth::ExchangeTokenCreateRequest, merchant_context: domain::MerchantContext, state: SessionState, bank_account_details_resp: pm_auth_types::BankAccountCredentialsResponse, connector_details: (&str, Secret<String>), mca_id: common_utils::id_type::MerchantConnectorAccountId, ) -> RouterResult<()> { let db = &*state.clone().store; let (connector_name, access_token) = connector_details; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), &payload.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(ApiErrorResponse::PaymentNotFound)?; let customer_id = payment_intent .customer_id .ok_or(ApiErrorResponse::CustomerNotFound)?; let payment_methods = db .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 .change_context(ApiErrorResponse::InternalServerError)?; let mut hash_to_payment_method: HashMap< String, ( domain::PaymentMethod, payment_methods::PaymentMethodDataBankCreds, ), > = HashMap::new(); let key_manager_state = (&state).into(); for pm in payment_methods { if pm.get_payment_method_type() == Some(enums::PaymentMethod::BankDebit) && pm.payment_method_data.is_some() { let bank_details_pm_data = pm .payment_method_data .clone() .map(|x| x.into_inner().expose()) .map(|v| v.parse_value("PaymentMethodsData")) .transpose() .unwrap_or_else(|error| { logger::error!(?error); None }) .and_then(|pmd| match pmd { payment_methods::PaymentMethodsData::BankDetails(bank_creds) => { Some(bank_creds) } _ => None, }) .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse PaymentMethodsData")?; hash_to_payment_method.insert( bank_details_pm_data.hash.clone(), (pm, bank_details_pm_data), ); } } let pm_auth_key = state .conf .payment_method_auth .get_inner() .pm_auth_key .clone() .expose(); let mut update_entries: Vec<(domain::PaymentMethod, storage::PaymentMethodUpdate)> = Vec::new(); let mut new_entries: Vec<domain::PaymentMethod> = Vec::new(); for creds in bank_account_details_resp.credentials { let (account_number, hash_string) = match creds.account_details { pm_auth_types::PaymentMethodTypeDetails::Ach(ach) => ( ach.account_number.clone(), format!( "{}-{}-{}", ach.account_number.peek(), ach.routing_number.peek(), PaymentMethodType::Ach, ), ), pm_auth_types::PaymentMethodTypeDetails::Bacs(bacs) => ( bacs.account_number.clone(), format!( "{}-{}-{}", bacs.account_number.peek(), bacs.sort_code.peek(), PaymentMethodType::Bacs ), ), pm_auth_types::PaymentMethodTypeDetails::Sepa(sepa) => ( sepa.iban.clone(), format!("{}-{}", sepa.iban.expose(), PaymentMethodType::Sepa), ), }; let generated_hash = hex::encode( HmacSha256::sign_message(&HmacSha256, pm_auth_key.as_bytes(), hash_string.as_bytes()) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to sign the message")?, ); let contains_account = hash_to_payment_method.get(&generated_hash); let mut pmd = payment_methods::PaymentMethodDataBankCreds { mask: account_number .peek() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), hash: generated_hash, account_type: creds.account_type, account_name: creds.account_name, payment_method_type: creds.payment_method_type, connector_details: vec![payment_methods::BankAccountConnectorDetails { connector: connector_name.to_string(), mca_id: mca_id.clone(), access_token: BankAccountAccessCreds::AccessToken(access_token.clone()), account_id: creds.account_id, }], }; if let Some((pm, details)) = contains_account { pmd.connector_details.extend( details .connector_details .clone() .into_iter() .filter(|conn| conn.mca_id != mca_id), ); let payment_method_data = payment_methods::PaymentMethodsData::BankDetails(pmd); let encrypted_data = cards::create_encrypted_data( &key_manager_state, merchant_context.get_merchant_key_store(), payment_method_data, ) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt customer details")?; let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data: Some(encrypted_data.into()), }; update_entries.push((pm.clone(), pm_update)); } else { let payment_method_data = payment_methods::PaymentMethodsData::BankDetails(pmd); let encrypted_data = cards::create_encrypted_data( &key_manager_state, merchant_context.get_merchant_key_store(), Some(payment_method_data), ) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt customer details")?; let pm_id = generate_id(consts::ID_LENGTH, "pm"); let now = common_utils::date_time::now(); let pm_new = domain::PaymentMethod { customer_id: customer_id.clone(), merchant_id: merchant_context.get_merchant_account().get_id().clone(), payment_method_id: pm_id, payment_method: Some(enums::PaymentMethod::BankDebit), payment_method_type: Some(creds.payment_method_type), status: enums::PaymentMethodStatus::Active, payment_method_issuer: None, scheme: None, metadata: None, payment_method_data: Some(encrypted_data), payment_method_issuer_code: None, accepted_currency: None, token: None, cardholder_name: None, issuer_name: None, issuer_country: None, payer_country: None, is_stored: None, swift_code: None, direct_debit_token: None, created_at: now, last_modified: now, locker_id: None, last_used_at: now, connector_mandate_details: None, customer_acceptance: None, network_transaction_id: None, client_secret: None, payment_method_billing_address: None, updated_by: None, version: common_types::consts::API_VERSION, network_token_requestor_reference_id: None, network_token_locker_id: None, network_token_payment_method_data: None, vault_source_details: Default::default(), }; new_entries.push(pm_new); }; } store_in_db( &state, merchant_context.get_merchant_key_store(), update_entries, new_entries, db, merchant_context.get_merchant_account().storage_scheme, ) .await?; Ok(()) } #[cfg(feature = "v2")] async fn store_bank_details_in_payment_methods( _payload: api_models::pm_auth::ExchangeTokenCreateRequest, _merchant_context: domain::MerchantContext, _state: SessionState, _bank_account_details_resp: pm_auth_types::BankAccountCredentialsResponse, _connector_details: (&str, Secret<String>), _mca_id: common_utils::id_type::MerchantConnectorAccountId, ) -> RouterResult<()> { todo!() } async fn store_in_db( state: &SessionState, key_store: &domain::MerchantKeyStore, update_entries: Vec<(domain::PaymentMethod, storage::PaymentMethodUpdate)>, new_entries: Vec<domain::PaymentMethod>, db: &dyn StorageInterface, storage_scheme: MerchantStorageScheme, ) -> RouterResult<()> { let key_manager_state = &(state.into()); let update_entries_futures = update_entries .into_iter() .map(|(pm, pm_update)| { db.update_payment_method(key_manager_state, key_store, pm, pm_update, storage_scheme) }) .collect::<Vec<_>>(); let new_entries_futures = new_entries .into_iter() .map(|pm_new| { db.insert_payment_method(key_manager_state, key_store, pm_new, storage_scheme) }) .collect::<Vec<_>>(); let update_futures = futures::future::join_all(update_entries_futures); let new_futures = futures::future::join_all(new_entries_futures); let (update, new) = tokio::join!(update_futures, new_futures); let _ = update .into_iter() .map(|res| res.map_err(|err| logger::error!("Payment method storage failed {err:?}"))); let _ = new .into_iter() .map(|res| res.map_err(|err| logger::error!("Payment method storage failed {err:?}"))); Ok(()) } pub async fn get_bank_account_creds( connector: PaymentAuthConnectorData, merchant_context: &domain::MerchantContext, connector_name: &str, access_token: &Secret<String>, auth_type: pm_auth_types::ConnectorAuthType, state: &SessionState, bank_account_id: Option<Secret<String>>, ) -> RouterResult<pm_auth_types::BankAccountCredentialsResponse> { let connector_integration_bank_details: BoxedConnectorIntegration< '_, BankAccountCredentials, pm_auth_types::BankAccountCredentialsRequest, pm_auth_types::BankAccountCredentialsResponse, > = connector.connector.get_connector_integration(); let router_data_bank_details = pm_auth_types::BankDetailsRouterData { flow: std::marker::PhantomData, merchant_id: Some(merchant_context.get_merchant_account().get_id().clone()), connector: Some(connector_name.to_string()), request: pm_auth_types::BankAccountCredentialsRequest { access_token: access_token.clone(), optional_ids: bank_account_id .map(|id| pm_auth_types::BankAccountOptionalIDs { ids: vec![id] }), }, response: Ok(pm_auth_types::BankAccountCredentialsResponse { credentials: Vec::new(), }), connector_http_status_code: None, connector_auth_type: auth_type, }; let bank_details_resp = pm_auth_services::execute_connector_processing_step( state, connector_integration_bank_details, &router_data_bank_details, &connector.connector_name, ) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed while calling bank account details connector api")?; let bank_account_details_resp = bank_details_resp .response .map_err(|err| ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: connector.connector_name.to_string(), status_code: err.status_code, reason: err.reason, })?; Ok(bank_account_details_resp) } async fn get_access_token_from_exchange_api( connector: &PaymentAuthConnectorData, connector_name: &str, payload: &api_models::pm_auth::ExchangeTokenCreateRequest, auth_type: &pm_auth_types::ConnectorAuthType, state: &SessionState, ) -> RouterResult<Secret<String>> { let connector_integration: BoxedConnectorIntegration< '_, ExchangeToken, pm_auth_types::ExchangeTokenRequest, pm_auth_types::ExchangeTokenResponse, > = connector.connector.get_connector_integration(); let router_data = pm_auth_types::ExchangeTokenRouterData { flow: std::marker::PhantomData, merchant_id: None, connector: Some(connector_name.to_string()), request: pm_auth_types::ExchangeTokenRequest { public_token: payload.public_token.clone(), }, response: Ok(pm_auth_types::ExchangeTokenResponse { access_token: "".to_string(), }), connector_http_status_code: None, connector_auth_type: auth_type.clone(), }; let resp = pm_auth_services::execute_connector_processing_step( state, connector_integration, &router_data, &connector.connector_name, ) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed while calling exchange token connector api")?; let exchange_token_resp = resp.response .map_err(|err| ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: connector.connector_name.to_string(), status_code: err.status_code, reason: err.reason, })?; let access_token = exchange_token_resp.access_token; Ok(Secret::new(access_token)) } async fn get_selected_config_from_redis( db: &dyn StorageInterface, payload: &api_models::pm_auth::ExchangeTokenCreateRequest, ) -> RouterResult<api_models::pm_auth::PaymentMethodAuthConnectorChoice> { let redis_conn = db .get_redis_conn() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let pm_auth_key = payload.payment_id.get_pm_auth_key(); redis_conn .exists::<Vec<u8>>(&pm_auth_key.as_str().into()) .await .change_context(ApiErrorResponse::InvalidRequestData { message: "Incorrect payment_id provided in request".to_string(), }) .attach_printable("Corresponding pm_auth_key does not exist in redis")? .then_some(()) .ok_or(ApiErrorResponse::InvalidRequestData { message: "Incorrect payment_id provided in request".to_string(), }) .attach_printable("Corresponding pm_auth_key does not exist in redis")?; let pm_auth_configs = redis_conn .get_and_deserialize_key::<Vec<api_models::pm_auth::PaymentMethodAuthConnectorChoice>>( &pm_auth_key.as_str().into(), "Vec<PaymentMethodAuthConnectorChoice>", ) .await .change_context(ApiErrorResponse::GenericNotFoundError { message: "payment method auth connector name not found".to_string(), }) .attach_printable("Failed to get payment method auth choices from redis")?; let selected_config = pm_auth_configs .iter() .find(|conf| { conf.payment_method == payload.payment_method && conf.payment_method_type == payload.payment_method_type }) .ok_or(ApiErrorResponse::GenericNotFoundError { message: "payment method auth connector name not found".to_string(), })? .clone(); Ok(selected_config) } #[cfg(feature = "v2")] pub async fn retrieve_payment_method_from_auth_service( state: &SessionState, key_store: &domain::MerchantKeyStore, auth_token: &payment_methods::BankAccountTokenData, payment_intent: &PaymentIntent, _customer: &Option<domain::Customer>, ) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> { todo!() } #[cfg(feature = "v1")] pub async fn retrieve_payment_method_from_auth_service( state: &SessionState, key_store: &domain::MerchantKeyStore, auth_token: &payment_methods::BankAccountTokenData, payment_intent: &PaymentIntent, _customer: &Option<domain::Customer>, ) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> { let db = state.store.as_ref(); let connector = PaymentAuthConnectorData::get_connector_by_name( auth_token.connector_details.connector.as_str(), )?; let key_manager_state = &state.into(); let merchant_account = db .find_merchant_account_by_merchant_id( key_manager_state, &payment_intent.merchant_id, key_store, ) .await .to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?; #[cfg(feature = "v1")] let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, &payment_intent.merchant_id, &auth_token.connector_details.mca_id, key_store, ) .await .to_not_found_response(ApiErrorResponse::MerchantConnectorAccountNotFound { id: auth_token .connector_details .mca_id .get_string_repr() .to_string() .clone(), }) .attach_printable( "error while fetching merchant_connector_account from merchant_id and connector name", )?; let auth_type = pm_auth_helpers::get_connector_auth_type(mca)?; let BankAccountAccessCreds::AccessToken(access_token) = &auth_token.connector_details.access_token; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), key_store.clone(), ))); let bank_account_creds = get_bank_account_creds( connector, &merchant_context, &auth_token.connector_details.connector, access_token, auth_type, state, Some(auth_token.connector_details.account_id.clone()), ) .await?; let bank_account = bank_account_creds .credentials .iter() .find(|acc| { acc.payment_method_type == auth_token.payment_method_type && acc.payment_method == auth_token.payment_method }) .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Bank account details not found")?; if let (Some(balance), Some(currency)) = (bank_account.balance, payment_intent.currency) { let required_conversion = util_types::FloatMajorUnitForConnector; let converted_amount = required_conversion .convert_back(balance, currency) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Could not convert FloatMajorUnit to MinorUnit")?; if converted_amount < payment_intent.amount { return Err((ApiErrorResponse::PreconditionFailed { message: "selected bank account has insufficient balance".to_string(), }) .into()); } } let mut bank_type = None; if let Some(account_type) = bank_account.account_type.clone() { bank_type = common_enums::BankType::from_str(account_type.as_str()) .map_err(|error| logger::error!(%error,"unable to parse account_type {account_type:?}")) .ok(); } let payment_method_data = match &bank_account.account_details { pm_auth_types::PaymentMethodTypeDetails::Ach(ach) => { domain::PaymentMethodData::BankDebit(domain::BankDebitData::AchBankDebit { account_number: ach.account_number.clone(), routing_number: ach.routing_number.clone(), bank_name: None, bank_type, bank_holder_type: None, card_holder_name: None, bank_account_holder_name: None, }) } pm_auth_types::PaymentMethodTypeDetails::Bacs(bacs) => { domain::PaymentMethodData::BankDebit(domain::BankDebitData::BacsBankDebit { account_number: bacs.account_number.clone(), sort_code: bacs.sort_code.clone(), bank_account_holder_name: None, }) } pm_auth_types::PaymentMethodTypeDetails::Sepa(sepa) => { domain::PaymentMethodData::BankDebit(domain::BankDebitData::SepaBankDebit { iban: sepa.iban.clone(), bank_account_holder_name: None, }) } }; Ok(Some((payment_method_data, enums::PaymentMethod::BankDebit))) } </file>
{ "crate": "router", "file": "crates/router/src/core/pm_auth.rs", "files": null, "module": null, "num_files": null, "token_count": 6533 }
large_file_-1489855136402063340
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/payments/tokenization.rs </path> <file> use std::collections::HashMap; use ::payment_methods::controller::PaymentMethodsController; #[cfg(feature = "v1")] use api_models::payment_methods::PaymentMethodsData; use api_models::{ payment_methods::PaymentMethodDataWalletInfo, payments::ConnectorMandateReferenceId, }; use common_enums::{ConnectorMandateStatus, PaymentMethod}; use common_types::callback_mapper::CallbackMapperData; use common_utils::{ crypto::Encryptable, ext_traits::{AsyncExt, Encode, ValueExt}, id_type, metrics::utils::record_operation_time, pii, }; use diesel_models::business_profile::ExternalVaultConnectorDetails; use error_stack::{report, ResultExt}; #[cfg(feature = "v1")] use hyperswitch_domain_models::{ callback_mapper::CallbackMapper, mandates::{CommonMandateReference, PaymentsMandateReference, PaymentsMandateReferenceRecord}, payment_method_data, }; use masking::{ExposeInterface, Secret}; use router_env::{instrument, tracing}; use super::helpers; #[cfg(feature = "v1")] use crate::core::payment_methods::vault_payment_method_external_v1; use crate::{ consts, core::{ errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt}, mandate, payment_methods::{ self, cards::{create_encrypted_data, PmCards}, network_tokenization, }, payments, }, logger, routes::{metrics, SessionState}, services, types::{ self, api::{self, CardDetailFromLocker, CardDetailsPaymentMethod, PaymentMethodCreateExt}, domain, payment_methods as pm_types, storage::enums as storage_enums, }, utils::{generate_id, OptionExt}, }; #[cfg(feature = "v1")] async fn save_in_locker( state: &SessionState, merchant_context: &domain::MerchantContext, payment_method_request: api::PaymentMethodCreate, card_detail: Option<api::CardDetail>, business_profile: &domain::Profile, ) -> RouterResult<( api_models::payment_methods::PaymentMethodResponse, Option<payment_methods::transformers::DataDuplicationCheck>, )> { match &business_profile.external_vault_details { domain::ExternalVaultDetails::ExternalVaultEnabled(external_vault_details) => { logger::info!("External vault is enabled, using vault_payment_method_external_v1"); Box::pin(save_in_locker_external( state, merchant_context, payment_method_request, card_detail, external_vault_details, )) .await } domain::ExternalVaultDetails::Skip => { // Use internal vault (locker) save_in_locker_internal(state, merchant_context, payment_method_request, card_detail) .await } } } pub struct SavePaymentMethodData<Req> { request: Req, response: Result<types::PaymentsResponseData, types::ErrorResponse>, payment_method_token: Option<types::PaymentMethodToken>, payment_method: PaymentMethod, attempt_status: common_enums::AttemptStatus, } impl<F, Req: Clone> From<&types::RouterData<F, Req, types::PaymentsResponseData>> for SavePaymentMethodData<Req> { fn from(router_data: &types::RouterData<F, Req, types::PaymentsResponseData>) -> Self { Self { request: router_data.request.clone(), response: router_data.response.clone(), payment_method_token: router_data.payment_method_token.clone(), payment_method: router_data.payment_method, attempt_status: router_data.status, } } } pub struct SavePaymentMethodDataResponse { pub payment_method_id: Option<String>, pub payment_method_status: Option<common_enums::PaymentMethodStatus>, pub connector_mandate_reference_id: Option<ConnectorMandateReferenceId>, } #[cfg(feature = "v1")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn save_payment_method<FData>( state: &SessionState, connector_name: String, save_payment_method_data: SavePaymentMethodData<FData>, customer_id: Option<id_type::CustomerId>, merchant_context: &domain::MerchantContext, payment_method_type: Option<storage_enums::PaymentMethodType>, billing_name: Option<Secret<String>>, payment_method_billing_address: Option<&hyperswitch_domain_models::address::Address>, business_profile: &domain::Profile, mut original_connector_mandate_reference_id: Option<ConnectorMandateReferenceId>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, vault_operation: Option<hyperswitch_domain_models::payments::VaultOperation>, payment_method_info: Option<domain::PaymentMethod>, ) -> RouterResult<SavePaymentMethodDataResponse> where FData: mandate::MandateBehaviour + Clone, { let mut pm_status = None; let cards = PmCards { state, merchant_context, }; match save_payment_method_data.response { Ok(responses) => { let db = &*state.store; let token_store = state .conf .tokenization .0 .get(&connector_name.to_string()) .map(|token_filter| token_filter.long_lived_token) .unwrap_or(false); let network_transaction_id = match &responses { types::PaymentsResponseData::TransactionResponse { network_txn_id, .. } => { network_txn_id.clone() } _ => None, }; let network_transaction_id = if save_payment_method_data.request.get_setup_future_usage() == Some(storage_enums::FutureUsage::OffSession) { if network_transaction_id.is_some() { network_transaction_id } else { logger::info!("Skip storing network transaction id"); None } } else { None }; let connector_token = if token_store { let tokens = save_payment_method_data .payment_method_token .to_owned() .get_required_value("payment_token")?; let token = match tokens { types::PaymentMethodToken::Token(connector_token) => connector_token.expose(), types::PaymentMethodToken::ApplePayDecrypt(_) => { Err(errors::ApiErrorResponse::NotSupported { message: "Apple Pay Decrypt token is not supported".to_string(), })? } types::PaymentMethodToken::PazeDecrypt(_) => { Err(errors::ApiErrorResponse::NotSupported { message: "Paze Decrypt token is not supported".to_string(), })? } types::PaymentMethodToken::GooglePayDecrypt(_) => { Err(errors::ApiErrorResponse::NotSupported { message: "Google Pay Decrypt token is not supported".to_string(), })? } }; Some((connector_name, token)) } else { None }; let mandate_data_customer_acceptance = save_payment_method_data .request .get_setup_mandate_details() .and_then(|mandate_data| mandate_data.customer_acceptance.clone()); let customer_acceptance = save_payment_method_data .request .get_customer_acceptance() .or(mandate_data_customer_acceptance.clone()) .map(|ca| ca.encode_to_value()) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to serialize customer acceptance to value")?; let (connector_mandate_id, mandate_metadata, connector_mandate_request_reference_id) = match responses { types::PaymentsResponseData::TransactionResponse { mandate_reference, .. } => { if let Some(ref mandate_ref) = *mandate_reference { ( mandate_ref.connector_mandate_id.clone(), mandate_ref.mandate_metadata.clone(), mandate_ref.connector_mandate_request_reference_id.clone(), ) } else { (None, None, None) } } _ => (None, None, None), }; let pm_id = if customer_acceptance.is_some() { let payment_method_data = save_payment_method_data.request.get_payment_method_data(); let payment_method_create_request = payment_methods::get_payment_method_create_request( Some(&payment_method_data), Some(save_payment_method_data.payment_method), payment_method_type, &customer_id.clone(), billing_name, payment_method_billing_address, ) .await?; let payment_methods_data = &save_payment_method_data.request.get_payment_method_data(); let co_badged_card_data = payment_methods_data.get_co_badged_card_data(); let customer_id = customer_id.to_owned().get_required_value("customer_id")?; let merchant_id = merchant_context.get_merchant_account().get_id(); let is_network_tokenization_enabled = business_profile.is_network_tokenization_enabled; let ( (mut resp, duplication_check, network_token_requestor_ref_id), network_token_resp, ) = if !state.conf.locker.locker_enabled { let (res, dc) = skip_saving_card_in_locker( merchant_context, payment_method_create_request.to_owned(), ) .await?; ((res, dc, None), None) } else { let payment_method_status = common_enums::PaymentMethodStatus::from( save_payment_method_data.attempt_status, ); pm_status = Some(payment_method_status); save_card_and_network_token_in_locker( state, customer_id.clone(), payment_method_status, payment_method_data.clone(), vault_operation, payment_method_info, merchant_context, payment_method_create_request.clone(), is_network_tokenization_enabled, business_profile, ) .await? }; let network_token_locker_id = match network_token_resp { Some(ref token_resp) => { if network_token_requestor_ref_id.is_some() { Some(token_resp.payment_method_id.clone()) } else { None } } None => None, }; let optional_pm_details = match (resp.card.as_ref(), payment_method_data) { (Some(card), _) => Some(PaymentMethodsData::Card( CardDetailsPaymentMethod::from((card.clone(), co_badged_card_data)), )), ( _, domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(applepay)), ) => Some(PaymentMethodsData::WalletDetails( PaymentMethodDataWalletInfo::from(applepay), )), ( _, domain::PaymentMethodData::Wallet(domain::WalletData::GooglePay(googlepay)), ) => Some(PaymentMethodsData::WalletDetails( PaymentMethodDataWalletInfo::from(googlepay), )), _ => None, }; let key_manager_state = state.into(); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = optional_pm_details .async_map(|pm| { create_encrypted_data( &key_manager_state, merchant_context.get_merchant_key_store(), pm, ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method data")?; let pm_network_token_data_encrypted: Option< Encryptable<Secret<serde_json::Value>>, > = match network_token_resp { Some(token_resp) => { let pm_token_details = token_resp.card.as_ref().map(|card| { PaymentMethodsData::Card(CardDetailsPaymentMethod::from(( card.clone(), None, ))) }); pm_token_details .async_map(|pm_card| { create_encrypted_data( &key_manager_state, merchant_context.get_merchant_key_store(), pm_card, ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method data")? } None => None, }; let encrypted_payment_method_billing_address: Option< Encryptable<Secret<serde_json::Value>>, > = payment_method_billing_address .async_map(|address| { create_encrypted_data( &key_manager_state, merchant_context.get_merchant_key_store(), address.clone(), ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method billing address")?; let mut payment_method_id = resp.payment_method_id.clone(); let mut locker_id = None; let (external_vault_details, vault_type) = match &business_profile.external_vault_details{ hyperswitch_domain_models::business_profile::ExternalVaultDetails::ExternalVaultEnabled(external_vault_connector_details) => { (Some(external_vault_connector_details), Some(common_enums::VaultType::External)) }, hyperswitch_domain_models::business_profile::ExternalVaultDetails::Skip => (None, Some(common_enums::VaultType::Internal)), }; let external_vault_mca_id = external_vault_details .map(|connector_details| connector_details.vault_connector_id.clone()); let vault_source_details = domain::PaymentMethodVaultSourceDetails::try_from(( vault_type, external_vault_mca_id, )) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to create vault source details")?; match duplication_check { Some(duplication_check) => match duplication_check { payment_methods::transformers::DataDuplicationCheck::Duplicated => { let payment_method = { let existing_pm_by_pmid = db .find_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), &payment_method_id, merchant_context.get_merchant_account().storage_scheme, ) .await; if let Err(err) = existing_pm_by_pmid { if err.current_context().is_db_not_found() { locker_id = Some(payment_method_id.clone()); let existing_pm_by_locker_id = db .find_payment_method_by_locker_id( &(state.into()), merchant_context.get_merchant_key_store(), &payment_method_id, merchant_context .get_merchant_account() .storage_scheme, ) .await; match &existing_pm_by_locker_id { Ok(pm) => { payment_method_id.clone_from(&pm.payment_method_id); } Err(_) => { payment_method_id = generate_id(consts::ID_LENGTH, "pm") } }; existing_pm_by_locker_id } else { Err(err) } } else { existing_pm_by_pmid } }; resp.payment_method_id = payment_method_id; match payment_method { Ok(pm) => { let pm_metadata = create_payment_method_metadata( pm.metadata.as_ref(), connector_token, )?; payment_methods::cards::update_payment_method_metadata_and_last_used( state, merchant_context.get_merchant_key_store(), db, pm.clone(), pm_metadata, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; } Err(err) => { if err.current_context().is_db_not_found() { let pm_metadata = create_payment_method_metadata(None, connector_token)?; cards .create_payment_method( &payment_method_create_request, &customer_id, &resp.payment_method_id, locker_id, merchant_id, pm_metadata, customer_acceptance, pm_data_encrypted, None, pm_status, network_transaction_id, encrypted_payment_method_billing_address, resp.card.and_then(|card| { card.card_network.map(|card_network| { card_network.to_string() }) }), network_token_requestor_ref_id, network_token_locker_id, pm_network_token_data_encrypted, Some(vault_source_details), ) .await } else { Err(err) .change_context( errors::ApiErrorResponse::InternalServerError, ) .attach_printable("Error while finding payment method") }?; } }; } payment_methods::transformers::DataDuplicationCheck::MetaDataChanged => { if let Some(card) = payment_method_create_request.card.clone() { let payment_method = { let existing_pm_by_pmid = db .find_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), &payment_method_id, merchant_context.get_merchant_account().storage_scheme, ) .await; if let Err(err) = existing_pm_by_pmid { if err.current_context().is_db_not_found() { locker_id = Some(payment_method_id.clone()); let existing_pm_by_locker_id = db .find_payment_method_by_locker_id( &(state.into()), merchant_context.get_merchant_key_store(), &payment_method_id, merchant_context .get_merchant_account() .storage_scheme, ) .await; match &existing_pm_by_locker_id { Ok(pm) => { payment_method_id .clone_from(&pm.payment_method_id); } Err(_) => { payment_method_id = generate_id(consts::ID_LENGTH, "pm") } }; existing_pm_by_locker_id } else { Err(err) } } else { existing_pm_by_pmid } }; resp.payment_method_id = payment_method_id; let existing_pm = match payment_method { Ok(pm) => { let mandate_details = pm .connector_mandate_details .clone() .map(|val| { val.parse_value::<PaymentsMandateReference>( "PaymentsMandateReference", ) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize to Payment Mandate Reference ")?; if let Some((mandate_details, merchant_connector_id)) = mandate_details.zip(merchant_connector_id) { let connector_mandate_details = update_connector_mandate_details_status( merchant_connector_id, mandate_details, ConnectorMandateStatus::Inactive, )?; payment_methods::cards::update_payment_method_connector_mandate_details( state, merchant_context.get_merchant_key_store(), db, pm.clone(), connector_mandate_details, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; } Ok(pm) } Err(err) => { if err.current_context().is_db_not_found() { cards .create_payment_method( &payment_method_create_request, &customer_id, &resp.payment_method_id, locker_id, merchant_id, resp.metadata.clone().map(|val| val.expose()), customer_acceptance, pm_data_encrypted, None, pm_status, network_transaction_id, encrypted_payment_method_billing_address, resp.card.and_then(|card| { card.card_network.map(|card_network| { card_network.to_string() }) }), network_token_requestor_ref_id, network_token_locker_id, pm_network_token_data_encrypted, Some(vault_source_details), ) .await } else { Err(err) .change_context( errors::ApiErrorResponse::InternalServerError, ) .attach_printable( "Error while finding payment method", ) } } }?; cards .delete_card_from_locker( &customer_id, merchant_id, existing_pm .locker_id .as_ref() .unwrap_or(&existing_pm.payment_method_id), ) .await?; let add_card_resp = cards .add_card_hs( payment_method_create_request, &card, &customer_id, api::enums::LockerChoice::HyperswitchCardVault, Some( existing_pm .locker_id .as_ref() .unwrap_or(&existing_pm.payment_method_id), ), ) .await; if let Err(err) = add_card_resp { logger::error!(vault_err=?err); db.delete_payment_method_by_merchant_id_payment_method_id( &(state.into()), merchant_context.get_merchant_key_store(), merchant_id, &resp.payment_method_id, ) .await .to_not_found_response( errors::ApiErrorResponse::PaymentMethodNotFound, )?; Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed while updating card metadata changes", ))? }; let existing_pm_data = cards .get_card_details_without_locker_fallback(&existing_pm) .await?; // scheme should be updated in case of co-badged cards let card_scheme = card .card_network .clone() .map(|card_network| card_network.to_string()) .or(existing_pm_data.scheme.clone()); let updated_card = Some(CardDetailFromLocker { scheme: card_scheme.clone(), last4_digits: Some(card.card_number.get_last4()), issuer_country: card .card_issuing_country .or(existing_pm_data.issuer_country), card_isin: Some(card.card_number.get_card_isin()), card_number: Some(card.card_number), expiry_month: Some(card.card_exp_month), expiry_year: Some(card.card_exp_year), card_token: None, card_fingerprint: None, card_holder_name: card .card_holder_name .or(existing_pm_data.card_holder_name), nick_name: card.nick_name.or(existing_pm_data.nick_name), card_network: card .card_network .or(existing_pm_data.card_network), card_issuer: card.card_issuer.or(existing_pm_data.card_issuer), card_type: card.card_type.or(existing_pm_data.card_type), saved_to_locker: true, }); let updated_pmd = updated_card.as_ref().map(|card| { PaymentMethodsData::Card(CardDetailsPaymentMethod::from(( card.clone(), co_badged_card_data, ))) }); let pm_data_encrypted: Option< Encryptable<Secret<serde_json::Value>>, > = updated_pmd .async_map(|pmd| { create_encrypted_data( &key_manager_state, merchant_context.get_merchant_key_store(), pmd, ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method data")?; payment_methods::cards::update_payment_method_and_last_used( state, merchant_context.get_merchant_key_store(), db, existing_pm, pm_data_encrypted.map(Into::into), merchant_context.get_merchant_account().storage_scheme, card_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; } } }, None => { let customer_saved_pm_option = if payment_method_type .map(|payment_method_type_value| { payment_method_type_value .should_check_for_customer_saved_payment_method_type() }) .unwrap_or(false) { match state .store .find_payment_method_by_customer_id_merchant_id_list( &(state.into()), merchant_context.get_merchant_key_store(), &customer_id, merchant_id, None, ) .await { Ok(customer_payment_methods) => Ok(customer_payment_methods .iter() .find(|payment_method| { payment_method.get_payment_method_subtype() == 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", ) } } } } else { Ok(None) }?; if let Some(customer_saved_pm) = customer_saved_pm_option { payment_methods::cards::update_last_used_at( &customer_saved_pm, 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(); resp.payment_method_id = customer_saved_pm.payment_method_id; } else { let pm_metadata = create_payment_method_metadata(None, connector_token)?; locker_id = resp.payment_method.and_then(|pm| { if pm == PaymentMethod::Card { Some(resp.payment_method_id) } else { None } }); resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); cards .create_payment_method( &payment_method_create_request, &customer_id, &resp.payment_method_id, locker_id, merchant_id, pm_metadata, customer_acceptance, pm_data_encrypted, None, pm_status, network_transaction_id, encrypted_payment_method_billing_address, resp.card.and_then(|card| { card.card_network .map(|card_network| card_network.to_string()) }), network_token_requestor_ref_id.clone(), network_token_locker_id, pm_network_token_data_encrypted, Some(vault_source_details), ) .await?; match network_token_requestor_ref_id { Some(network_token_requestor_ref_id) => { //Insert the network token reference ID along with merchant id, customer id in CallbackMapper table for its respective webooks let callback_mapper_data = CallbackMapperData::NetworkTokenWebhook { merchant_id: merchant_context .get_merchant_account() .get_id() .clone(), customer_id, payment_method_id: resp.payment_method_id.clone(), }; let callback_mapper = CallbackMapper::new( network_token_requestor_ref_id, common_enums::CallbackMapperIdType::NetworkTokenRequestorReferenceID, callback_mapper_data, common_utils::date_time::now(), common_utils::date_time::now(), ); db.insert_call_back_mapper(callback_mapper) .await .change_context( errors::ApiErrorResponse::InternalServerError, ) .attach_printable( "Failed to insert in Callback Mapper table", )?; } None => { logger::info!("Network token requestor reference ID is not available, skipping callback mapper insertion"); } }; }; } } Some(resp.payment_method_id) } else { None }; // check if there needs to be a config if yes then remove it to a different place 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 { None }; Ok(SavePaymentMethodDataResponse { payment_method_id: pm_id, payment_method_status: pm_status, connector_mandate_reference_id, }) } Err(_) => Ok(SavePaymentMethodDataResponse { payment_method_id: None, payment_method_status: None, connector_mandate_reference_id: None, }), } } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn save_payment_method<FData>( _state: &SessionState, _connector_name: String, _save_payment_method_data: SavePaymentMethodData<FData>, _customer_id: Option<id_type::CustomerId>, _merchant_context: &domain::MerchantContext, _payment_method_type: Option<storage_enums::PaymentMethodType>, _billing_name: Option<Secret<String>>, _payment_method_billing_address: Option<&api::Address>, _business_profile: &domain::Profile, _connector_mandate_request_reference_id: Option<String>, ) -> RouterResult<SavePaymentMethodDataResponse> where FData: mandate::MandateBehaviour + Clone, { todo!() } #[cfg(feature = "v1")] pub async fn pre_payment_tokenization( state: &SessionState, customer_id: id_type::CustomerId, card: &payment_method_data::Card, ) -> RouterResult<(Option<pm_types::TokenResponse>, Option<String>)> { let network_tokenization_supported_card_networks = &state .conf .network_tokenization_supported_card_networks .card_networks; if card .card_network .as_ref() .filter(|cn| network_tokenization_supported_card_networks.contains(cn)) .is_some() { let optional_card_cvc = Some(card.card_cvc.clone()); let card_detail = payment_method_data::CardDetail::from(card); match network_tokenization::make_card_network_tokenization_request( state, &card_detail, optional_card_cvc, &customer_id, ) .await { Ok((_token_response, network_token_requestor_ref_id)) => { let network_tokenization_service = &state.conf.network_tokenization_service; match ( network_token_requestor_ref_id.clone(), network_tokenization_service, ) { (Some(token_ref), Some(network_tokenization_service)) => { let network_token = record_operation_time( async { network_tokenization::get_network_token( state, customer_id, token_ref, network_tokenization_service.get_inner(), ) .await }, &metrics::FETCH_NETWORK_TOKEN_TIME, &[], ) .await; match network_token { Ok(token_response) => { Ok((Some(token_response), network_token_requestor_ref_id.clone())) } _ => { logger::error!( "Error while fetching token from tokenization service" ); Ok((None, network_token_requestor_ref_id.clone())) } } } (Some(token_ref), _) => Ok((None, Some(token_ref))), _ => Ok((None, None)), } } Err(err) => { logger::error!("Failed to tokenize card: {:?}", err); Ok((None, None)) //None will be returned in case of error when calling network tokenization service } } } else { Ok((None, None)) //None will be returned in case of unsupported card network. } } #[cfg(feature = "v1")] async fn skip_saving_card_in_locker( merchant_context: &domain::MerchantContext, payment_method_request: api::PaymentMethodCreate, ) -> RouterResult<( api_models::payment_methods::PaymentMethodResponse, Option<payment_methods::transformers::DataDuplicationCheck>, )> { let merchant_id = merchant_context.get_merchant_account().get_id(); let customer_id = payment_method_request .clone() .customer_id .clone() .get_required_value("customer_id")?; let payment_method_id = common_utils::generate_id(consts::ID_LENGTH, "pm"); let last4_digits = payment_method_request .card .clone() .map(|c| c.card_number.get_last4()); let card_isin = payment_method_request .card .clone() .map(|c| c.card_number.get_card_isin()); match payment_method_request.card.clone() { Some(card) => { let card_detail = CardDetailFromLocker { scheme: None, issuer_country: card.card_issuing_country.clone(), last4_digits: last4_digits.clone(), card_number: None, expiry_month: Some(card.card_exp_month.clone()), expiry_year: Some(card.card_exp_year), card_token: None, card_holder_name: card.card_holder_name.clone(), card_fingerprint: None, nick_name: None, card_isin: card_isin.clone(), card_issuer: card.card_issuer.clone(), card_network: card.card_network.clone(), card_type: card.card_type.clone(), saved_to_locker: false, }; let pm_resp = api::PaymentMethodResponse { merchant_id: merchant_id.to_owned(), customer_id: Some(customer_id), payment_method_id, payment_method: payment_method_request.payment_method, payment_method_type: payment_method_request.payment_method_type, card: Some(card_detail), recurring_enabled: Some(false), installment_payment_enabled: Some(false), payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), metadata: None, created: Some(common_utils::date_time::now()), #[cfg(feature = "payouts")] bank_transfer: None, last_used_at: Some(common_utils::date_time::now()), client_secret: None, }; Ok((pm_resp, None)) } None => { let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm"); let payment_method_response = api::PaymentMethodResponse { merchant_id: merchant_id.to_owned(), customer_id: Some(customer_id), payment_method_id: pm_id, payment_method: payment_method_request.payment_method, payment_method_type: payment_method_request.payment_method_type, card: None, metadata: None, created: Some(common_utils::date_time::now()), recurring_enabled: Some(false), installment_payment_enabled: Some(false), payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), #[cfg(feature = "payouts")] bank_transfer: None, last_used_at: Some(common_utils::date_time::now()), client_secret: None, }; Ok((payment_method_response, None)) } } } #[cfg(feature = "v2")] async fn skip_saving_card_in_locker( merchant_context: &domain::MerchantContext, payment_method_request: api::PaymentMethodCreate, ) -> RouterResult<( api_models::payment_methods::PaymentMethodResponse, Option<payment_methods::transformers::DataDuplicationCheck>, )> { todo!() } #[cfg(feature = "v1")] pub async fn save_in_locker_internal( state: &SessionState, merchant_context: &domain::MerchantContext, payment_method_request: api::PaymentMethodCreate, card_detail: Option<api::CardDetail>, ) -> RouterResult<( api_models::payment_methods::PaymentMethodResponse, Option<payment_methods::transformers::DataDuplicationCheck>, )> { payment_method_request.validate()?; let merchant_id = merchant_context.get_merchant_account().get_id(); let customer_id = payment_method_request .customer_id .clone() .get_required_value("customer_id")?; match (payment_method_request.card.clone(), card_detail) { (_, Some(card)) | (Some(card), _) => Box::pin( PmCards { state, merchant_context, } .add_card_to_locker(payment_method_request, &card, &customer_id, None), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Card Failed"), _ => { let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm"); let payment_method_response = api::PaymentMethodResponse { merchant_id: merchant_id.clone(), customer_id: Some(customer_id), payment_method_id: pm_id, payment_method: payment_method_request.payment_method, payment_method_type: payment_method_request.payment_method_type, #[cfg(feature = "payouts")] bank_transfer: None, card: None, metadata: None, created: Some(common_utils::date_time::now()), recurring_enabled: Some(false), installment_payment_enabled: Some(false), payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219] last_used_at: Some(common_utils::date_time::now()), client_secret: None, }; Ok((payment_method_response, None)) } } } #[cfg(feature = "v1")] pub async fn save_in_locker_external( state: &SessionState, merchant_context: &domain::MerchantContext, payment_method_request: api::PaymentMethodCreate, card_detail: Option<api::CardDetail>, external_vault_connector_details: &ExternalVaultConnectorDetails, ) -> RouterResult<( api_models::payment_methods::PaymentMethodResponse, Option<payment_methods::transformers::DataDuplicationCheck>, )> { let customer_id = payment_method_request .customer_id .clone() .get_required_value("customer_id")?; // For external vault, we need to convert the card data to PaymentMethodVaultingData if let Some(card) = card_detail { let payment_method_vaulting_data = hyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(card.clone()); let external_vault_mca_id = external_vault_connector_details.vault_connector_id.clone(); 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_context.get_merchant_account().get_id(), &external_vault_mca_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: external_vault_mca_id.get_string_repr().to_string(), })?; // Call vault_payment_method_external_v1 let vault_response = vault_payment_method_external_v1( state, &payment_method_vaulting_data, merchant_context.get_merchant_account(), merchant_connector_account_details, ) .await?; let payment_method_id = vault_response.vault_id.to_string().to_owned(); let card_detail = CardDetailFromLocker::from(card); let pm_resp = api::PaymentMethodResponse { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), customer_id: Some(customer_id), payment_method_id, payment_method: payment_method_request.payment_method, payment_method_type: payment_method_request.payment_method_type, card: Some(card_detail), recurring_enabled: Some(false), installment_payment_enabled: Some(false), payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), metadata: None, created: Some(common_utils::date_time::now()), #[cfg(feature = "payouts")] bank_transfer: None, last_used_at: Some(common_utils::date_time::now()), client_secret: None, }; Ok((pm_resp, None)) } else { //Similar implementation is done for save in locker internal let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm"); let payment_method_response = api::PaymentMethodResponse { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), customer_id: Some(customer_id), payment_method_id: pm_id, payment_method: payment_method_request.payment_method, payment_method_type: payment_method_request.payment_method_type, #[cfg(feature = "payouts")] bank_transfer: None, card: None, metadata: None, created: Some(common_utils::date_time::now()), recurring_enabled: Some(false), installment_payment_enabled: Some(false), payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219] last_used_at: Some(common_utils::date_time::now()), client_secret: None, }; Ok((payment_method_response, None)) } } #[cfg(feature = "v2")] pub async fn save_in_locker_internal( _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_method_request: api::PaymentMethodCreate, ) -> RouterResult<( api_models::payment_methods::PaymentMethodResponse, Option<payment_methods::transformers::DataDuplicationCheck>, )> { todo!() } #[cfg(feature = "v2")] pub async fn save_network_token_in_locker( _state: &SessionState, _merchant_context: &domain::MerchantContext, _card_data: &domain::Card, _payment_method_request: api::PaymentMethodCreate, ) -> RouterResult<( Option<api_models::payment_methods::PaymentMethodResponse>, Option<payment_methods::transformers::DataDuplicationCheck>, Option<String>, )> { todo!() } #[cfg(feature = "v1")] pub async fn save_network_token_in_locker( state: &SessionState, merchant_context: &domain::MerchantContext, card_data: &payment_method_data::Card, network_token_data: Option<api::CardDetail>, payment_method_request: api::PaymentMethodCreate, ) -> RouterResult<( Option<api_models::payment_methods::PaymentMethodResponse>, Option<payment_methods::transformers::DataDuplicationCheck>, Option<String>, )> { let customer_id = payment_method_request .customer_id .clone() .get_required_value("customer_id")?; let network_tokenization_supported_card_networks = &state .conf .network_tokenization_supported_card_networks .card_networks; match network_token_data { Some(nt_data) => { let (res, dc) = Box::pin( PmCards { state, merchant_context, } .add_card_to_locker( payment_method_request, &nt_data, &customer_id, None, ), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Network Token Failed")?; Ok((Some(res), dc, None)) } None => { if card_data .card_network .as_ref() .filter(|cn| network_tokenization_supported_card_networks.contains(cn)) .is_some() { let optional_card_cvc = Some(card_data.card_cvc.clone()); match network_tokenization::make_card_network_tokenization_request( state, &domain::CardDetail::from(card_data), optional_card_cvc, &customer_id, ) .await { Ok((token_response, network_token_requestor_ref_id)) => { // Only proceed if the tokenization was successful let network_token_data = api::CardDetail { card_number: token_response.token.clone(), card_exp_month: token_response.token_expiry_month.clone(), card_exp_year: token_response.token_expiry_year.clone(), card_holder_name: None, nick_name: None, card_issuing_country: None, card_network: Some(token_response.card_brand.clone()), card_issuer: None, card_type: None, }; let (res, dc) = Box::pin( PmCards { state, merchant_context, } .add_card_to_locker( payment_method_request, &network_token_data, &customer_id, None, ), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Network Token Failed")?; Ok((Some(res), dc, network_token_requestor_ref_id)) } Err(err) => { logger::error!("Failed to tokenize card: {:?}", err); Ok((None, None, None)) //None will be returned in case of error when calling network tokenization service } } } else { Ok((None, None, None)) //None will be returned in case of unsupported card network. } } } } pub fn handle_tokenization_response<F, Req>( resp: &mut types::RouterData<F, Req, types::PaymentsResponseData>, ) { let response = resp.response.clone(); if let Err(err) = response { if let Some(secret_metadata) = &err.connector_metadata { let metadata = secret_metadata.clone().expose(); if let Some(token) = metadata .get("payment_method_token") .and_then(|t| t.as_str()) { resp.response = Ok(types::PaymentsResponseData::TokenizationResponse { token: token.to_string(), }); } } } } pub fn create_payment_method_metadata( metadata: Option<&pii::SecretSerdeValue>, connector_token: Option<(String, String)>, ) -> RouterResult<Option<serde_json::Value>> { let mut meta = match metadata { None => serde_json::Map::new(), Some(meta) => { let metadata = meta.clone().expose(); let existing_metadata: serde_json::Map<String, serde_json::Value> = metadata .parse_value("Map<String, Value>") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse the metadata")?; existing_metadata } }; Ok(connector_token.and_then(|connector_and_token| { meta.insert( connector_and_token.0, serde_json::Value::String(connector_and_token.1), ) })) } pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>( state: &SessionState, connector: &api::ConnectorData, tokenization_action: &payments::TokenizationAction, router_data: &mut types::RouterData<F, T, types::PaymentsResponseData>, pm_token_request_data: types::PaymentMethodTokenizationData, should_continue_payment: bool, ) -> RouterResult<types::PaymentMethodTokenResult> { if should_continue_payment { match tokenization_action { payments::TokenizationAction::TokenizeInConnector => { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let pm_token_response_data: Result< types::PaymentsResponseData, types::ErrorResponse, > = Err(types::ErrorResponse::default()); let pm_token_router_data = helpers::router_data_type_conversion::<_, api::PaymentMethodToken, _, _, _, _>( router_data.clone(), pm_token_request_data, pm_token_response_data, ); router_data .request .set_session_token(pm_token_router_data.session_token.clone()); let mut resp = services::execute_connector_processing_step( state, connector_integration, &pm_token_router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_payment_failed_response()?; // checks for metadata in the ErrorResponse, if present bypasses it and constructs an Ok response handle_tokenization_response(&mut resp); metrics::CONNECTOR_PAYMENT_METHOD_TOKENIZATION.add( 1, router_env::metric_attributes!( ("connector", connector.connector_name.to_string()), ("payment_method", router_data.payment_method.to_string()), ), ); let payment_token_resp = resp.response.map(|res| { if let types::PaymentsResponseData::TokenizationResponse { token } = res { Some(token) } else { None } }); Ok(types::PaymentMethodTokenResult { payment_method_token_result: payment_token_resp, is_payment_method_tokenization_performed: true, connector_response: resp.connector_response.clone(), }) } _ => Ok(types::PaymentMethodTokenResult { payment_method_token_result: Ok(None), is_payment_method_tokenization_performed: false, connector_response: None, }), } } else { logger::debug!("Skipping connector tokenization based on should_continue_payment flag"); Ok(types::PaymentMethodTokenResult { payment_method_token_result: Ok(None), is_payment_method_tokenization_performed: false, connector_response: None, }) } } pub fn update_router_data_with_payment_method_token_result<F: Clone, T>( payment_method_token_result: types::PaymentMethodTokenResult, router_data: &mut types::RouterData<F, T, types::PaymentsResponseData>, is_retry_payment: bool, should_continue_further: bool, ) -> bool { if payment_method_token_result.is_payment_method_tokenization_performed { match payment_method_token_result.payment_method_token_result { Ok(pm_token_result) => { router_data.payment_method_token = pm_token_result.map(|pm_token| { hyperswitch_domain_models::router_data::PaymentMethodToken::Token(Secret::new( pm_token, )) }); if router_data.connector_response.is_none() { router_data.connector_response = payment_method_token_result.connector_response.clone(); } true } Err(err) => { if is_retry_payment { router_data.response = Err(err); false } else { logger::debug!(payment_method_tokenization_error=?err); true } } } } else { should_continue_further } } #[cfg(feature = "v1")] pub fn add_connector_mandate_details_in_payment_method( payment_method_type: Option<storage_enums::PaymentMethodType>, authorized_amount: Option<i64>, authorized_currency: Option<storage_enums::Currency>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, connector_mandate_id: Option<String>, mandate_metadata: Option<Secret<serde_json::Value>>, connector_mandate_request_reference_id: Option<String>, ) -> Option<CommonMandateReference> { let mut mandate_details = HashMap::new(); if let Some((mca_id, connector_mandate_id)) = merchant_connector_id.clone().zip(connector_mandate_id) { mandate_details.insert( mca_id, PaymentsMandateReferenceRecord { connector_mandate_id, payment_method_type, original_payment_authorized_amount: authorized_amount, original_payment_authorized_currency: authorized_currency, mandate_metadata, connector_mandate_status: Some(ConnectorMandateStatus::Active), connector_mandate_request_reference_id, }, ); Some(CommonMandateReference { payments: Some(PaymentsMandateReference(mandate_details)), payouts: None, }) } else { None } } #[allow(clippy::too_many_arguments)] #[cfg(feature = "v1")] pub fn update_connector_mandate_details( mandate_details: Option<CommonMandateReference>, payment_method_type: Option<storage_enums::PaymentMethodType>, authorized_amount: Option<i64>, authorized_currency: Option<storage_enums::Currency>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, connector_mandate_id: Option<String>, mandate_metadata: Option<Secret<serde_json::Value>>, connector_mandate_request_reference_id: Option<String>, ) -> RouterResult<Option<CommonMandateReference>> { let mandate_reference = match mandate_details .as_ref() .and_then(|common_mandate| common_mandate.payments.clone()) { Some(mut payment_mandate_reference) => { if let Some((mca_id, connector_mandate_id)) = merchant_connector_id.clone().zip(connector_mandate_id) { let updated_record = PaymentsMandateReferenceRecord { connector_mandate_id: connector_mandate_id.clone(), payment_method_type, original_payment_authorized_amount: authorized_amount, original_payment_authorized_currency: authorized_currency, mandate_metadata: mandate_metadata.clone(), connector_mandate_status: Some(ConnectorMandateStatus::Active), connector_mandate_request_reference_id: connector_mandate_request_reference_id .clone(), }; payment_mandate_reference .entry(mca_id) .and_modify(|pm| *pm = updated_record) .or_insert(PaymentsMandateReferenceRecord { connector_mandate_id, payment_method_type, original_payment_authorized_amount: authorized_amount, original_payment_authorized_currency: authorized_currency, mandate_metadata: mandate_metadata.clone(), connector_mandate_status: Some(ConnectorMandateStatus::Active), connector_mandate_request_reference_id, }); let payout_data = mandate_details.and_then(|common_mandate| common_mandate.payouts); Some(CommonMandateReference { payments: Some(payment_mandate_reference), payouts: payout_data, }) } else { None } } None => add_connector_mandate_details_in_payment_method( payment_method_type, authorized_amount, authorized_currency, merchant_connector_id, connector_mandate_id, mandate_metadata, connector_mandate_request_reference_id, ), }; Ok(mandate_reference) } #[cfg(feature = "v1")] pub fn update_connector_mandate_details_status( merchant_connector_id: id_type::MerchantConnectorAccountId, mut payment_mandate_reference: PaymentsMandateReference, status: ConnectorMandateStatus, ) -> RouterResult<Option<CommonMandateReference>> { let mandate_reference = { payment_mandate_reference .entry(merchant_connector_id) .and_modify(|pm| { let update_rec = PaymentsMandateReferenceRecord { connector_mandate_id: pm.connector_mandate_id.clone(), payment_method_type: pm.payment_method_type, original_payment_authorized_amount: pm.original_payment_authorized_amount, original_payment_authorized_currency: pm.original_payment_authorized_currency, mandate_metadata: pm.mandate_metadata.clone(), connector_mandate_status: Some(status), connector_mandate_request_reference_id: pm .connector_mandate_request_reference_id .clone(), }; *pm = update_rec }); Some(payment_mandate_reference) }; Ok(Some(CommonMandateReference { payments: mandate_reference, payouts: None, })) } #[cfg(feature = "v2")] pub async fn add_token_for_payment_method( router_data: &mut types::RouterData< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, >, payment_method_data_request: types::PaymentMethodTokenizationData, state: SessionState, merchant_connector_account_details: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, ) -> RouterResult<types::PspTokenResult> { let connector_id = merchant_connector_account_details.id.clone(); let connector_data = api::ConnectorData::get_connector_by_name( &(state.conf.connectors), &merchant_connector_account_details .connector_name .to_string(), api::GetToken::Connector, Some(connector_id.clone()), )?; let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, > = connector_data.connector.get_connector_integration(); let payment_method_token_response_data_type: Result< types::PaymentsResponseData, types::ErrorResponse, > = Err(types::ErrorResponse::default()); let payment_method_token_router_data = helpers::router_data_type_conversion::<_, api::PaymentMethodToken, _, _, _, _>( router_data.clone(), payment_method_data_request.clone(), payment_method_token_response_data_type, ); let connector_integration_response = services::execute_connector_processing_step( &state, connector_integration, &payment_method_token_router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_payment_failed_response()?; let payment_token_response = connector_integration_response.response.map(|res| { if let types::PaymentsResponseData::TokenizationResponse { token } = res { Ok(token) } else { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get token from connector") } }); match payment_token_response { Ok(token) => Ok(types::PspTokenResult { token: Ok(token?) }), Err(error_response) => Ok(types::PspTokenResult { token: Err(error_response), }), } } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn save_card_and_network_token_in_locker( state: &SessionState, customer_id: id_type::CustomerId, payment_method_status: common_enums::PaymentMethodStatus, payment_method_data: domain::PaymentMethodData, vault_operation: Option<hyperswitch_domain_models::payments::VaultOperation>, payment_method_info: Option<domain::PaymentMethod>, merchant_context: &domain::MerchantContext, payment_method_create_request: api::PaymentMethodCreate, is_network_tokenization_enabled: bool, business_profile: &domain::Profile, ) -> RouterResult<( ( api_models::payment_methods::PaymentMethodResponse, Option<payment_methods::transformers::DataDuplicationCheck>, Option<String>, ), Option<api_models::payment_methods::PaymentMethodResponse>, )> { let network_token_requestor_reference_id = payment_method_info .and_then(|pm_info| pm_info.network_token_requestor_reference_id.clone()); match vault_operation { Some(hyperswitch_domain_models::payments::VaultOperation::SaveCardData(card)) => { let card_data = api::CardDetail::from(card.card_data.clone()); if let (Some(nt_ref_id), Some(tokenization_service)) = ( card.network_token_req_ref_id.clone(), &state.conf.network_tokenization_service, ) { let _ = record_operation_time( async { network_tokenization::delete_network_token_from_tokenization_service( state, nt_ref_id.clone(), &customer_id, tokenization_service.get_inner(), ) .await }, &metrics::DELETE_NETWORK_TOKEN_TIME, &[], ) .await; } let (res, dc) = Box::pin(save_in_locker( state, merchant_context, payment_method_create_request.to_owned(), Some(card_data), business_profile, )) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Card In Locker Failed")?; Ok(((res, dc, None), None)) } Some(hyperswitch_domain_models::payments::VaultOperation::SaveCardAndNetworkTokenData( save_card_and_network_token_data, )) => { let card_data = api::CardDetail::from(save_card_and_network_token_data.card_data.clone()); let network_token_data = api::CardDetail::from( save_card_and_network_token_data .network_token .network_token_data .clone(), ); if payment_method_status == common_enums::PaymentMethodStatus::Active { let (res, dc) = Box::pin(save_in_locker_internal( state, merchant_context, payment_method_create_request.to_owned(), Some(card_data), )) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Card In Locker Failed")?; let (network_token_resp, _dc, _) = Box::pin(save_network_token_in_locker( state, merchant_context, &save_card_and_network_token_data.card_data, Some(network_token_data), payment_method_create_request.clone(), )) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Network Token In Locker Failed")?; Ok(( (res, dc, network_token_requestor_reference_id), network_token_resp, )) } else { if let (Some(nt_ref_id), Some(tokenization_service)) = ( network_token_requestor_reference_id.clone(), &state.conf.network_tokenization_service, ) { let _ = record_operation_time( async { network_tokenization::delete_network_token_from_tokenization_service( state, nt_ref_id.clone(), &customer_id, tokenization_service.get_inner(), ) .await }, &metrics::DELETE_NETWORK_TOKEN_TIME, &[], ) .await; } let (res, dc) = Box::pin(save_in_locker_internal( state, merchant_context, payment_method_create_request.to_owned(), Some(card_data), )) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Card In Locker Failed")?; Ok(((res, dc, None), None)) } } _ => { let card_data = payment_method_create_request.card.clone(); let (res, dc) = Box::pin(save_in_locker( state, merchant_context, payment_method_create_request.to_owned(), card_data, business_profile, )) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Card In Locker Failed")?; if is_network_tokenization_enabled { match &payment_method_data { domain::PaymentMethodData::Card(card) => { let ( network_token_resp, _network_token_duplication_check, //the duplication check is discarded, since each card has only one token, handling card duplication check will be suffice network_token_requestor_ref_id, ) = Box::pin(save_network_token_in_locker( state, merchant_context, card, None, payment_method_create_request.clone(), )) .await?; Ok(( (res, dc, network_token_requestor_ref_id), network_token_resp, )) } _ => Ok(((res, dc, None), None)), //network_token_resp is None in case of other payment methods } } else { Ok(((res, dc, None), None)) } } } } </file>
{ "crate": "router", "file": "crates/router/src/core/payments/tokenization.rs", "files": null, "module": null, "num_files": null, "token_count": 13485 }
large_file_-2545729181458397840
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/payments/payment_methods.rs </path> <file> //! Contains functions of payment methods that are used in payments //! one of such functions is `list_payment_methods` use std::{ collections::{BTreeMap, HashSet}, str::FromStr, }; use common_utils::{ ext_traits::{OptionExt, ValueExt}, id_type, }; use error_stack::ResultExt; use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret; use super::errors; use crate::{ configs::settings, core::{payment_methods, payments::helpers}, db::errors::StorageErrorExt, logger, routes, types::{self, api, domain, storage}, }; #[cfg(feature = "v2")] pub async fn list_payment_methods( state: routes::SessionState, merchant_context: domain::MerchantContext, profile: domain::Profile, payment_id: id_type::GlobalPaymentId, req: api_models::payments::ListMethodsForPaymentsRequest, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> errors::RouterResponse<api_models::payments::PaymentMethodListResponseForPayments> { let db = &*state.store; let key_manager_state = &(&state).into(); let payment_intent = db .find_payment_intent_by_id( key_manager_state, &payment_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; validate_payment_status_for_payment_method_list(payment_intent.status)?; 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 = match &payment_intent.customer_id { Some(customer_id) => Some( payment_methods::list_customer_payment_methods_core( &state, &merchant_context, customer_id, ) .await?, ), None => None, }; let response = FlattenedPaymentMethodsEnabled(hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled::from_payment_connectors_list(payment_connector_accounts)) .perform_filtering( &state, &merchant_context, profile.get_id(), &req, &payment_intent, ).await? .store_gift_card_mca_in_redis(&payment_id, db, &profile).await .merge_and_transform() .get_required_fields(RequiredFieldsInput::new(state.conf.required_fields.clone(), payment_intent.setup_future_usage)) .perform_surcharge_calculation() .populate_pm_subtype_specific_data(&state.conf.bank_config) .generate_response(customer_payment_methods); Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) } /// Container for the inputs required for the required fields struct RequiredFieldsInput { required_fields_config: settings::RequiredFields, setup_future_usage: common_enums::FutureUsage, } impl RequiredFieldsInput { fn new( required_fields_config: settings::RequiredFields, setup_future_usage: common_enums::FutureUsage, ) -> Self { Self { required_fields_config, setup_future_usage, } } } trait GetRequiredFields { fn get_required_fields( &self, payment_method_enabled: &MergedEnabledPaymentMethod, ) -> Option<&settings::RequiredFieldFinal>; } impl GetRequiredFields for settings::RequiredFields { fn get_required_fields( &self, payment_method_enabled: &MergedEnabledPaymentMethod, ) -> Option<&settings::RequiredFieldFinal> { self.0 .get(&payment_method_enabled.payment_method_type) .and_then(|required_fields_for_payment_method| { required_fields_for_payment_method .0 .get(&payment_method_enabled.payment_method_subtype) }) .map(|connector_fields| &connector_fields.fields) .and_then(|connector_hashmap| { payment_method_enabled .connectors .first() .and_then(|connector| connector_hashmap.get(connector)) }) } } struct FlattenedPaymentMethodsEnabled( hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled, ); /// Container for the filtered payment methods struct FilteredPaymentMethodsEnabled( Vec<hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector>, ); impl FilteredPaymentMethodsEnabled { fn merge_and_transform(self) -> MergedEnabledPaymentMethodTypes { let values = self .0 .into_iter() // BTreeMap used to ensure soretd response, otherwise the response is arbitrarily ordered .fold(BTreeMap::new(), |mut acc, item| { let key = ( item.payment_method, item.payment_methods_enabled.payment_method_subtype, ); let (experiences, connectors) = acc .entry(key) // HashSet used to ensure payment_experience does not have duplicates, due to multiple connectors for a pm_subtype .or_insert_with(|| (HashSet::new(), Vec::new())); if let Some(experience) = item.payment_methods_enabled.payment_experience { experiences.insert(experience); } connectors.push(item.connector); acc }) .into_iter() .map( |( (payment_method_type, payment_method_subtype), (payment_experience, connectors), )| { MergedEnabledPaymentMethod { payment_method_type, payment_method_subtype, payment_experience: if payment_experience.is_empty() { None } else { Some(payment_experience.into_iter().collect()) }, connectors, } }, ) .collect(); MergedEnabledPaymentMethodTypes(values) } async fn store_gift_card_mca_in_redis( self, payment_id: &id_type::GlobalPaymentId, db: &dyn crate::db::StorageInterface, profile: &domain::Profile, ) -> Self { let gift_card_connector_id = self .0 .iter() .find(|item| item.payment_method == common_enums::PaymentMethod::GiftCard) .map(|item| &item.merchant_connector_id); if let Some(gift_card_mca) = gift_card_connector_id { let gc_key = payment_id.get_gift_card_connector_key(); let redis_expiry = profile .get_order_fulfillment_time() .unwrap_or(common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME); let redis_conn = db .get_redis_conn() .map_err(|redis_error| logger::error!(?redis_error)) .ok(); if let Some(rc) = redis_conn { rc.set_key_with_expiry( &gc_key.as_str().into(), gift_card_mca.get_string_repr().to_string(), redis_expiry, ) .await .attach_printable("Failed to store gift card mca_id in redis") .unwrap_or_else(|error| { logger::error!(?error); }) }; } else { logger::error!( "Could not find any configured MCA supporting gift card for payment_id -> {}", payment_id.get_string_repr() ); } self } } /// Element container to hold the filtered payment methods with payment_experience and connectors merged for a pm_subtype struct MergedEnabledPaymentMethod { payment_method_subtype: common_enums::PaymentMethodType, payment_method_type: common_enums::PaymentMethod, payment_experience: Option<Vec<common_enums::PaymentExperience>>, connectors: Vec<api_models::enums::Connector>, } /// Container to hold the filtered payment methods with payment_experience and connectors merged for a pm_subtype struct MergedEnabledPaymentMethodTypes(Vec<MergedEnabledPaymentMethod>); impl MergedEnabledPaymentMethodTypes { fn get_required_fields( self, input: RequiredFieldsInput, ) -> RequiredFieldsForEnabledPaymentMethodTypes { let required_fields_config = input.required_fields_config; let is_cit_transaction = input.setup_future_usage == common_enums::FutureUsage::OffSession; 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); // Collect non-mandate required fields because this is for zero auth mandates only let non_mandate_required_fields = required_fields .non_mandate .iter() .flatten() .map(ToOwned::to_owned); // Combine mandate and non-mandate required fields based on setup_future_usage if is_cit_transaction { common_required_fields .chain(non_mandate_required_fields) .collect::<Vec<_>>() } else { common_required_fields .chain(mandate_required_fields) .collect::<Vec<_>>() } }) .unwrap_or_default(); RequiredFieldsForEnabledPaymentMethod { required_fields, payment_method_type: payment_methods_enabled.payment_method_type, payment_method_subtype: payment_methods_enabled.payment_method_subtype, payment_experience: payment_methods_enabled.payment_experience, connectors: payment_methods_enabled.connectors, } }) .collect(); RequiredFieldsForEnabledPaymentMethodTypes(required_fields_info) } } /// Element container to hold the filtered payment methods with required fields struct RequiredFieldsForEnabledPaymentMethod { required_fields: Vec<api_models::payment_methods::RequiredFieldInfo>, payment_method_subtype: common_enums::PaymentMethodType, payment_method_type: common_enums::PaymentMethod, payment_experience: Option<Vec<common_enums::PaymentExperience>>, connectors: Vec<api_models::enums::Connector>, } /// Container to hold the filtered payment methods enabled with required fields struct RequiredFieldsForEnabledPaymentMethodTypes(Vec<RequiredFieldsForEnabledPaymentMethod>); impl RequiredFieldsForEnabledPaymentMethodTypes { fn perform_surcharge_calculation( self, ) -> RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes { // TODO: Perform surcharge calculation let details_with_surcharge = self .0 .into_iter() .map( |payment_methods_enabled| RequiredFieldsAndSurchargeForEnabledPaymentMethodType { payment_method_type: payment_methods_enabled.payment_method_type, required_fields: payment_methods_enabled.required_fields, payment_method_subtype: payment_methods_enabled.payment_method_subtype, payment_experience: payment_methods_enabled.payment_experience, surcharge: None, connectors: payment_methods_enabled.connectors, }, ) .collect(); RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes(details_with_surcharge) } } /// Element Container to hold the filtered payment methods enabled with required fields and surcharge struct RequiredFieldsAndSurchargeForEnabledPaymentMethodType { required_fields: Vec<api_models::payment_methods::RequiredFieldInfo>, payment_method_subtype: common_enums::PaymentMethodType, payment_method_type: common_enums::PaymentMethod, payment_experience: Option<Vec<common_enums::PaymentExperience>>, connectors: Vec<api_models::enums::Connector>, surcharge: Option<api_models::payment_methods::SurchargeDetailsResponse>, } /// Container to hold the filtered payment methods enabled with required fields and surcharge struct RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes( Vec<RequiredFieldsAndSurchargeForEnabledPaymentMethodType>, ); fn get_pm_subtype_specific_data( bank_config: &settings::BankRedirectConfig, payment_method_type: common_enums::enums::PaymentMethod, payment_method_subtype: common_enums::enums::PaymentMethodType, connectors: &[api_models::enums::Connector], ) -> Option<api_models::payment_methods::PaymentMethodSubtypeSpecificData> { match payment_method_type { // TODO: Return card_networks common_enums::PaymentMethod::Card | common_enums::PaymentMethod::CardRedirect => None, common_enums::PaymentMethod::BankRedirect | common_enums::PaymentMethod::BankTransfer | common_enums::PaymentMethod::BankDebit | common_enums::PaymentMethod::OpenBanking => { if let Some(connector_bank_names) = bank_config.0.get(&payment_method_subtype) { let bank_names = connectors .iter() .filter_map(|connector| { connector_bank_names.0.get(&connector.to_string()) .map(|connector_hash_set| { connector_hash_set.banks.clone() }) .or_else(|| { logger::debug!("Could not find any configured connectors for payment_method -> {payment_method_subtype} for connector -> {connector}"); None }) }) .flatten() .collect(); Some( api_models::payment_methods::PaymentMethodSubtypeSpecificData::Bank { bank_names, }, ) } else { logger::debug!("Could not find any configured banks for payment_method -> {payment_method_subtype}"); None } } common_enums::PaymentMethod::PayLater | common_enums::PaymentMethod::Wallet | common_enums::PaymentMethod::Crypto | common_enums::PaymentMethod::Reward | common_enums::PaymentMethod::RealTimePayment | common_enums::PaymentMethod::Upi | common_enums::PaymentMethod::Voucher | common_enums::PaymentMethod::GiftCard | common_enums::PaymentMethod::MobilePayment => None, } } impl RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes { fn populate_pm_subtype_specific_data( self, bank_config: &settings::BankRedirectConfig, ) -> RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodTypes { let response_payment_methods = self .0 .into_iter() .map(|payment_methods_enabled| { RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodType { payment_method_type: payment_methods_enabled.payment_method_type, payment_method_subtype: payment_methods_enabled.payment_method_subtype, payment_experience: payment_methods_enabled.payment_experience, required_fields: payment_methods_enabled.required_fields, surcharge: payment_methods_enabled.surcharge, pm_subtype_specific_data: get_pm_subtype_specific_data( bank_config, payment_methods_enabled.payment_method_type, payment_methods_enabled.payment_method_subtype, &payment_methods_enabled.connectors, ), } }) .collect(); RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodTypes( response_payment_methods, ) } } /// Element Container to hold the filtered payment methods enabled with required fields, surcharge and subtype specific data struct RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodType { required_fields: Vec<api_models::payment_methods::RequiredFieldInfo>, payment_method_subtype: common_enums::PaymentMethodType, payment_method_type: common_enums::PaymentMethod, payment_experience: Option<Vec<common_enums::PaymentExperience>>, surcharge: Option<api_models::payment_methods::SurchargeDetailsResponse>, pm_subtype_specific_data: Option<api_models::payment_methods::PaymentMethodSubtypeSpecificData>, } /// Container to hold the filtered payment methods enabled with required fields, surcharge and subtype specific data struct RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodTypes( Vec<RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodType>, ); impl RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodTypes { fn generate_response( self, customer_payment_methods: Option< Vec<api_models::payment_methods::CustomerPaymentMethodResponseItem>, >, ) -> api_models::payments::PaymentMethodListResponseForPayments { let response_payment_methods = self .0 .into_iter() .map(|payment_methods_enabled| { api_models::payments::ResponsePaymentMethodTypesForPayments { payment_method_type: payment_methods_enabled.payment_method_type, payment_method_subtype: payment_methods_enabled.payment_method_subtype, payment_experience: payment_methods_enabled.payment_experience, required_fields: payment_methods_enabled.required_fields, surcharge_details: payment_methods_enabled.surcharge, extra_information: payment_methods_enabled.pm_subtype_specific_data, } }) .collect(); api_models::payments::PaymentMethodListResponseForPayments { payment_methods_enabled: response_payment_methods, customer_payment_methods, } } } impl FlattenedPaymentMethodsEnabled { async fn perform_filtering( self, state: &routes::SessionState, merchant_context: &domain::MerchantContext, profile_id: &id_type::ProfileId, req: &api_models::payments::ListMethodsForPaymentsRequest, payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, ) -> errors::RouterResult<FilteredPaymentMethodsEnabled> { let billing_address = payment_intent .billing_address .clone() .and_then(|address| address.into_inner().address); let mut response: Vec<hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector> = vec![]; for payment_method_enabled_details in self.0.payment_methods_enabled { filter_payment_methods( payment_method_enabled_details, req, &mut response, Some(payment_intent), billing_address.as_ref(), &state.conf, ) .await?; } Ok(FilteredPaymentMethodsEnabled(response)) } } // note: v2 type for ListMethodsForPaymentMethodsRequest will not have the installment_payment_enabled field, #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn filter_payment_methods( payment_method_type_details: hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector, req: &api_models::payments::ListMethodsForPaymentsRequest, resp: &mut Vec< hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector, >, payment_intent: Option<&storage::PaymentIntent>, address: Option<&hyperswitch_domain_models::address::AddressDetails>, configs: &settings::Settings<RawSecret>, ) -> errors::CustomResult<(), errors::ApiErrorResponse> { let payment_method = payment_method_type_details.payment_method; let mut payment_method_object = payment_method_type_details.payment_methods_enabled.clone(); // filter based on request parameters let request_based_filter = filter_recurring_based(&payment_method_object, req.recurring_enabled) && filter_amount_based(&payment_method_object, req.amount) && filter_card_network_based( payment_method_object.card_networks.as_ref(), req.card_networks.as_ref(), payment_method_object.payment_method_subtype, ); // filter based on payment intent let intent_based_filter = if let Some(payment_intent) = payment_intent { filter_country_based(address, &payment_method_object) && filter_currency_based( payment_intent.amount_details.currency, &payment_method_object, ) && filter_amount_based( &payment_method_object, Some(payment_intent.amount_details.calculate_net_amount()), ) && filter_zero_mandate_based(configs, payment_intent, &payment_method_type_details) && filter_allowed_payment_method_types_based( payment_intent.allowed_payment_method_types.as_ref(), payment_method_object.payment_method_subtype, ) } else { true }; // filter based on payment method type configuration let config_based_filter = filter_config_based( configs, &payment_method_type_details.connector.to_string(), payment_method_object.payment_method_subtype, payment_intent, &mut payment_method_object.card_networks, address.and_then(|inner| inner.country), payment_intent.map(|value| value.amount_details.currency), ); // if all filters pass, add the payment method type details to the response if request_based_filter && intent_based_filter && config_based_filter { resp.push(payment_method_type_details); } Ok(()) } // filter based on country supported by payment method type // return true if the intent's country is null or if the country is in the accepted countries list fn filter_country_based( address: Option<&hyperswitch_domain_models::address::AddressDetails>, pm: &common_types::payment_methods::RequestPaymentMethodTypes, ) -> bool { address.is_none_or(|address| { address.country.as_ref().is_none_or(|country| { pm.accepted_countries.as_ref().is_none_or(|ac| match ac { common_types::payment_methods::AcceptedCountries::EnableOnly(acc) => { acc.contains(country) } common_types::payment_methods::AcceptedCountries::DisableOnly(den) => { !den.contains(country) } common_types::payment_methods::AcceptedCountries::AllAccepted => true, }) }) }) } // filter based on currency supported by payment method type // return true if the intent's currency is null or if the currency is in the accepted currencies list fn filter_currency_based( currency: common_enums::Currency, pm: &common_types::payment_methods::RequestPaymentMethodTypes, ) -> bool { pm.accepted_currencies.as_ref().is_none_or(|ac| match ac { common_types::payment_methods::AcceptedCurrencies::EnableOnly(acc) => { acc.contains(&currency) } common_types::payment_methods::AcceptedCurrencies::DisableOnly(den) => { !den.contains(&currency) } common_types::payment_methods::AcceptedCurrencies::AllAccepted => true, }) } // filter based on payment method type configuration // return true if the payment method type is in the configuration for the connector // return true if the configuration is not available for the connector fn filter_config_based<'a>( config: &'a settings::Settings<RawSecret>, connector: &'a str, payment_method_type: common_enums::PaymentMethodType, payment_intent: Option<&storage::PaymentIntent>, card_network: &mut Option<Vec<common_enums::CardNetwork>>, country: Option<common_enums::CountryAlpha2>, currency: Option<common_enums::Currency>, ) -> bool { config .pm_filters .0 .get(connector) .or_else(|| config.pm_filters.0.get("default")) .and_then(|inner| match payment_method_type { common_enums::PaymentMethodType::Credit | common_enums::PaymentMethodType::Debit => { inner .0 .get(&settings::PaymentMethodFilterKey::PaymentMethodType( payment_method_type, )) .map(|value| filter_config_country_currency_based(value, country, currency)) } payment_method_type => inner .0 .get(&settings::PaymentMethodFilterKey::PaymentMethodType( payment_method_type, )) .map(|value| filter_config_country_currency_based(value, country, currency)), }) .unwrap_or(true) } // filter country and currency based on config for payment method type // return true if the country and currency are in the accepted countries and currencies list fn filter_config_country_currency_based( item: &settings::CurrencyCountryFlowFilter, country: Option<common_enums::CountryAlpha2>, currency: Option<common_enums::Currency>, ) -> bool { let country_condition = item .country .as_ref() .zip(country.as_ref()) .map(|(lhs, rhs)| lhs.contains(rhs)); let currency_condition = item .currency .as_ref() .zip(currency) .map(|(lhs, rhs)| lhs.contains(&rhs)); country_condition.unwrap_or(true) && currency_condition.unwrap_or(true) } // filter based on recurring enabled parameter of request // return true if recurring_enabled is null or if it matches the payment method's recurring_enabled fn filter_recurring_based( payment_method: &common_types::payment_methods::RequestPaymentMethodTypes, recurring_enabled: Option<bool>, ) -> bool { recurring_enabled.is_none_or(|enabled| payment_method.recurring_enabled == Some(enabled)) } // filter based on valid amount range of payment method type // return true if the amount is within the payment method's minimum and maximum amount range // return true if the amount is null or zero fn filter_amount_based( payment_method: &common_types::payment_methods::RequestPaymentMethodTypes, amount: Option<types::MinorUnit>, ) -> bool { let min_check = amount .and_then(|amt| payment_method.minimum_amount.map(|min_amt| amt >= min_amt)) .unwrap_or(true); let max_check = amount .and_then(|amt| payment_method.maximum_amount.map(|max_amt| amt <= max_amt)) .unwrap_or(true); (min_check && max_check) || amount == Some(types::MinorUnit::zero()) } // return true if the intent is a zero mandate intent and the payment method is supported for zero mandates // return false if the intent is a zero mandate intent and the payment method is not supported for zero mandates // return true if the intent is not a zero mandate intent fn filter_zero_mandate_based( configs: &settings::Settings<RawSecret>, payment_intent: &storage::PaymentIntent, payment_method_type_details: &hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector, ) -> bool { if payment_intent.setup_future_usage == common_enums::FutureUsage::OffSession && payment_intent.amount_details.calculate_net_amount() == types::MinorUnit::zero() { configs .zero_mandates .supported_payment_methods .0 .get(&payment_method_type_details.payment_method) .and_then(|supported_pm_for_mandates| { supported_pm_for_mandates .0 .get( &payment_method_type_details .payment_methods_enabled .payment_method_subtype, ) .map(|supported_connector_for_mandates| { supported_connector_for_mandates .connector_list .contains(&payment_method_type_details.connector) }) }) .unwrap_or(false) } else { true } } // filter based on allowed payment method types // return true if the allowed types are null or if the payment method type is in the allowed types list fn filter_allowed_payment_method_types_based( allowed_types: Option<&Vec<api_models::enums::PaymentMethodType>>, payment_method_type: api_models::enums::PaymentMethodType, ) -> bool { allowed_types.is_none_or(|pm| pm.contains(&payment_method_type)) } // filter based on card networks // return true if the payment method type's card networks are a subset of the request's card networks // return true if the card networks are not specified in the request fn filter_card_network_based( pm_card_networks: Option<&Vec<api_models::enums::CardNetwork>>, request_card_networks: Option<&Vec<api_models::enums::CardNetwork>>, pm_type: api_models::enums::PaymentMethodType, ) -> bool { match pm_type { api_models::enums::PaymentMethodType::Credit | api_models::enums::PaymentMethodType::Debit => { match (pm_card_networks, request_card_networks) { (Some(pm_card_networks), Some(request_card_networks)) => request_card_networks .iter() .all(|card_network| pm_card_networks.contains(card_network)), (None, Some(_)) => false, _ => true, } } _ => true, } } /// Validate if payment methods list can be performed on the current status of payment intent fn validate_payment_status_for_payment_method_list( 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: "list_payment_methods".to_string(), field_name: "status".to_string(), current_value: intent_status.to_string(), states: ["requires_payment_method".to_string()].join(", "), }) } } } </file>
{ "crate": "router", "file": "crates/router/src/core/payments/payment_methods.rs", "files": null, "module": null, "num_files": null, "token_count": 6328 }
large_file_-3751045133191515166
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/payments/types.rs </path> <file> 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()) } } } </file>
{ "crate": "router", "file": "crates/router/src/core/payments/types.rs", "files": null, "module": null, "num_files": null, "token_count": 3314 }
large_file_1654828196352520402
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/payments/vault_session.rs </path> <file> use std::{fmt::Debug, str::FromStr}; pub use common_enums::enums::CallConnectorAction; use common_utils::id_type; use error_stack::{report, ResultExt}; pub use hyperswitch_domain_models::{ mandates::MandateData, payment_address::PaymentAddress, payments::{HeaderPayload, PaymentIntentData}, router_data::{PaymentMethodToken, RouterData}, router_data_v2::{flow_common_types::VaultConnectorFlowData, RouterDataV2}, router_flow_types::ExternalVaultCreateFlow, router_request_types::CustomerDetails, types::{VaultRouterData, VaultRouterDataV2}, }; use hyperswitch_interfaces::{ api::Connector as ConnectorTrait, connector_integration_v2::{ConnectorIntegrationV2, ConnectorV2}, }; use masking::ExposeInterface; use router_env::{env::Env, instrument, tracing}; use crate::{ core::{ errors::{self, utils::StorageErrorExt, RouterResult}, payments::{ self as payments_core, call_multiple_connectors_service, customers, flows::{ConstructFlowSpecificData, Feature}, helpers, helpers as payment_helpers, operations, operations::{BoxedOperation, Operation}, transformers, OperationSessionGetters, OperationSessionSetters, }, utils as core_utils, }, db::errors::ConnectorErrorExt, errors::RouterResponse, routes::{app::ReqState, SessionState}, services::{self, connector_integration_interface::RouterDataConversion}, types::{ self as router_types, api::{self, enums as api_enums, ConnectorCommon}, domain, storage, }, utils::{OptionExt, ValueExt}, }; #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn populate_vault_session_details<F, RouterDReq, ApiRequest, D>( state: &SessionState, req_state: ReqState, customer: &Option<domain::Customer>, merchant_context: &domain::MerchantContext, operation: &BoxedOperation<'_, F, ApiRequest, D>, profile: &domain::Profile, payment_data: &mut D, header_payload: HeaderPayload, ) -> RouterResult<()> 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 is_external_vault_sdk_enabled = profile.is_vault_sdk_enabled(); if is_external_vault_sdk_enabled { let external_vault_source = profile .external_vault_connector_details .as_ref() .map(|details| &details.vault_connector_id); let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new( helpers::get_merchant_connector_account_v2( state, merchant_context.get_merchant_key_store(), external_vault_source, ) .await?, )); let updated_customer = call_create_connector_customer_if_required( state, customer, merchant_context, &merchant_connector_account, payment_data, ) .await?; if let Some((customer, updated_customer)) = customer.clone().zip(updated_customer) { let db = &*state.store; let customer_id = customer.get_id().clone(); let customer_merchant_id = customer.merchant_id.clone(); let _updated_customer = db .update_customer_by_global_id( &state.into(), &customer_id, customer, updated_customer, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update customer during Vault session")?; }; let vault_session_details = generate_vault_session_details( state, merchant_context, &merchant_connector_account, payment_data.get_connector_customer_id(), ) .await?; payment_data.set_vault_session_details(vault_session_details); } Ok(()) } #[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_type: &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 db_merchant_connector_account = merchant_connector_account_type.get_inner_db_merchant_connector_account(); match db_merchant_connector_account { Some(merchant_connector_account) => { let connector_name = merchant_connector_account.get_connector_name_as_string(); let merchant_connector_id = merchant_connector_account.get_id(); let connector = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_name, api::GetToken::Connector, Some(merchant_connector_id.clone()), )?; let (should_call_connector, existing_connector_customer_id) = customers::should_call_connector_create_customer( &connector, customer, payment_data.get_payment_attempt(), merchant_connector_account_type, ); 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_type, 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_type, 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 => { router_env::logger::error!( "Merchant connector account is missing, cannot create customer for vault session" ); Err(errors::ApiErrorResponse::InternalServerError.into()) } } } #[cfg(feature = "v2")] pub async fn generate_vault_session_details( state: &SessionState, merchant_context: &domain::MerchantContext, merchant_connector_account_type: &domain::MerchantConnectorAccountTypeDetails, connector_customer_id: Option<String>, ) -> RouterResult<Option<api::VaultSessionDetails>> { let connector_name = merchant_connector_account_type .get_connector_name() .map(|name| name.to_string()) .ok_or(errors::ApiErrorResponse::InternalServerError)?; // should not panic since we should always have a connector name let connector = api_enums::VaultConnectors::from_str(&connector_name) .change_context(errors::ApiErrorResponse::InternalServerError)?; let connector_auth_type: router_types::ConnectorAuthType = merchant_connector_account_type .get_connector_account_details() .map_err(|err| { err.change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse connector auth type") })?; match (connector, connector_auth_type) { // create session for vgs vault ( api_enums::VaultConnectors::Vgs, router_types::ConnectorAuthType::SignatureKey { api_secret, .. }, ) => { let sdk_env = match state.conf.env { Env::Sandbox | Env::Development => "sandbox", Env::Production => "live", } .to_string(); Ok(Some(api::VaultSessionDetails::Vgs( api::VgsSessionDetails { external_vault_id: api_secret, sdk_env, }, ))) } // create session for hyperswitch vault ( api_enums::VaultConnectors::HyperswitchVault, router_types::ConnectorAuthType::SignatureKey { key1, api_secret, .. }, ) => { generate_hyperswitch_vault_session_details( state, merchant_context, merchant_connector_account_type, connector_customer_id, connector_name, key1, api_secret, ) .await } _ => { router_env::logger::warn!( "External vault session creation is not supported for connector: {}", connector_name ); Ok(None) } } } async fn generate_hyperswitch_vault_session_details( state: &SessionState, merchant_context: &domain::MerchantContext, merchant_connector_account_type: &domain::MerchantConnectorAccountTypeDetails, connector_customer_id: Option<String>, connector_name: String, vault_publishable_key: masking::Secret<String>, vault_profile_id: masking::Secret<String>, ) -> RouterResult<Option<api::VaultSessionDetails>> { let connector_response = call_external_vault_create( state, merchant_context, connector_name, merchant_connector_account_type, connector_customer_id, ) .await?; match connector_response.response { Ok(router_types::VaultResponseData::ExternalVaultCreateResponse { session_id, client_secret, }) => Ok(Some(api::VaultSessionDetails::HyperswitchVault( api::HyperswitchVaultSessionDetails { payment_method_session_id: session_id, client_secret, publishable_key: vault_publishable_key, profile_id: vault_profile_id, }, ))), Ok(_) => { router_env::logger::warn!("Unexpected response from external vault create API"); Err(errors::ApiErrorResponse::InternalServerError.into()) } Err(err) => { router_env::logger::error!(error_response_from_external_vault_create=?err); Err(errors::ApiErrorResponse::InternalServerError.into()) } } } #[cfg(feature = "v2")] async fn call_external_vault_create( state: &SessionState, merchant_context: &domain::MerchantContext, connector_name: String, merchant_connector_account_type: &domain::MerchantConnectorAccountTypeDetails, connector_customer_id: Option<String>, ) -> RouterResult<VaultRouterData<ExternalVaultCreateFlow>> where dyn ConnectorTrait + Sync: services::api::ConnectorIntegration< ExternalVaultCreateFlow, router_types::VaultRequestData, router_types::VaultResponseData, >, dyn ConnectorV2 + Sync: ConnectorIntegrationV2< ExternalVaultCreateFlow, VaultConnectorFlowData, router_types::VaultRequestData, router_types::VaultResponseData, >, { let connector_data: api::ConnectorData = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_name, api::GetToken::Connector, merchant_connector_account_type.get_mca_id(), )?; let merchant_connector_account = match &merchant_connector_account_type { 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 mut router_data = core_utils::construct_vault_router_data( state, merchant_context.get_merchant_account().get_id(), merchant_connector_account, None, None, connector_customer_id, ) .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 create api call", )?; let connector_integration: services::BoxedVaultConnectorIntegrationInterface< ExternalVaultCreateFlow, router_types::VaultRequestData, router_types::VaultResponseData, > = connector_data.connector.get_connector_integration(); services::execute_connector_processing_step( state, connector_integration, &old_router_data, CallConnectorAction::Trigger, None, None, ) .await .to_vault_failed_response() } </file>
{ "crate": "router", "file": "crates/router/src/core/payments/vault_session.rs", "files": null, "module": null, "num_files": null, "token_count": 2836 }
large_file_6190899907478948207
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/payments/access_token.rs </path> <file> use std::fmt::Debug; use common_utils::ext_traits::AsyncExt; use error_stack::ResultExt; use hyperswitch_interfaces::api::ConnectorSpecifications; use crate::{ consts, core::{ errors::{self, RouterResult}, payments, }, routes::{metrics, SessionState}, services::{self, logger}, types::{self, api as api_types, domain}, }; /// After we get the access token, check if there was an error and if the flow should proceed further /// Returns bool /// true - Everything is well, continue with the flow /// false - There was an error, cannot proceed further pub fn update_router_data_with_access_token_result<F, Req, Res>( add_access_token_result: &types::AddAccessTokenResult, router_data: &mut types::RouterData<F, Req, Res>, call_connector_action: &payments::CallConnectorAction, ) -> bool { // Update router data with access token or error only if it will be calling connector let should_update_router_data = matches!( ( add_access_token_result.connector_supports_access_token, call_connector_action ), (true, payments::CallConnectorAction::Trigger) ); if should_update_router_data { match add_access_token_result.access_token_result.as_ref() { Ok(access_token) => { router_data.access_token.clone_from(access_token); true } Err(connector_error) => { router_data.response = Err(connector_error.clone()); false } } } else { true } } pub async fn add_access_token< F: Clone + 'static, Req: Debug + Clone + 'static, Res: Debug + Clone + 'static, >( state: &SessionState, connector: &api_types::ConnectorData, merchant_context: &domain::MerchantContext, router_data: &types::RouterData<F, Req, Res>, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { if connector .connector_name .supports_access_token(router_data.payment_method) { let merchant_id = merchant_context.get_merchant_account().get_id(); let store = &*state.store; // `merchant_connector_id` may not be present in the below cases // - when straight through routing is used without passing the `merchant_connector_id` // - when creds identifier is passed // // In these cases fallback to `connector_name`. // We cannot use multiple merchant connector account in these cases let merchant_connector_id_or_connector_name = connector .merchant_connector_id .clone() .map(|mca_id| mca_id.get_string_repr().to_string()) .or(creds_identifier.map(|id| id.to_string())) .unwrap_or(connector.connector_name.to_string()); let old_access_token = store .get_access_token(merchant_id, &merchant_connector_id_or_connector_name) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("DB error when accessing the access token")?; let res = match old_access_token { Some(access_token) => { router_env::logger::debug!( "Access token found in redis for merchant_id: {:?}, payment_id: {:?}, connector: {} which has expiry of: {} seconds", merchant_context.get_merchant_account().get_id(), router_data.payment_id, connector.connector_name, access_token.expires ); metrics::ACCESS_TOKEN_CACHE_HIT.add( 1, router_env::metric_attributes!(( "connector", connector.connector_name.to_string() )), ); Ok(Some(access_token)) } None => { metrics::ACCESS_TOKEN_CACHE_MISS.add( 1, router_env::metric_attributes!(( "connector", connector.connector_name.to_string() )), ); let authentication_token = execute_authentication_token(state, connector, router_data).await?; let cloned_router_data = router_data.clone(); let refresh_token_request_data = types::AccessTokenRequestData::try_from(( router_data.connector_auth_type.clone(), authentication_token, )) .attach_printable( "Could not create access token request, invalid connector account credentials", )?; let refresh_token_response_data: Result<types::AccessToken, types::ErrorResponse> = Err(types::ErrorResponse::default()); let refresh_token_router_data = payments::helpers::router_data_type_conversion::< _, api_types::AccessTokenAuth, _, _, _, _, >( cloned_router_data, refresh_token_request_data, refresh_token_response_data, ); refresh_connector_auth( state, connector, merchant_context, &refresh_token_router_data, ) .await? .async_map(|access_token| async move { let store = &*state.store; // The expiry should be adjusted for network delays from the connector // The access token might not have been expired when request is sent // But once it reaches the connector, it might expire because of the network delay // Subtract few seconds from the expiry in order to account for these network delays // This will reduce the expiry time by `REDUCE_ACCESS_TOKEN_EXPIRY_TIME` seconds let modified_access_token_with_expiry = types::AccessToken { expires: access_token .expires .saturating_sub(consts::REDUCE_ACCESS_TOKEN_EXPIRY_TIME.into()), ..access_token }; logger::debug!( access_token_expiry_after_modification = modified_access_token_with_expiry.expires ); if let Err(access_token_set_error) = store .set_access_token( merchant_id, &merchant_connector_id_or_connector_name, modified_access_token_with_expiry.clone(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("DB error when setting the access token") { // If we are not able to set the access token in redis, the error should just be logged and proceed with the payment // Payments should not fail, once the access token is successfully created // The next request will create new access token, if required logger::error!(access_token_set_error=?access_token_set_error); } Some(modified_access_token_with_expiry) }) .await } }; Ok(types::AddAccessTokenResult { access_token_result: res, connector_supports_access_token: true, }) } else { Ok(types::AddAccessTokenResult { access_token_result: Err(types::ErrorResponse::default()), connector_supports_access_token: false, }) } } pub async fn refresh_connector_auth( state: &SessionState, connector: &api_types::ConnectorData, _merchant_context: &domain::MerchantContext, router_data: &types::RouterData< api_types::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken, >, ) -> RouterResult<Result<types::AccessToken, types::ErrorResponse>> { let connector_integration: services::BoxedAccessTokenConnectorIntegrationInterface< api_types::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken, > = connector.connector.get_connector_integration(); let access_token_router_data_result = services::execute_connector_processing_step( state, connector_integration, router_data, payments::CallConnectorAction::Trigger, None, None, ) .await; let access_token_router_data = match access_token_router_data_result { Ok(router_data) => Ok(router_data.response), Err(connector_error) => { // If we receive a timeout error from the connector, then // the error has to be handled gracefully by updating the payment status to failed. // further payment flow will not be continued if connector_error.current_context().is_connector_timeout() { let error_response = types::ErrorResponse { code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(), message: consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string(), reason: Some(consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string()), status_code: 504, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }; Ok(Err(error_response)) } else { Err(connector_error .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not refresh access token")) } } }?; metrics::ACCESS_TOKEN_CREATION.add( 1, router_env::metric_attributes!(("connector", connector.connector_name.to_string())), ); Ok(access_token_router_data) } pub async fn execute_authentication_token< F: Clone + 'static, Req: Debug + Clone + 'static, Res: Debug + Clone + 'static, >( state: &SessionState, connector: &api_types::ConnectorData, router_data: &types::RouterData<F, Req, Res>, ) -> RouterResult<Option<types::AccessTokenAuthenticationResponse>> { let should_create_authentication_token = connector .connector .authentication_token_for_token_creation(); if !should_create_authentication_token { return Ok(None); } let authentication_token_request_data = types::AccessTokenAuthenticationRequestData::try_from( router_data.connector_auth_type.clone(), ) .attach_printable( "Could not create authentication token request, invalid connector account credentials", )?; let authentication_token_response_data: Result< types::AccessTokenAuthenticationResponse, types::ErrorResponse, > = Err(types::ErrorResponse::default()); let auth_token_router_data = payments::helpers::router_data_type_conversion::< _, api_types::AccessTokenAuthentication, _, _, _, _, >( router_data.clone(), authentication_token_request_data, authentication_token_response_data, ); let connector_integration: services::BoxedAuthenticationTokenConnectorIntegrationInterface< api_types::AccessTokenAuthentication, types::AccessTokenAuthenticationRequestData, types::AccessTokenAuthenticationResponse, > = connector.connector.get_connector_integration(); let auth_token_router_data_result = services::execute_connector_processing_step( state, connector_integration, &auth_token_router_data, payments::CallConnectorAction::Trigger, None, None, ) .await; let auth_token_result = match auth_token_router_data_result { Ok(router_data) => router_data.response, Err(connector_error) => { // Handle timeout errors if connector_error.current_context().is_connector_timeout() { let error_response = types::ErrorResponse { code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(), message: consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string(), reason: Some(consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string()), status_code: 504, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }; Err(error_response) } else { return Err(connector_error .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not get authentication token")); } } }; let authentication_token = auth_token_result .map_err(|_error| errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get authentication token")?; Ok(Some(authentication_token)) } </file>
{ "crate": "router", "file": "crates/router/src/core/payments/access_token.rs", "files": null, "module": null, "num_files": null, "token_count": 2466 }
large_file_-8266206015060125525
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/payments/flows.rs </path> <file> pub mod approve_flow; pub mod authorize_flow; pub mod cancel_flow; pub mod cancel_post_capture_flow; pub mod capture_flow; pub mod complete_authorize_flow; pub mod extend_authorization_flow; #[cfg(feature = "v2")] pub mod external_proxy_flow; pub mod incremental_authorization_flow; pub mod post_session_tokens_flow; pub mod psync_flow; pub mod reject_flow; pub mod session_flow; pub mod session_update_flow; pub mod setup_mandate_flow; pub mod update_metadata_flow; use async_trait::async_trait; use common_enums::{self, ExecutionMode}; use common_types::payments::CustomerAcceptance; use external_services::grpc_client; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_domain_models::router_flow_types::{ BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, InvoiceRecordBack, }; use hyperswitch_domain_models::{ payments as domain_payments, router_request_types::PaymentsCaptureData, }; use crate::{ core::{ errors::{ApiErrorResponse, RouterResult}, payments::{self, helpers}, }, logger, routes::SessionState, services, types as router_types, types::{self, api, api::enums as api_enums, domain}, }; #[async_trait] #[allow(clippy::too_many_arguments)] pub trait ConstructFlowSpecificData<F, Req, Res> { #[cfg(feature = "v1")] async fn construct_router_data<'a>( &self, state: &SessionState, connector_id: &str, merchant_context: &domain::MerchantContext, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, merchant_recipient_data: Option<types::MerchantRecipientData>, header_payload: Option<domain_payments::HeaderPayload>, payment_method: Option<common_enums::PaymentMethod>, payment_method_type: Option<common_enums::PaymentMethodType>, ) -> RouterResult<types::RouterData<F, Req, Res>>; #[cfg(feature = "v2")] async fn construct_router_data<'a>( &self, _state: &SessionState, _connector_id: &str, _merchant_context: &domain::MerchantContext, _customer: &Option<domain::Customer>, _merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails, _merchant_recipient_data: Option<types::MerchantRecipientData>, _header_payload: Option<domain_payments::HeaderPayload>, ) -> RouterResult<types::RouterData<F, Req, Res>>; async fn get_merchant_recipient_data<'a>( &self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _merchant_connector_account: &helpers::MerchantConnectorAccountType, _connector: &api::ConnectorData, ) -> RouterResult<Option<types::MerchantRecipientData>> { Ok(None) } } #[allow(clippy::too_many_arguments)] #[async_trait] pub trait Feature<F, T> { async fn decide_flows<'a>( self, state: &SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, business_profile: &domain::Profile, header_payload: domain_payments::HeaderPayload, return_raw_connector_response: Option<bool>, ) -> RouterResult<Self> where Self: Sized, F: Clone, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>; async fn add_access_token<'a>( &self, state: &SessionState, connector: &api::ConnectorData, merchant_context: &domain::MerchantContext, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>; async fn add_session_token<'a>( self, _state: &SessionState, _connector: &api::ConnectorData, ) -> RouterResult<Self> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, { Ok(self) } async fn add_payment_method_token<'a>( &mut self, _state: &SessionState, _connector: &api::ConnectorData, _tokenization_action: &payments::TokenizationAction, _should_continue_payment: bool, ) -> RouterResult<types::PaymentMethodTokenResult> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, { Ok(types::PaymentMethodTokenResult { payment_method_token_result: Ok(None), is_payment_method_tokenization_performed: false, connector_response: None, }) } async fn preprocessing_steps<'a>( self, _state: &SessionState, _connector: &api::ConnectorData, ) -> RouterResult<Self> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, { Ok(self) } async fn postprocessing_steps<'a>( self, _state: &SessionState, _connector: &api::ConnectorData, ) -> RouterResult<Self> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, { Ok(self) } async fn create_connector_customer<'a>( &self, _state: &SessionState, _connector: &api::ConnectorData, ) -> RouterResult<Option<String>> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, { Ok(None) } /// Returns the connector request and a bool which specifies whether to proceed with further async fn build_flow_specific_connector_request( &mut self, _state: &SessionState, _connector: &api::ConnectorData, _call_connector_action: payments::CallConnectorAction, ) -> RouterResult<(Option<services::Request>, bool)> { Ok((None, true)) } async fn create_order_at_connector( &mut self, _state: &SessionState, _connector: &api::ConnectorData, _should_continue_payment: bool, ) -> RouterResult<Option<types::CreateOrderResult>> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, { Ok(None) } fn update_router_data_with_create_order_response( &mut self, _create_order_result: types::CreateOrderResult, ) { } async fn call_unified_connector_service<'a>( &mut self, _state: &SessionState, _header_payload: &domain_payments::HeaderPayload, _lineage_ids: grpc_client::LineageIds, #[cfg(feature = "v1")] _merchant_connector_account: helpers::MerchantConnectorAccountType, #[cfg(feature = "v2")] _merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, _merchant_context: &domain::MerchantContext, _unified_connector_service_execution_mode: ExecutionMode, ) -> RouterResult<()> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, { Ok(()) } #[cfg(feature = "v2")] async fn call_unified_connector_service_with_external_vault_proxy<'a>( &mut self, _state: &SessionState, _header_payload: &domain_payments::HeaderPayload, _lineage_ids: grpc_client::LineageIds, _merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, _external_vault_merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, _merchant_context: &domain::MerchantContext, _unified_connector_service_execution_mode: ExecutionMode, ) -> RouterResult<()> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, { Ok(()) } } /// Determines whether a capture API call should be made for a payment attempt /// This function evaluates whether an authorized payment should proceed with a capture API call /// based on various payment parameters. It's primarily used in two-step (auth + capture) payment flows for CaptureMethod SequentialAutomatic /// pub fn should_initiate_capture_flow( connector_name: &router_types::Connector, customer_acceptance: Option<CustomerAcceptance>, capture_method: Option<api_enums::CaptureMethod>, setup_future_usage: Option<api_enums::FutureUsage>, status: common_enums::AttemptStatus, ) -> bool { match status { common_enums::AttemptStatus::Authorized => { if let Some(api_enums::CaptureMethod::SequentialAutomatic) = capture_method { match connector_name { router_types::Connector::Paybox => { // Check CIT conditions for Paybox setup_future_usage == Some(api_enums::FutureUsage::OffSession) && customer_acceptance.is_some() } _ => false, } } else { false } } _ => false, } } /// Executes a capture request by building a connector-specific request and deciding /// the appropriate flow to send it to the payment connector. pub async fn call_capture_request( mut capture_router_data: types::RouterData< api::Capture, PaymentsCaptureData, types::PaymentsResponseData, >, state: &SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, business_profile: &domain::Profile, header_payload: domain_payments::HeaderPayload, ) -> RouterResult<types::RouterData<api::Capture, PaymentsCaptureData, types::PaymentsResponseData>> { // Build capture-specific connector request let (connector_request, _should_continue_further) = capture_router_data .build_flow_specific_connector_request(state, connector, call_connector_action.clone()) .await?; // Execute capture flow capture_router_data .decide_flows( state, connector, call_connector_action, connector_request, business_profile, header_payload.clone(), None, ) .await } /// Processes the response from the capture flow and determines the final status and the response. fn handle_post_capture_response( authorize_router_data_response: types::PaymentsResponseData, post_capture_router_data: Result< types::RouterData<api::Capture, PaymentsCaptureData, types::PaymentsResponseData>, error_stack::Report<ApiErrorResponse>, >, ) -> RouterResult<(common_enums::AttemptStatus, types::PaymentsResponseData)> { match post_capture_router_data { Err(err) => { logger::error!( "Capture flow encountered an error: {:?}. Proceeding without updating.", err ); Ok(( common_enums::AttemptStatus::Authorized, authorize_router_data_response, )) } Ok(post_capture_router_data) => { match ( &post_capture_router_data.response, post_capture_router_data.status, ) { (Ok(post_capture_resp), common_enums::AttemptStatus::Charged) => Ok(( common_enums::AttemptStatus::Charged, types::PaymentsResponseData::merge_transaction_responses( &authorize_router_data_response, post_capture_resp, )?, )), _ => { logger::error!( "Error in post capture_router_data response: {:?}, Current Status: {:?}. Proceeding without updating.", post_capture_router_data.response, post_capture_router_data.status, ); Ok(( common_enums::AttemptStatus::Authorized, authorize_router_data_response, )) } } } } } </file>
{ "crate": "router", "file": "crates/router/src/core/payments/flows.rs", "files": null, "module": null, "num_files": null, "token_count": 2644 }
large_file_77338367375188649
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/payments/operations.rs </path> <file> #[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; } </file>
{ "crate": "router", "file": "crates/router/src/core/payments/operations.rs", "files": null, "module": null, "num_files": null, "token_count": 7584 }
large_file_-5477187277214457943
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/payments/retry.rs </path> <file> use std::vec::IntoIter; use common_utils::{ext_traits::Encode, types::MinorUnit}; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use hyperswitch_domain_models::ext_traits::OptionExt; use router_env::{ logger, tracing::{self, instrument}, }; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{ self, flows::{ConstructFlowSpecificData, Feature}, operations, }, routing::helpers as routing_helpers, }, db::StorageInterface, routes::{ self, app::{self, ReqState}, metrics, }, services, types::{self, api, domain, storage, transformers::ForeignFrom}, }; #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] #[cfg(feature = "v1")] pub async fn do_gsm_actions<'a, F, ApiRequest, FData, D>( state: &app::SessionState, req_state: ReqState, payment_data: &mut D, mut connector_routing_data: IntoIter<api::ConnectorRoutingData>, original_connector_data: &api::ConnectorData, mut router_data: types::RouterData<F, FData, types::PaymentsResponseData>, merchant_context: &domain::MerchantContext, operation: &operations::BoxedOperation<'_, F, ApiRequest, D>, customer: &Option<domain::Customer>, validate_result: &operations::ValidateResult, schedule_time: Option<time::PrimitiveDateTime>, frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &domain::Profile, ) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>> where F: Clone + Send + Sync + 'static, FData: Send + Sync + types::Capturable + Clone + 'static + serde::Serialize, payments::PaymentResponse: operations::Operation<F, FData>, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, FData, types::PaymentsResponseData>, types::RouterData<F, FData, types::PaymentsResponseData>: Feature<F, FData>, dyn api::Connector: services::api::ConnectorIntegration<F, FData, types::PaymentsResponseData>, { let mut retries = None; metrics::AUTO_RETRY_ELIGIBLE_REQUEST_COUNT.add(1, &[]); let mut initial_gsm = get_gsm(state, &router_data).await?; let step_up_possible = initial_gsm .as_ref() .and_then(|data| data.feature_data.get_retry_feature_data()) .map(|data| data.is_step_up_possible()) .unwrap_or(false); #[cfg(feature = "v1")] let is_no_three_ds_payment = matches!( payment_data.get_payment_attempt().authentication_type, Some(storage_enums::AuthenticationType::NoThreeDs) ); #[cfg(feature = "v2")] let is_no_three_ds_payment = matches!( payment_data.get_payment_attempt().authentication_type, storage_enums::AuthenticationType::NoThreeDs ); let should_step_up = if step_up_possible && is_no_three_ds_payment { is_step_up_enabled_for_merchant_connector( state, merchant_context.get_merchant_account().get_id(), original_connector_data.connector_name, ) .await } else { false }; if should_step_up { router_data = do_retry( &state.clone(), req_state.clone(), original_connector_data, operation, customer, merchant_context, payment_data, router_data, validate_result, schedule_time, true, frm_suggestion, business_profile, false, //should_retry_with_pan is not applicable for step-up None, ) .await?; } // Step up is not applicable so proceed with auto retries flow else { loop { // Use initial_gsm for first time alone let gsm = match initial_gsm.as_ref() { Some(gsm) => Some(gsm.clone()), None => get_gsm(state, &router_data).await?, }; match get_gsm_decision(gsm) { storage_enums::GsmDecision::Retry => { retries = get_retries( state, retries, merchant_context.get_merchant_account().get_id(), business_profile, ) .await; if retries.is_none() || retries == Some(0) { metrics::AUTO_RETRY_EXHAUSTED_COUNT.add(1, &[]); logger::info!("retries exhausted for auto_retry payment"); break; } if connector_routing_data.len() == 0 { logger::info!("connectors exhausted for auto_retry payment"); metrics::AUTO_RETRY_EXHAUSTED_COUNT.add(1, &[]); break; } let is_network_token = payment_data .get_payment_method_data() .map(|pmd| pmd.is_network_token_payment_method_data()) .unwrap_or(false); let clear_pan_possible = initial_gsm .and_then(|data| data.feature_data.get_retry_feature_data()) .map(|data| data.is_clear_pan_possible()) .unwrap_or(false); let should_retry_with_pan = is_network_token && clear_pan_possible && business_profile.is_clear_pan_retries_enabled; // Currently we are taking off_session as a source of truth to identify MIT payments. let is_mit_payment = payment_data .get_payment_intent() .off_session .unwrap_or(false); let (connector, routing_decision) = if is_mit_payment { let connector_routing_data = super::get_connector_data(&mut connector_routing_data)?; let payment_method_info = payment_data .get_payment_method_info() .get_required_value("payment_method_info")? .clone(); let mandate_reference_id = payments::get_mandate_reference_id( connector_routing_data.action_type.clone(), connector_routing_data.clone(), payment_data, &payment_method_info, )?; payment_data.set_mandate_id(api_models::payments::MandateIds { mandate_id: None, mandate_reference_id, //mandate_ref_id }); (connector_routing_data.connector_data, None) } else if should_retry_with_pan { // If should_retry_with_pan is true, it indicates that we are retrying with PAN using the same connector. (original_connector_data.clone(), None) } else { let connector_routing_data = super::get_connector_data(&mut connector_routing_data)?; let routing_decision = connector_routing_data.network.map(|card_network| { routing_helpers::RoutingDecisionData::get_debit_routing_decision_data( card_network, None, ) }); (connector_routing_data.connector_data, routing_decision) }; router_data = do_retry( &state.clone(), req_state.clone(), &connector, operation, customer, merchant_context, payment_data, router_data, validate_result, schedule_time, //this is an auto retry payment, but not step-up false, frm_suggestion, business_profile, should_retry_with_pan, routing_decision, ) .await?; retries = retries.map(|i| i - 1); } storage_enums::GsmDecision::DoDefault => break, } initial_gsm = None; } } Ok(router_data) } #[instrument(skip_all)] pub async fn is_step_up_enabled_for_merchant_connector( state: &app::SessionState, merchant_id: &common_utils::id_type::MerchantId, connector_name: types::Connector, ) -> bool { let key = merchant_id.get_step_up_enabled_key(); let db = &*state.store; db.find_config_by_key_unwrap_or(key.as_str(), Some("[]".to_string())) .await .change_context(errors::ApiErrorResponse::InternalServerError) .and_then(|step_up_config| { serde_json::from_str::<Vec<types::Connector>>(&step_up_config.config) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Step-up config parsing failed") }) .map_err(|err| { logger::error!(step_up_config_error=?err); }) .ok() .map(|connectors_enabled| connectors_enabled.contains(&connector_name)) .unwrap_or(false) } #[cfg(feature = "v1")] pub async fn get_merchant_max_auto_retries_enabled( db: &dyn StorageInterface, merchant_id: &common_utils::id_type::MerchantId, ) -> Option<i32> { let key = merchant_id.get_max_auto_retries_enabled(); db.find_config_by_key(key.as_str()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .and_then(|retries_config| { retries_config .config .parse::<i32>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Retries config parsing failed") }) .map_err(|err| { logger::error!(retries_error=?err); None::<i32> }) .ok() } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn get_retries( state: &app::SessionState, retries: Option<i32>, merchant_id: &common_utils::id_type::MerchantId, profile: &domain::Profile, ) -> Option<i32> { match retries { Some(retries) => Some(retries), None => get_merchant_max_auto_retries_enabled(state.store.as_ref(), merchant_id) .await .or(profile.max_auto_retries_enabled.map(i32::from)), } } #[instrument(skip_all)] pub async fn get_gsm<F, FData>( state: &app::SessionState, router_data: &types::RouterData<F, FData, types::PaymentsResponseData>, ) -> RouterResult<Option<hyperswitch_domain_models::gsm::GatewayStatusMap>> { let error_response = router_data.response.as_ref().err(); let error_code = error_response.map(|err| err.code.to_owned()); let error_message = error_response.map(|err| err.message.to_owned()); let connector_name = router_data.connector.to_string(); let flow = get_flow_name::<F>()?; Ok( payments::helpers::get_gsm_record(state, error_code, error_message, connector_name, flow) .await, ) } #[instrument(skip_all)] pub fn get_gsm_decision( option_gsm: Option<hyperswitch_domain_models::gsm::GatewayStatusMap>, ) -> storage_enums::GsmDecision { let option_gsm_decision = option_gsm .as_ref() .map(|gsm| gsm.feature_data.get_decision()); if option_gsm_decision.is_some() { metrics::AUTO_RETRY_GSM_MATCH_COUNT.add(1, &[]); } option_gsm_decision.unwrap_or_default() } #[inline] 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()) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn do_retry<'a, F, ApiRequest, FData, D>( state: &'a routes::SessionState, req_state: ReqState, connector: &'a api::ConnectorData, operation: &'a operations::BoxedOperation<'a, F, ApiRequest, D>, customer: &'a Option<domain::Customer>, merchant_context: &domain::MerchantContext, payment_data: &'a mut D, router_data: types::RouterData<F, FData, types::PaymentsResponseData>, validate_result: &operations::ValidateResult, schedule_time: Option<time::PrimitiveDateTime>, is_step_up: bool, frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &domain::Profile, should_retry_with_pan: bool, routing_decision: Option<routing_helpers::RoutingDecisionData>, ) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>> where F: Clone + Send + Sync + 'static, FData: Send + Sync + types::Capturable + Clone + 'static + serde::Serialize, payments::PaymentResponse: operations::Operation<F, FData>, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, FData, types::PaymentsResponseData>, types::RouterData<F, FData, types::PaymentsResponseData>: Feature<F, FData>, dyn api::Connector: services::api::ConnectorIntegration<F, FData, types::PaymentsResponseData>, { metrics::AUTO_RETRY_PAYMENT_COUNT.add(1, &[]); modify_trackers( state, connector.connector_name.to_string(), payment_data, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, router_data, is_step_up, ) .await?; let (merchant_connector_account, router_data, tokenization_action) = payments::call_connector_service_prerequisites( state, merchant_context, connector.clone(), operation, payment_data, customer, validate_result, business_profile, should_retry_with_pan, routing_decision, ) .await?; let (router_data, _mca) = payments::decide_unified_connector_service_call( state, req_state, merchant_context, connector.clone(), operation, payment_data, customer, payments::CallConnectorAction::Trigger, validate_result, schedule_time, hyperswitch_domain_models::payments::HeaderPayload::default(), frm_suggestion, business_profile, true, None, merchant_connector_account, router_data, tokenization_action, ) .await?; Ok(router_data) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn modify_trackers<F, FData, D>( state: &routes::SessionState, connector: String, payment_data: &mut D, key_store: &domain::MerchantKeyStore, storage_scheme: storage_enums::MerchantStorageScheme, router_data: types::RouterData<F, FData, types::PaymentsResponseData>, is_step_up: bool, ) -> RouterResult<()> where F: Clone + Send, FData: Send, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync, { todo!() } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn modify_trackers<F, FData, D>( state: &routes::SessionState, connector: String, payment_data: &mut D, key_store: &domain::MerchantKeyStore, storage_scheme: storage_enums::MerchantStorageScheme, router_data: types::RouterData<F, FData, types::PaymentsResponseData>, is_step_up: bool, ) -> RouterResult<()> where F: Clone + Send, FData: Send + types::Capturable, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync, { let new_attempt_count = payment_data.get_payment_intent().attempt_count + 1; let new_payment_attempt = make_new_payment_attempt( connector, payment_data.get_payment_attempt().clone(), new_attempt_count, is_step_up, payment_data.get_payment_intent().setup_future_usage, ); let db = &*state.store; let key_manager_state = &state.into(); let additional_payment_method_data = payments::helpers::update_additional_payment_data_with_connector_response_pm_data( payment_data .get_payment_attempt() .payment_method_data .clone(), router_data .connector_response .clone() .and_then(|connector_response| connector_response.additional_payment_method_data), )?; let debit_routing_savings = payment_data.get_payment_method_data().and_then(|data| { payments::helpers::get_debit_routing_savings_amount( data, payment_data.get_payment_attempt(), ) }); match router_data.response { Ok(types::PaymentsResponseData::TransactionResponse { resource_id, connector_metadata, redirection_data, charges, .. }) => { let encoded_data = payment_data.get_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 payment_attempt_update = storage::PaymentAttemptUpdate::ResponseUpdate { status: router_data.status, connector: None, connector_transaction_id: match resource_id { types::ResponseId::NoResponseId => None, types::ResponseId::ConnectorTransactionId(id) | types::ResponseId::EncodedData(id) => Some(id), }, connector_response_reference_id: payment_data .get_payment_attempt() .connector_response_reference_id .clone(), authentication_type: None, payment_method_id: payment_data.get_payment_attempt().payment_method_id.clone(), mandate_id: payment_data .get_mandate_id() .and_then(|mandate| mandate.mandate_id.clone()), connector_metadata, payment_token: None, error_code: None, error_message: None, error_reason: None, amount_capturable: if router_data.status.is_terminal_status() { Some(MinorUnit::new(0)) } else { None }, updated_by: storage_scheme.to_string(), authentication_data, encoded_data, unified_code: None, unified_message: None, capture_before: None, extended_authorization_applied: None, payment_method_data: additional_payment_method_data, connector_mandate_detail: None, charges, setup_future_usage_applied: None, debit_routing_savings, network_transaction_id: payment_data .get_payment_attempt() .network_transaction_id .clone(), is_overcapture_enabled: None, authorized_amount: router_data.authorized_amount, }; #[cfg(feature = "v1")] db.update_payment_attempt_with_attempt_id( payment_data.get_payment_attempt().clone(), payment_attempt_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; #[cfg(feature = "v2")] db.update_payment_attempt_with_attempt_id( key_manager_state, key_store, payment_data.get_payment_attempt().clone(), payment_attempt_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; } Ok(_) => { logger::error!("unexpected response: this response was not expected in Retry flow"); return Ok(()); } Err(ref error_response) => { let option_gsm = get_gsm(state, &router_data).await?; let auth_update = if Some(router_data.auth_type) != payment_data.get_payment_attempt().authentication_type { Some(router_data.auth_type) } else { None }; let payment_attempt_update = storage::PaymentAttemptUpdate::ErrorUpdate { connector: None, error_code: Some(Some(error_response.code.clone())), error_message: Some(Some(error_response.message.clone())), status: storage_enums::AttemptStatus::Failure, error_reason: Some(error_response.reason.clone()), amount_capturable: Some(MinorUnit::new(0)), updated_by: storage_scheme.to_string(), unified_code: option_gsm.clone().map(|gsm| gsm.unified_code), unified_message: option_gsm.map(|gsm| gsm.unified_message), connector_transaction_id: error_response.connector_transaction_id.clone(), payment_method_data: additional_payment_method_data, authentication_type: auth_update, issuer_error_code: error_response.network_decline_code.clone(), issuer_error_message: error_response.network_error_message.clone(), network_details: Some(ForeignFrom::foreign_from(error_response)), }; #[cfg(feature = "v1")] db.update_payment_attempt_with_attempt_id( payment_data.get_payment_attempt().clone(), payment_attempt_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; #[cfg(feature = "v2")] db.update_payment_attempt_with_attempt_id( key_manager_state, key_store, payment_data.get_payment_attempt().clone(), payment_attempt_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; } } #[cfg(feature = "v1")] let payment_attempt = db .insert_payment_attempt(new_payment_attempt, storage_scheme) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error inserting payment attempt")?; #[cfg(feature = "v2")] let payment_attempt = db .insert_payment_attempt( key_manager_state, key_store, new_payment_attempt, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error inserting payment attempt")?; // update payment_attempt, connector_response and payment_intent in payment_data payment_data.set_payment_attempt(payment_attempt); let payment_intent = db .update_payment_intent( key_manager_state, payment_data.get_payment_intent().clone(), storage::PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate { active_attempt_id: payment_data.get_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)?; payment_data.set_payment_intent(payment_intent); Ok(()) } #[cfg(feature = "v1")] #[instrument(skip_all)] pub fn make_new_payment_attempt( connector: String, old_payment_attempt: storage::PaymentAttempt, new_attempt_count: i16, is_step_up: bool, setup_future_usage_intent: Option<storage_enums::FutureUsage>, ) -> storage::PaymentAttemptNew { let created_at @ modified_at @ last_synced = Some(common_utils::date_time::now()); storage::PaymentAttemptNew { connector: Some(connector), 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, status: old_payment_attempt.status, currency: old_payment_attempt.currency, save_to_locker: old_payment_attempt.save_to_locker, offer_amount: old_payment_attempt.offer_amount, payment_method_id: old_payment_attempt.payment_method_id, payment_method: old_payment_attempt.payment_method, payment_method_type: old_payment_attempt.payment_method_type, capture_method: old_payment_attempt.capture_method, capture_on: old_payment_attempt.capture_on, confirm: old_payment_attempt.confirm, authentication_type: if is_step_up { Some(storage_enums::AuthenticationType::ThreeDs) } else { old_payment_attempt.authentication_type }, amount_to_capture: old_payment_attempt.amount_to_capture, mandate_id: old_payment_attempt.mandate_id, browser_info: old_payment_attempt.browser_info, payment_token: old_payment_attempt.payment_token, client_source: old_payment_attempt.client_source, client_version: old_payment_attempt.client_version, created_at, modified_at, last_synced, profile_id: old_payment_attempt.profile_id, organization_id: old_payment_attempt.organization_id, net_amount: old_payment_attempt.net_amount, error_message: Default::default(), cancellation_reason: Default::default(), error_code: Default::default(), connector_metadata: Default::default(), payment_experience: Default::default(), payment_method_data: Default::default(), business_sub_label: Default::default(), straight_through_algorithm: Default::default(), preprocessing_step_id: Default::default(), mandate_details: Default::default(), error_reason: Default::default(), connector_response_reference_id: Default::default(), multiple_capture_count: Default::default(), amount_capturable: Default::default(), updated_by: Default::default(), authentication_data: Default::default(), encoded_data: Default::default(), merchant_connector_id: Default::default(), unified_code: Default::default(), unified_message: Default::default(), external_three_ds_authentication_attempted: Default::default(), authentication_connector: Default::default(), authentication_id: Default::default(), mandate_data: Default::default(), payment_method_billing_address_id: Default::default(), fingerprint_id: Default::default(), customer_acceptance: Default::default(), connector_mandate_detail: Default::default(), request_extended_authorization: Default::default(), extended_authorization_applied: Default::default(), capture_before: Default::default(), card_discovery: old_payment_attempt.card_discovery, processor_merchant_id: old_payment_attempt.processor_merchant_id, created_by: old_payment_attempt.created_by, setup_future_usage_applied: setup_future_usage_intent, // setup future usage is picked from intent for new payment attempt routing_approach: old_payment_attempt.routing_approach, connector_request_reference_id: Default::default(), network_transaction_id: old_payment_attempt.network_transaction_id, network_details: Default::default(), is_stored_credential: old_payment_attempt.is_stored_credential, authorized_amount: old_payment_attempt.authorized_amount, } } #[cfg(feature = "v2")] #[instrument(skip_all)] pub fn make_new_payment_attempt( _connector: String, _old_payment_attempt: storage::PaymentAttempt, _new_attempt_count: i16, _is_step_up: bool, ) -> storage::PaymentAttempt { todo!() } pub async fn get_merchant_config_for_gsm( db: &dyn StorageInterface, merchant_id: &common_utils::id_type::MerchantId, ) -> bool { let config = db .find_config_by_key_unwrap_or( &merchant_id.get_should_call_gsm_key(), Some("false".to_string()), ) .await; match config { Ok(conf) => conf.config == "true", Err(error) => { logger::error!(?error); false } } } #[cfg(feature = "v1")] pub async fn config_should_call_gsm( db: &dyn StorageInterface, merchant_id: &common_utils::id_type::MerchantId, profile: &domain::Profile, ) -> bool { let merchant_config_gsm = get_merchant_config_for_gsm(db, merchant_id).await; let profile_config_gsm = profile.is_auto_retries_enabled; merchant_config_gsm || profile_config_gsm } pub trait GsmValidation<F: Send + Clone + Sync, FData: Send + Sync, Resp> { // TODO : move this function to appropriate place later. fn should_call_gsm(&self) -> bool; } impl<F: Send + Clone + Sync, FData: Send + Sync> GsmValidation<F, FData, types::PaymentsResponseData> for types::RouterData<F, FData, types::PaymentsResponseData> { #[inline(always)] fn should_call_gsm(&self) -> bool { if self.response.is_err() { true } else { match self.status { storage_enums::AttemptStatus::Started | storage_enums::AttemptStatus::AuthenticationPending | storage_enums::AttemptStatus::AuthenticationSuccessful | storage_enums::AttemptStatus::Authorized | storage_enums::AttemptStatus::Charged | storage_enums::AttemptStatus::Authorizing | storage_enums::AttemptStatus::CodInitiated | storage_enums::AttemptStatus::Voided | storage_enums::AttemptStatus::VoidedPostCharge | storage_enums::AttemptStatus::VoidInitiated | storage_enums::AttemptStatus::CaptureInitiated | storage_enums::AttemptStatus::RouterDeclined | storage_enums::AttemptStatus::VoidFailed | storage_enums::AttemptStatus::AutoRefunded | storage_enums::AttemptStatus::CaptureFailed | storage_enums::AttemptStatus::PartialCharged | storage_enums::AttemptStatus::PartialChargedAndChargeable | storage_enums::AttemptStatus::Pending | storage_enums::AttemptStatus::PaymentMethodAwaited | storage_enums::AttemptStatus::ConfirmationAwaited | storage_enums::AttemptStatus::Unresolved | storage_enums::AttemptStatus::DeviceDataCollectionPending | storage_enums::AttemptStatus::IntegrityFailure | storage_enums::AttemptStatus::Expired | storage_enums::AttemptStatus::PartiallyAuthorized => false, storage_enums::AttemptStatus::AuthenticationFailed | storage_enums::AttemptStatus::AuthorizationFailed | storage_enums::AttemptStatus::Failure => true, } } } } </file>
{ "crate": "router", "file": "crates/router/src/core/payments/retry.rs", "files": null, "module": null, "num_files": null, "token_count": 6448 }
large_file_-9194876420252877497
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/payments/operations/payment_status.rs </path> <file> 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 } </file>
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_status.rs", "files": null, "module": null, "num_files": null, "token_count": 5002 }
large_file_-5819882756527770821
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/payments/operations/tax_calculation.rs </path> <file> 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, }, )) } } </file>
{ "crate": "router", "file": "crates/router/src/core/payments/operations/tax_calculation.rs", "files": null, "module": null, "num_files": null, "token_count": 3494 }
large_file_-7965878602057789942
clm
file
<path> Repository: hyperswitch Crate: router File: crates/router/src/core/payments/operations/payment_get.rs </path> <file> 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)) } } </file>
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_get.rs", "files": null, "module": null, "num_files": null, "token_count": 2957 }