text
stringlengths 65
57.3k
| file_path
stringlengths 22
92
| module
stringclasses 38
values | type
stringclasses 7
values | struct_name
stringlengths 3
60
⌀ | impl_count
int64 0
60
⌀ | traits
listlengths 0
59
⌀ | tokens
int64 16
8.19k
| function_name
stringlengths 3
85
⌀ | type_name
stringlengths 1
67
⌀ | trait_name
stringclasses 573
values | method_count
int64 0
31
⌀ | public_method_count
int64 0
19
⌀ | submodule_count
int64 0
56
⌀ | export_count
int64 0
9
⌀ |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
// Struct: PollConfig
// File: crates/router/src/types.rs
// Module: router
// Implementations: 2
// Traits: Default
pub struct PollConfig
|
crates/router/src/types.rs
|
router
|
struct_definition
|
PollConfig
| 2
|
[
"Default"
] | 36
| null | null | null | null | null | null | null |
// File: crates/router/src/services/email.rs
// Module: router
pub mod types;
|
crates/router/src/services/email.rs
|
router
|
full_file
| null | null | null | 19
| null | null | null | null | null | null | null |
// Implementation: impl std::ops::Deref for for Handler
// File: crates/drainer/src/handler.rs
// Module: drainer
// Methods: 1 total (0 public)
impl std::ops::Deref for for Handler
|
crates/drainer/src/handler.rs
|
drainer
|
impl_block
| null | null | null | 51
| null |
Handler
|
std::ops::Deref for
| 1
| 0
| null | null |
// Implementation: impl ConnectorCommon for for Trustpay
// File: crates/hyperswitch_connectors/src/connectors/trustpay.rs
// Module: hyperswitch_connectors
// Methods: 6 total (0 public)
impl ConnectorCommon for for Trustpay
|
crates/hyperswitch_connectors/src/connectors/trustpay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 54
| null |
Trustpay
|
ConnectorCommon for
| 6
| 0
| null | null |
// Struct: MerchantRiskIndicator
// File: crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct MerchantRiskIndicator
|
crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs
|
hyperswitch_connectors
|
struct_definition
|
MerchantRiskIndicator
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// File: crates/scheduler/src/flow.rs
// Module: scheduler
#[derive(Copy, Clone, Debug, strum::Display, strum::EnumString)]
#[strum(serialize_all = "snake_case")]
pub enum SchedulerFlow {
Producer,
Consumer,
Cleaner,
}
|
crates/scheduler/src/flow.rs
|
scheduler
|
full_file
| null | null | null | 62
| null | null | null | null | null | null | null |
// Function: insert_role_in_blacklist
// File: crates/router/src/services/authentication/blacklist.rs
// Module: router
pub fn insert_role_in_blacklist(state: &SessionState, role_id: &str) -> UserResult<()>
|
crates/router/src/services/authentication/blacklist.rs
|
router
|
function_signature
| null | null | null | 49
|
insert_role_in_blacklist
| null | null | null | null | null | null |
// Function: rust_locker_migration
// File: crates/router/src/routes/locker_migration.rs
// Module: router
pub fn rust_locker_migration(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse
|
crates/router/src/routes/locker_migration.rs
|
router
|
function_signature
| null | null | null | 65
|
rust_locker_migration
| null | null | null | null | null | null |
// Implementation: impl api::PaymentVoid for for Nexinets
// File: crates/hyperswitch_connectors/src/connectors/nexinets.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Nexinets
|
crates/hyperswitch_connectors/src/connectors/nexinets.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Nexinets
|
api::PaymentVoid for
| 0
| 0
| null | null |
// Struct: Purchase
// File: crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct Purchase
|
crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs
|
hyperswitch_connectors
|
struct_definition
|
Purchase
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_domain_models/src/router_flow_types/unified_authentication_service.rs
// Module: hyperswitch_domain_models
// Public structs: 4
#[derive(Debug, Clone)]
pub struct PreAuthenticate;
#[derive(Debug, Clone)]
pub struct PostAuthenticate;
#[derive(Debug, Clone)]
pub struct AuthenticationConfirmation;
#[derive(Debug, Clone)]
pub struct Authenticate;
|
crates/hyperswitch_domain_models/src/router_flow_types/unified_authentication_service.rs
|
hyperswitch_domain_models
|
full_file
| null | null | null | 78
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentPostSessionTokens for for Paypal
// File: crates/hyperswitch_connectors/src/connectors/paypal.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentPostSessionTokens for for Paypal
|
crates/hyperswitch_connectors/src/connectors/paypal.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Paypal
|
api::PaymentPostSessionTokens for
| 0
| 0
| null | null |
// Struct: JpmorganValidationErrors
// File: crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct JpmorganValidationErrors
|
crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
JpmorganValidationErrors
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Struct: SuccessfulSmartRetries
// File: crates/api_models/src/analytics/payment_intents.rs
// Module: api_models
// Implementations: 0
pub struct SuccessfulSmartRetries
|
crates/api_models/src/analytics/payment_intents.rs
|
api_models
|
struct_definition
|
SuccessfulSmartRetries
| 0
|
[] | 41
| null | null | null | null | null | null | null |
// File: crates/analytics/src/core.rs
// Module: analytics
// Public functions: 1
use api_models::analytics::GetInfoResponse;
use crate::{types::AnalyticsDomain, utils};
pub async fn get_domain_info(
domain: AnalyticsDomain,
) -> crate::errors::AnalyticsResult<GetInfoResponse> {
let info = match domain {
AnalyticsDomain::Payments => GetInfoResponse {
metrics: utils::get_payment_metrics_info(),
download_dimensions: None,
dimensions: utils::get_payment_dimensions(),
},
AnalyticsDomain::PaymentIntents => GetInfoResponse {
metrics: utils::get_payment_intent_metrics_info(),
download_dimensions: None,
dimensions: utils::get_payment_intent_dimensions(),
},
AnalyticsDomain::Refunds => GetInfoResponse {
metrics: utils::get_refund_metrics_info(),
download_dimensions: None,
dimensions: utils::get_refund_dimensions(),
},
AnalyticsDomain::Frm => GetInfoResponse {
metrics: utils::get_frm_metrics_info(),
download_dimensions: None,
dimensions: utils::get_frm_dimensions(),
},
AnalyticsDomain::SdkEvents => GetInfoResponse {
metrics: utils::get_sdk_event_metrics_info(),
download_dimensions: None,
dimensions: utils::get_sdk_event_dimensions(),
},
AnalyticsDomain::AuthEvents => GetInfoResponse {
metrics: utils::get_auth_event_metrics_info(),
download_dimensions: None,
dimensions: utils::get_auth_event_dimensions(),
},
AnalyticsDomain::ApiEvents => GetInfoResponse {
metrics: utils::get_api_event_metrics_info(),
download_dimensions: None,
dimensions: utils::get_api_event_dimensions(),
},
AnalyticsDomain::Dispute => GetInfoResponse {
metrics: utils::get_dispute_metrics_info(),
download_dimensions: None,
dimensions: utils::get_dispute_dimensions(),
},
AnalyticsDomain::Routing => GetInfoResponse {
metrics: utils::get_payment_metrics_info(),
download_dimensions: None,
dimensions: utils::get_payment_dimensions(),
},
};
Ok(info)
}
|
crates/analytics/src/core.rs
|
analytics
|
full_file
| null | null | null | 436
| null | null | null | null | null | null | null |
// Struct: FraudDetails
// File: crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct FraudDetails
|
crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
FraudDetails
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentSync for for Dlocal
// File: crates/hyperswitch_connectors/src/connectors/dlocal.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSync for for Dlocal
|
crates/hyperswitch_connectors/src/connectors/dlocal.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Dlocal
|
api::PaymentSync for
| 0
| 0
| null | null |
// Function: payments_manual_update
// File: crates/router/src/routes/payments.rs
// Module: router
pub fn payments_manual_update(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsManualUpdateRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder
|
crates/router/src/routes/payments.rs
|
router
|
function_signature
| null | null | null | 86
|
payments_manual_update
| null | null | null | null | null | null |
// Struct: WorldpayPaymentsResponse
// File: crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct WorldpayPaymentsResponse
|
crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
|
hyperswitch_connectors
|
struct_definition
|
WorldpayPaymentsResponse
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Implementation: impl api::RefundExecute for for Globalpay
// File: crates/hyperswitch_connectors/src/connectors/globalpay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundExecute for for Globalpay
|
crates/hyperswitch_connectors/src/connectors/globalpay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Globalpay
|
api::RefundExecute for
| 0
| 0
| null | null |
// Struct: SiftAuthType
// File: crates/hyperswitch_connectors/src/connectors/sift/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct SiftAuthType
|
crates/hyperswitch_connectors/src/connectors/sift/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
SiftAuthType
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Struct: PaymentsMetricsResponse
// File: crates/api_models/src/analytics.rs
// Module: api_models
// Implementations: 0
pub struct PaymentsMetricsResponse<T>
|
crates/api_models/src/analytics.rs
|
api_models
|
struct_definition
|
PaymentsMetricsResponse
| 0
|
[] | 38
| null | null | null | null | null | null | null |
// Function: set_stored_token_response
// File: crates/router/src/core/payment_methods/tokenize/card_executor.rs
// Module: router
pub fn set_stored_token_response(
self,
store_token_response: &'a StoreLockerResponse,
) -> NetworkTokenizationBuilder<'a, CardTokenStored>
|
crates/router/src/core/payment_methods/tokenize/card_executor.rs
|
router
|
function_signature
| null | null | null | 65
|
set_stored_token_response
| null | null | null | null | null | null |
// Implementation: impl ConnectorCommon for for Hyperwallet
// File: crates/hyperswitch_connectors/src/connectors/hyperwallet.rs
// Module: hyperswitch_connectors
// Methods: 6 total (0 public)
impl ConnectorCommon for for Hyperwallet
|
crates/hyperswitch_connectors/src/connectors/hyperwallet.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 54
| null |
Hyperwallet
|
ConnectorCommon for
| 6
| 0
| null | null |
// File: crates/hyperswitch_interfaces/src/api/payouts_v2.rs
// Module: hyperswitch_interfaces
//! Payouts V2 interface
use hyperswitch_domain_models::{
router_data_v2::flow_common_types::PayoutFlowData,
router_flow_types::payouts::{
PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount,
PoSync,
},
router_request_types::PayoutsData,
router_response_types::PayoutsResponseData,
};
use super::ConnectorCommon;
use crate::api::ConnectorIntegrationV2;
/// trait PayoutCancelV2
pub trait PayoutCancelV2:
ConnectorIntegrationV2<PoCancel, PayoutFlowData, PayoutsData, PayoutsResponseData>
{
}
/// trait PayoutCreateV2
pub trait PayoutCreateV2:
ConnectorIntegrationV2<PoCreate, PayoutFlowData, PayoutsData, PayoutsResponseData>
{
}
/// trait PayoutEligibilityV2
pub trait PayoutEligibilityV2:
ConnectorIntegrationV2<PoEligibility, PayoutFlowData, PayoutsData, PayoutsResponseData>
{
}
/// trait PayoutFulfillV2
pub trait PayoutFulfillV2:
ConnectorIntegrationV2<PoFulfill, PayoutFlowData, PayoutsData, PayoutsResponseData>
{
}
/// trait PayoutQuoteV2
pub trait PayoutQuoteV2:
ConnectorIntegrationV2<PoQuote, PayoutFlowData, PayoutsData, PayoutsResponseData>
{
}
/// trait PayoutRecipientV2
pub trait PayoutRecipientV2:
ConnectorIntegrationV2<PoRecipient, PayoutFlowData, PayoutsData, PayoutsResponseData>
{
}
/// trait PayoutRecipientAccountV2
pub trait PayoutRecipientAccountV2:
ConnectorIntegrationV2<PoRecipientAccount, PayoutFlowData, PayoutsData, PayoutsResponseData>
{
}
/// trait PayoutSyncV2
pub trait PayoutSyncV2:
ConnectorIntegrationV2<PoSync, PayoutFlowData, PayoutsData, PayoutsResponseData>
{
}
#[cfg(feature = "payouts")]
/// trait Payouts
pub trait PayoutsV2:
ConnectorCommon
+ PayoutCancelV2
+ PayoutCreateV2
+ PayoutEligibilityV2
+ PayoutFulfillV2
+ PayoutQuoteV2
+ PayoutRecipientV2
+ PayoutRecipientAccountV2
+ PayoutSyncV2
{
}
/// Empty trait for when payouts feature is disabled
#[cfg(not(feature = "payouts"))]
pub trait PayoutsV2 {}
|
crates/hyperswitch_interfaces/src/api/payouts_v2.rs
|
hyperswitch_interfaces
|
full_file
| null | null | null | 615
| null | null | null | null | null | null | null |
// File: crates/test_utils/tests/connectors/adyen_uk_ui.rs
// Module: test_utils
use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct AdyenSeleniumTest;
impl SeleniumTest for AdyenSeleniumTest {
fn get_connector_name(&self) -> String {
"adyen_uk".to_string()
}
}
async fn should_make_adyen_3ds_payment_failed(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/177"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Name("threeDSIframe"))),
Event::Assert(Assert::IsPresent("AUTHENTICATION DETAILS")),
Event::Trigger(Trigger::SendKeys(By::ClassName("input-field"), "password")),
Event::Trigger(Trigger::Click(By::Id("buttonSubmit"))),
Event::Trigger(Trigger::Sleep(5)),
Event::Assert(Assert::IsPresent("failed")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_3ds_payment_success(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/62"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Name("threeDSIframe"))),
Event::Assert(Assert::IsPresent("AUTHENTICATION DETAILS")),
Event::Trigger(Trigger::SendKeys(By::ClassName("input-field"), "password")),
Event::Trigger(Trigger::Click(By::Id("buttonSubmit"))),
Event::Trigger(Trigger::Sleep(5)),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_3ds_mandate_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/203"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")), // mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("a.btn"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_3ds_mandate_with_zero_dollar_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/204"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")), // mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("a.btn"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_gpay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_gpay_payment(web_driver,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=70.00&country=US¤cy=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_adyen_gpay_mandate_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_gpay_payment(web_driver,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=70.00&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=7000&mandate_data[mandate_type][multi_use][currency]=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_adyen_gpay_zero_dollar_mandate_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_gpay_payment(web_driver,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=0.00&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_adyen_klarna_mandate_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/195"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Id("klarna-apf-iframe"))),
Event::Trigger(Trigger::Sleep(5)),
Event::Trigger(Trigger::Click(By::Id("signInWithBankId"))),
Event::Assert(Assert::IsPresent("Klart att betala")),
Event::EitherOr(
Assert::IsPresent("Klart att betala"),
vec![Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='confirm-and-pay']",
)))],
vec![
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='SmoothCheckoutPopUp:skip']",
))),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='confirm-and-pay']",
))),
],
),
Event::RunIf(
Assert::IsPresent("Färre klick, snabbare betalning"),
vec![Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='SmoothCheckoutPopUp:enable']",
)))],
),
Event::Trigger(Trigger::SwitchTab(Position::Prev)),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")), // mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_alipay_hk_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/162"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::EitherOr(
Assert::IsPresent("Payment Method Not Available"),
vec![Event::Assert(Assert::IsPresent(
"Please try again or select a different payment method",
))],
vec![
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_bizum_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/186"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(By::Id("iPhBizInit"), "700000000")),
Event::Trigger(Trigger::Click(By::Id("bBizInit"))),
Event::Trigger(Trigger::Click(By::Css("input.btn.btn-lg.btn-continue"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_clearpay_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_clearpay_payment(
driver,
&format!("{CHECKOUT_BASE_URL}/saved/163"),
vec![Event::Assert(Assert::IsPresent("succeeded"))],
)
.await?;
Ok(())
}
async fn should_make_adyen_paypal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_paypal_payment(
web_driver,
&format!("{CHECKOUT_BASE_URL}/saved/202"),
vec![
Event::Trigger(Trigger::Click(By::Id("payment-submit-btn"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=processing"], //final status of this payment method will remain in processing state
)),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_ach_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/58"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_sepa_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/51"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_bacs_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/54"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Status")),
Event::Assert(Assert::IsPresent("processing")), //final status of this payment method will remain in processing state
],
)
.await?;
Ok(())
}
async fn should_make_adyen_ideal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/52"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::ClassName("btnLink"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_eps_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/61"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_bancontact_card_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
let user = &conn
.get_configs()
.automation_configs
.unwrap()
.adyen_bancontact_username
.unwrap();
let pass = &conn
.get_configs()
.automation_configs
.unwrap()
.adyen_bancontact_pass
.unwrap();
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/68"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(By::Id("username"), user)),
Event::Trigger(Trigger::SendKeys(By::Id("password"), pass)),
Event::Trigger(Trigger::Click(By::ClassName("button"))),
Event::Trigger(Trigger::Sleep(2)),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_wechatpay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/75"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_mbway_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/196"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Status")),
Event::Assert(Assert::IsPresent("processing")), //final status of this payment method will remain in processing state
],
)
.await?;
Ok(())
}
async fn should_make_adyen_ebanking_fi_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/78"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::ClassName("css-ns0tbt"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_onlinebanking_pl_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/197"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("user_account_pbl_correct"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
#[ignore]
async fn should_make_adyen_giropay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/70"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(
By::Css("input[id='tags']"),
"Testbank Fiducia 44448888 GENODETT488",
)),
Event::Trigger(Trigger::Click(By::Css("input[id='tags']"))),
Event::Trigger(Trigger::Sleep(3)),
Event::Trigger(Trigger::Click(By::Id("ui-id-3"))),
Event::Trigger(Trigger::Click(By::ClassName("blueButton"))),
Event::Trigger(Trigger::SendKeys(By::Name("sc"), "10")),
Event::Trigger(Trigger::SendKeys(By::Name("extensionSc"), "4000")),
Event::Trigger(Trigger::SendKeys(By::Name("customerName1"), "Hopper")),
Event::Trigger(Trigger::SendKeys(
By::Name("customerIBAN"),
"DE36444488881234567890",
)),
Event::Trigger(Trigger::Click(By::Css("input[value='Absenden']"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=processing"], //final status of this payment method will remain in processing state
)),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_twint_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/170"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_walley_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/198"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Teknikmössor AB")),
Event::Trigger(Trigger::SwitchFrame(By::ClassName(
"collector-checkout-iframe",
))),
Event::Trigger(Trigger::Click(By::Id("purchase"))),
Event::Trigger(Trigger::Sleep(10)),
Event::Trigger(Trigger::SwitchFrame(By::Css(
"iframe[title='Walley Modal - idp-choices']",
))),
Event::Assert(Assert::IsPresent("Identifisering")),
Event::Trigger(Trigger::Click(By::Id("optionLoggInnMedBankId"))),
Event::Trigger(Trigger::SwitchFrame(By::Css("iframe[title='BankID']"))),
Event::Assert(Assert::IsPresent("Engangskode")),
Event::Trigger(Trigger::SendKeys(By::Css("input[type='password']"), "otp")),
Event::Trigger(Trigger::Sleep(4)),
Event::Trigger(Trigger::Click(By::Css("button[title='Neste']"))),
Event::Assert(Assert::IsPresent("Ditt BankID-passord")),
Event::Trigger(Trigger::Sleep(4)),
Event::Trigger(Trigger::SendKeys(
By::Css("input[type='password']"),
"qwer1234",
)),
Event::Trigger(Trigger::Click(By::Css("button[title='Neste']"))),
Event::Trigger(Trigger::SwitchTab(Position::Prev)),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_dana_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/175"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(
By::Css("input[type='number']"),
"12345678901",
)), // Mobile Number can be any random 11 digit number
Event::Trigger(Trigger::Click(By::Css("button"))),
Event::Trigger(Trigger::SendKeys(By::Css("input[type='number']"), "111111")), // PIN can be any random 11 digit number
Event::Trigger(Trigger::Click(By::ClassName("btn-next"))),
Event::Trigger(Trigger::Sleep(3)),
Event::Trigger(Trigger::Click(By::ClassName("btn-next"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_online_banking_fpx_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/172"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_online_banking_thailand_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/184"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_touch_n_go_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/185"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_swish_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/210"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("status")),
Event::Assert(Assert::IsPresent("processing")),
Event::Assert(Assert::IsPresent("Next Action Type")),
Event::Assert(Assert::IsPresent("qr_code_information")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_blik_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/64"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Next Action Type")),
Event::Assert(Assert::IsPresent("wait_screen_information")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_momo_atm_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/238"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(5)), // Delay for provider to not reject payment for botting
Event::Trigger(Trigger::SendKeys(
By::Id("card-number"),
"9704 0000 0000 0018",
)),
Event::Trigger(Trigger::SendKeys(By::Id("card-expire"), "03/07")),
Event::Trigger(Trigger::SendKeys(By::Id("card-name"), "NGUYEN VAN A")),
Event::Trigger(Trigger::SendKeys(By::Id("number-phone"), "987656666")),
Event::Trigger(Trigger::Click(By::Id("btn-pay-card"))),
Event::Trigger(Trigger::SendKeys(By::Id("napasOtpCode"), "otp")),
Event::Trigger(Trigger::Click(By::Id("napasProcessBtn1"))),
Event::Trigger(Trigger::Sleep(5)), // Delay to get to status page
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_adyen_gpay_payment_test() {
tester!(should_make_adyen_gpay_payment);
}
#[test]
#[serial]
fn should_make_adyen_gpay_mandate_payment_test() {
tester!(should_make_adyen_gpay_mandate_payment);
}
#[test]
#[serial]
fn should_make_adyen_gpay_zero_dollar_mandate_payment_test() {
tester!(should_make_adyen_gpay_zero_dollar_mandate_payment);
}
#[test]
#[serial]
fn should_make_adyen_klarna_mandate_payment_test() {
tester!(should_make_adyen_klarna_mandate_payment);
}
#[test]
#[serial]
fn should_make_adyen_3ds_payment_failed_test() {
tester!(should_make_adyen_3ds_payment_failed);
}
#[test]
#[serial]
fn should_make_adyen_3ds_mandate_payment_test() {
tester!(should_make_adyen_3ds_mandate_payment);
}
#[test]
#[serial]
fn should_make_adyen_3ds_mandate_with_zero_dollar_payment_test() {
tester!(should_make_adyen_3ds_mandate_with_zero_dollar_payment);
}
#[test]
#[serial]
fn should_make_adyen_3ds_payment_success_test() {
tester!(should_make_adyen_3ds_payment_success);
}
#[test]
#[serial]
fn should_make_adyen_alipay_hk_payment_test() {
tester!(should_make_adyen_alipay_hk_payment);
}
#[test]
#[serial]
fn should_make_adyen_swish_payment_test() {
tester!(should_make_adyen_swish_payment);
}
#[test]
#[serial]
#[ignore = "Failing from connector side"]
fn should_make_adyen_bizum_payment_test() {
tester!(should_make_adyen_bizum_payment);
}
#[test]
#[serial]
fn should_make_adyen_clearpay_payment_test() {
tester!(should_make_adyen_clearpay_payment);
}
#[test]
#[serial]
fn should_make_adyen_twint_payment_test() {
tester!(should_make_adyen_twint_payment);
}
#[test]
#[serial]
fn should_make_adyen_paypal_payment_test() {
tester!(should_make_adyen_paypal_payment);
}
#[test]
#[serial]
fn should_make_adyen_ach_payment_test() {
tester!(should_make_adyen_ach_payment);
}
#[test]
#[serial]
fn should_make_adyen_sepa_payment_test() {
tester!(should_make_adyen_sepa_payment);
}
#[test]
#[serial]
fn should_make_adyen_bacs_payment_test() {
tester!(should_make_adyen_bacs_payment);
}
#[test]
#[serial]
fn should_make_adyen_ideal_payment_test() {
tester!(should_make_adyen_ideal_payment);
}
#[test]
#[serial]
fn should_make_adyen_eps_payment_test() {
tester!(should_make_adyen_eps_payment);
}
#[test]
#[serial]
fn should_make_adyen_bancontact_card_payment_test() {
tester!(should_make_adyen_bancontact_card_payment);
}
#[test]
#[serial]
fn should_make_adyen_wechatpay_payment_test() {
tester!(should_make_adyen_wechatpay_payment);
}
#[test]
#[serial]
fn should_make_adyen_mbway_payment_test() {
tester!(should_make_adyen_mbway_payment);
}
#[test]
#[serial]
fn should_make_adyen_ebanking_fi_payment_test() {
tester!(should_make_adyen_ebanking_fi_payment);
}
#[test]
#[serial]
fn should_make_adyen_onlinebanking_pl_payment_test() {
tester!(should_make_adyen_onlinebanking_pl_payment);
}
#[ignore]
#[test]
#[serial]
fn should_make_adyen_giropay_payment_test() {
tester!(should_make_adyen_giropay_payment);
}
#[ignore]
#[test]
#[serial]
fn should_make_adyen_walley_payment_test() {
tester!(should_make_adyen_walley_payment);
}
#[test]
#[serial]
fn should_make_adyen_dana_payment_test() {
tester!(should_make_adyen_dana_payment);
}
#[test]
#[serial]
fn should_make_adyen_blik_payment_test() {
tester!(should_make_adyen_blik_payment);
}
#[test]
#[serial]
fn should_make_adyen_online_banking_fpx_payment_test() {
tester!(should_make_adyen_online_banking_fpx_payment);
}
#[test]
#[serial]
fn should_make_adyen_online_banking_thailand_payment_test() {
tester!(should_make_adyen_online_banking_thailand_payment);
}
#[test]
#[serial]
fn should_make_adyen_touch_n_go_payment_test() {
tester!(should_make_adyen_touch_n_go_payment);
}
#[ignore]
#[test]
#[serial]
fn should_make_adyen_momo_atm_payment_test() {
tester!(should_make_adyen_momo_atm_payment);
}
|
crates/test_utils/tests/connectors/adyen_uk_ui.rs
|
test_utils
|
full_file
| null | null | null | 7,611
| null | null | null | null | null | null | null |
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status = map_cybersource_attempt_status(
item.response
.status
.clone()
.unwrap_or(CybersourcePaymentStatus::StatusNotReceived),
item.data.request.is_auto_capture()?,
);
let response =
get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err);
let connector_response = item
.response
.processor_information
.as_ref()
.map(AdditionalPaymentMethodConnectorResponse::from)
.map(ConnectorResponseData::with_additional_payment_method_data);
Ok(Self {
status,
response,
connector_response,
..item.data
})
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
CybersourceAuthSetupResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
CybersourceAuthSetupResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
CybersourceAuthSetupResponse::ClientAuthSetupInfo(info_response) => Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(RedirectForm::CybersourceAuthSetup {
access_token: info_response
.consumer_authentication_information
.access_token,
ddc_url: info_response
.consumer_authentication_information
.device_data_collection_url,
reference_id: info_response
.consumer_authentication_information
.reference_id,
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
info_response
.client_reference_information
.code
.unwrap_or(info_response.id.clone()),
),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
CybersourceAuthSetupResponse::ErrorInformation(error_response) => {
let detailed_error_info =
error_response
.error_information
.details
.to_owned()
.map(|details| {
details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message,
detailed_error_info,
None,
);
let error_message = error_response.error_information.reason;
Ok(Self {
response: Err(ErrorResponse {
code: error_message
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_message.unwrap_or(
hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string(),
),
reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
status: enums::AttemptStatus::AuthenticationFailed,
..item.data
})
}
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceConsumerAuthInformationRequest {
return_url: String,
reference_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceAuthEnrollmentRequest {
payment_information: PaymentInformation,
client_reference_information: ClientReferenceInformation,
consumer_authentication_information: CybersourceConsumerAuthInformationRequest,
order_information: OrderInformationWithBill,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct CybersourceRedirectionAuthResponse {
pub transaction_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceConsumerAuthInformationValidateRequest {
authentication_transaction_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceAuthValidateRequest {
payment_information: PaymentInformation,
client_reference_information: ClientReferenceInformation,
consumer_authentication_information: CybersourceConsumerAuthInformationValidateRequest,
order_information: OrderInformation,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum CybersourcePreProcessingRequest {
AuthEnrollment(Box<CybersourceAuthEnrollmentRequest>),
AuthValidate(Box<CybersourceAuthValidateRequest>),
}
impl TryFrom<&CybersourceRouterData<&PaymentsPreProcessingRouterData>>
for CybersourcePreProcessingRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CybersourceRouterData<&PaymentsPreProcessingRouterData>,
) -> Result<Self, Self::Error> {
let client_reference_information = ClientReferenceInformation {
code: Some(item.router_data.connector_request_reference_id.clone()),
};
let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "payment_method_data",
},
)?;
let payment_information = match payment_method_data {
PaymentMethodData::Card(ccard) => {
let card_type = match ccard
.card_network
.clone()
.and_then(get_cybersource_card_type)
{
Some(card_network) => Some(card_network.to_string()),
None => ccard.get_card_issuer().ok().map(String::from),
};
Ok(PaymentInformation::Cards(Box::new(
CardPaymentInformation {
card: Card {
number: ccard.card_number,
expiration_month: ccard.card_exp_month,
expiration_year: ccard.card_exp_year,
security_code: Some(ccard.card_cvc),
card_type,
type_selection_indicator: Some("1".to_owned()),
},
},
)))
}
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
))
}
}?;
let redirect_response = item.router_data.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
let amount_details = Amount {
total_amount: item.amount.clone(),
currency: item.router_data.request.currency.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "currency",
},
)?,
};
match redirect_response.params {
Some(param) if !param.clone().peek().is_empty() => {
let reference_id = param
.clone()
.peek()
.split_once('=')
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.params.reference_id",
})?
.1
.to_string();
let email = item
.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?;
let order_information = OrderInformationWithBill {
amount_details,
bill_to: Some(bill_to),
};
Ok(Self::AuthEnrollment(Box::new(
CybersourceAuthEnrollmentRequest {
payment_information,
client_reference_information,
consumer_authentication_information:
CybersourceConsumerAuthInformationRequest {
return_url: item
.router_data
.request
.get_complete_authorize_url()?,
reference_id,
},
order_information,
},
)))
}
Some(_) | None => {
let redirect_payload: CybersourceRedirectionAuthResponse = redirect_response
.payload
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
})?
.peek()
.clone()
.parse_value("CybersourceRedirectionAuthResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let order_information = OrderInformation { amount_details };
Ok(Self::AuthValidate(Box::new(
CybersourceAuthValidateRequest {
payment_information,
client_reference_information,
consumer_authentication_information:
CybersourceConsumerAuthInformationValidateRequest {
authentication_transaction_id: redirect_payload.transaction_id,
},
order_information,
},
)))
}
}
}
}
impl TryFrom<&CybersourceRouterData<&PaymentsAuthenticateRouterData>>
for CybersourceAuthEnrollmentRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CybersourceRouterData<&PaymentsAuthenticateRouterData>,
) -> Result<Self, Self::Error> {
let client_reference_information = ClientReferenceInformation {
code: Some(item.router_data.connector_request_reference_id.clone()),
};
let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "payment_method_data",
},
)?;
let payment_information = match payment_method_data {
PaymentMethodData::Card(ccard) => {
let card_type = match ccard
.card_network
.clone()
.and_then(get_cybersource_card_type)
{
Some(card_network) => Some(card_network.to_string()),
None => ccard.get_card_issuer().ok().map(String::from),
};
Ok(PaymentInformation::Cards(Box::new(
CardPaymentInformation {
card: Card {
number: ccard.card_number,
expiration_month: ccard.card_exp_month,
expiration_year: ccard.card_exp_year,
security_code: Some(ccard.card_cvc),
card_type,
type_selection_indicator: Some("1".to_owned()),
},
},
)))
}
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
))
}
}?;
let redirect_response = item.router_data.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
let amount_details = Amount {
total_amount: item.amount.clone(),
currency: item.router_data.request.currency.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "currency",
},
)?,
};
let param = redirect_response.params.ok_or(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.params",
},
)?;
let reference_id = param
.clone()
.peek()
.split('=')
.next_back()
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.params.reference_id",
})?
.to_string();
let email = item.router_data.get_billing_email().or(item
.router_data
.request
.email
.clone()
.ok_or_else(utils::missing_field_err("email")))?;
let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?;
let order_information = OrderInformationWithBill {
amount_details,
bill_to: Some(bill_to),
};
Ok(Self {
payment_information,
client_reference_information,
consumer_authentication_information: CybersourceConsumerAuthInformationRequest {
return_url: item
.router_data
.request
.complete_authorize_url
.clone()
.ok_or_else(utils::missing_field_err("complete_authorize_url"))?,
reference_id,
},
order_information,
})
}
}
impl TryFrom<&CybersourceRouterData<&PaymentsPostAuthenticateRouterData>>
for CybersourceAuthValidateRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CybersourceRouterData<&PaymentsPostAuthenticateRouterData>,
) -> Result<Self, Self::Error> {
let client_reference_information = ClientReferenceInformation {
code: Some(item.router_data.connector_request_reference_id.clone()),
};
let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "payment_method_data",
},
)?;
let payment_information = match payment_method_data {
PaymentMethodData::Card(ccard) => {
let card_type = match ccard
.card_network
.clone()
.and_then(get_cybersource_card_type)
{
Some(card_network) => Some(card_network.to_string()),
None => ccard.get_card_issuer().ok().map(String::from),
};
Ok(PaymentInformation::Cards(Box::new(
CardPaymentInformation {
card: Card {
number: ccard.card_number,
expiration_month: ccard.card_exp_month,
expiration_year: ccard.card_exp_year,
security_code: Some(ccard.card_cvc),
card_type,
type_selection_indicator: Some("1".to_owned()),
},
},
)))
}
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
))
}
}?;
let redirect_response = item.router_data.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
let amount_details = Amount {
total_amount: item.amount.clone(),
currency: item.router_data.request.currency.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "currency",
},
)?,
};
let redirect_payload: CybersourceRedirectionAuthResponse = redirect_response
.payload
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
})?
.peek()
.clone()
.parse_value("CybersourceRedirectionAuthResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let order_information = OrderInformation { amount_details };
Ok(Self {
payment_information,
client_reference_information,
consumer_authentication_information:
CybersourceConsumerAuthInformationValidateRequest {
authentication_transaction_id: redirect_payload.transaction_id,
},
order_information,
})
}
}
impl TryFrom<&CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>>
for CybersourcePaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "payment_method_data",
},
)?;
match payment_method_data {
PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)),
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
)
.into())
}
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CybersourceAuthEnrollmentStatus {
PendingAuthentication,
AuthenticationSuccessful,
AuthenticationFailed,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceConsumerAuthValidateResponse {
ucaf_collection_indicator: Option<String>,
cavv: Option<Secret<String>>,
ucaf_authentication_data: Option<Secret<String>>,
xid: Option<String>,
specification_version: Option<SemanticVersion>,
directory_server_transaction_id: Option<Secret<String>>,
indicator: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CybersourceThreeDSMetadata {
three_ds_data: CybersourceConsumerAuthValidateResponse,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceConsumerAuthInformationEnrollmentResponse {
access_token: Option<Secret<String>>,
step_up_url: Option<String>,
//Added to segregate the three_ds_data in a separate struct
#[serde(flatten)]
validate_response: CybersourceConsumerAuthValidateResponse,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientAuthCheckInfoResponse {
id: String,
client_reference_information: ClientReferenceInformation,
consumer_authentication_information: CybersourceConsumerAuthInformationEnrollmentResponse,
status: CybersourceAuthEnrollmentStatus,
error_information: Option<CybersourceErrorInformation>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CybersourcePreProcessingResponse {
ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>),
ErrorInformation(Box<CybersourceErrorInformationResponse>),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CybersourceAuthenticateResponse {
ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>),
ErrorInformation(Box<CybersourceErrorInformationResponse>),
}
impl From<CybersourceAuthEnrollmentStatus> for enums::AttemptStatus {
fn from(item: CybersourceAuthEnrollmentStatus) -> Self {
match item {
CybersourceAuthEnrollmentStatus::PendingAuthentication => Self::AuthenticationPending,
CybersourceAuthEnrollmentStatus::AuthenticationSuccessful => {
Self::AuthenticationSuccessful
}
CybersourceAuthEnrollmentStatus::AuthenticationFailed => Self::AuthenticationFailed,
}
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
CybersourcePreProcessingResponse,
PaymentsPreProcessingData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
CybersourcePreProcessingResponse,
PaymentsPreProcessingData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
CybersourcePreProcessingResponse::ClientAuthCheckInfo(info_response) => {
let status = enums::AttemptStatus::from(info_response.status);
let risk_info: Option<ClientRiskInformation> = None;
if utils::is_payment_failure(status) {
let response = Err(get_error_response(
&info_response.error_information,
&None,
&risk_info,
Some(status),
item.http_code,
info_response.id.clone(),
));
Ok(Self {
status,
response,
..item.data
})
} else {
let connector_response_reference_id = Some(
info_response
.client_reference_information
.code
.unwrap_or(info_response.id.clone()),
);
let redirection_data = match (
info_response
.consumer_authentication_information
.access_token,
info_response
.consumer_authentication_information
.step_up_url,
) {
(Some(token), Some(step_up_url)) => {
Some(RedirectForm::CybersourceConsumerAuth {
access_token: token.expose(),
step_up_url,
})
}
_ => None,
};
let three_ds_data = serde_json::to_value(
info_response
.consumer_authentication_information
.validate_response,
)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!({
"three_ds_data": three_ds_data
})),
network_txn_id: None,
connector_response_reference_id,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
CybersourcePreProcessingResponse::ErrorInformation(error_response) => {
let detailed_error_info =
error_response
.error_information
.details
.to_owned()
.map(|details| {
details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message,
detailed_error_info,
None,
);
let error_message = error_response.error_information.reason.to_owned();
let response = Err(ErrorResponse {
code: error_message
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
Ok(Self {
response,
status: enums::AttemptStatus::AuthenticationFailed,
..item.data
})
}
}
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
CybersourcePaymentsResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<F, CompleteAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
CybersourcePaymentsResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status = map_cybersource_attempt_status(
item.response
.status
.clone()
.unwrap_or(CybersourcePaymentStatus::StatusNotReceived),
item.data.request.is_auto_capture()?,
);
let response =
get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err);
let connector_response = item
.response
.processor_information
.as_ref()
.map(AdditionalPaymentMethodConnectorResponse::from)
.map(ConnectorResponseData::with_additional_payment_method_data);
Ok(Self {
status,
response,
connector_response,
..item.data
})
}
}
impl From<&ClientProcessorInformation> for AdditionalPaymentMethodConnectorResponse {
fn from(processor_information: &ClientProcessorInformation) -> Self {
let payment_checks = Some(
serde_json::json!({"avs_response": processor_information.avs, "card_verification": processor_information.card_verification}),
);
Self::Card {
authentication_data: None,
payment_checks,
card_network: None,
domestic_network: None,
}
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
CybersourcePaymentsResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
CybersourcePaymentsResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status = map_cybersource_attempt_status(
item.response
.status
.clone()
.unwrap_or(CybersourcePaymentStatus::StatusNotReceived),
true,
);
let response =
get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err);
Ok(Self {
status,
response,
..item.data
})
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
CybersourcePaymentsResponse,
PaymentsCancelData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsCancelData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
CybersourcePaymentsResponse,
PaymentsCancelData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status = map_cybersource_attempt_status(
item.response
.status
.clone()
.unwrap_or(CybersourcePaymentStatus::StatusNotReceived),
false,
);
let response =
get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err);
Ok(Self {
status,
response,
..item.data
})
}
}
// zero dollar response
impl
TryFrom<
ResponseRouterData<
SetupMandate,
CybersourcePaymentsResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
> for RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
SetupMandate,
CybersourcePaymentsResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let mandate_reference =
item.response
.token_information
.clone()
.map(|token_info| MandateReference {
connector_mandate_id: token_info
.payment_instrument
.map(|payment_instrument| payment_instrument.id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
let mut mandate_status = map_cybersource_attempt_status(
item.response
.status
.clone()
.unwrap_or(CybersourcePaymentStatus::StatusNotReceived),
false,
);
if matches!(mandate_status, enums::AttemptStatus::Authorized) {
//In case of zero auth mandates we want to make the payment reach the terminal status so we are converting the authorized status to charged as well.
mandate_status = enums::AttemptStatus::Charged
}
let error_response =
get_error_response_if_failure((&item.response, mandate_status, item.http_code));
let connector_response = item
.response
.processor_information
.as_ref()
.map(AdditionalPaymentMethodConnectorResponse::from)
.map(ConnectorResponseData::with_additional_payment_method_data);
Ok(Self {
status: mandate_status,
response: match error_response {
Some(error) => Err(error),
None => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: item.response.processor_information.as_ref().and_then(
|processor_information| {
processor_information.network_transaction_id.clone()
},
),
connector_response_reference_id: Some(
item.response
.client_reference_information
.and_then(|client_reference_information| {
client_reference_information.code.clone()
})
.unwrap_or(item.response.id),
),
incremental_authorization_allowed: Some(
mandate_status == enums::AttemptStatus::Authorized,
),
charges: None,
}),
},
connector_response,
..item.data
})
}
}
impl<F, T>
TryFrom<
ResponseRouterData<
F,
CybersourcePaymentsIncrementalAuthorizationResponse,
T,
PaymentsResponseData,
>,
> for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
CybersourcePaymentsIncrementalAuthorizationResponse,
T,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: match item.response.error_information {
Some(error) => Ok(PaymentsResponseData::IncrementalAuthorizationResponse {
status: common_enums::AuthorizationStatus::Failure,
error_code: error.reason,
error_message: error.message,
connector_authorization_id: None,
}),
None => Ok(PaymentsResponseData::IncrementalAuthorizationResponse {
status: item.response.status.into(),
error_code: None,
error_message: None,
connector_authorization_id: None,
}),
},
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceTransactionResponse {
id: String,
application_information: ApplicationInformation,
processor_information: Option<ClientProcessorInformation>,
client_reference_information: Option<ClientReferenceInformation>,
error_information: Option<CybersourceErrorInformation>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplicationInformation {
status: Option<CybersourcePaymentStatus>,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
CybersourceAuthSetupResponse,
PaymentsPreAuthenticateData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsPreAuthenticateData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
CybersourceAuthSetupResponse,
PaymentsPreAuthenticateData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
CybersourceAuthSetupResponse::ClientAuthSetupInfo(info_response) => Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(RedirectForm::CybersourceAuthSetup {
access_token: info_response
.consumer_authentication_information
.access_token,
ddc_url: info_response
.consumer_authentication_information
.device_data_collection_url,
reference_id: info_response
.consumer_authentication_information
.reference_id,
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
info_response
.client_reference_information
.code
.unwrap_or(info_response.id.clone()),
),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
CybersourceAuthSetupResponse::ErrorInformation(error_response) => {
let detailed_error_info =
error_response
.error_information
.details
.to_owned()
.map(|details| {
details
.iter()
.map(|details| format!("{} : {}", details.field, details.reason))
.collect::<Vec<_>>()
.join(", ")
});
let reason = get_error_reason(
error_response.error_information.message,
detailed_error_info,
None,
);
let error_message = error_response.error_information.reason;
Ok(Self {
response: Err(ErrorResponse {
code: error_message
.clone()
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: error_message.unwrap_or(
hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string(),
),
reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(error_response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
status: enums::AttemptStatus::AuthenticationFailed,
..item.data
})
}
}
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
CybersourceAuthenticateResponse,
PaymentsAuthenticateData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsAuthenticateData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
CybersourceAuthenticateResponse,
PaymentsAuthenticateData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
CybersourceAuthenticateResponse::ClientAuthCheckInfo(info_response) => {
let status = enums::AttemptStatus::from(info_response.status);
let risk_info: Option<ClientRiskInformation> = None;
if utils::is_payment_failure(status) {
let response = Err(get_error_response(
&info_response.error_information,
&None,
&risk_info,
Some(status),
item.http_code,
info_response.id.clone(),
));
Ok(Self {
status,
response,
..item.data
})
} else {
let connector_response_reference_id = Some(
info_response
.client_reference_information
.code
.unwrap_or(info_response.id.clone()),
);
let redirection_data = match (
info_response
.consumer_authentication_information
.access_token,
info_response
.consumer_authentication_information
.step_up_url,
) {
(Some(token), Some(step_up_url)) => {
Some(RedirectForm::CybersourceConsumerAuth {
access_token: token.expose(),
step_up_url,
})
}
_ => None,
};
let three_ds_data = serde_json::to_value(
info_response
.consumer_authentication_information
.validate_response,
)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!({
|
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs#chunk3
|
hyperswitch_connectors
|
chunk
| null | null | null | 8,187
| null | null | null | null | null | null | null |
// Trait: ErrorSwitchFrom
// File: crates/common_utils/src/errors.rs
// Module: common_utils
// Documentation: Allow [error_stack::Report] to convert between error types This serves as an alternative to [ErrorSwitch]
pub trait ErrorSwitchFrom<T>
|
crates/common_utils/src/errors.rs
|
common_utils
|
trait_definition
| null | null | null | 55
| null | null |
ErrorSwitchFrom
| null | null | null | null |
// Implementation: impl ActivePaymentsMetricsAccumulator
// File: crates/analytics/src/active_payments/accumulator.rs
// Module: analytics
// Methods: 1 total (1 public)
impl ActivePaymentsMetricsAccumulator
|
crates/analytics/src/active_payments/accumulator.rs
|
analytics
|
impl_block
| null | null | null | 47
| null |
ActivePaymentsMetricsAccumulator
| null | 1
| 1
| null | null |
// Implementation: impl api::RefundSync for for Inespay
// File: crates/hyperswitch_connectors/src/connectors/inespay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundSync for for Inespay
|
crates/hyperswitch_connectors/src/connectors/inespay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 62
| null |
Inespay
|
api::RefundSync for
| 0
| 0
| null | null |
// Function: build_payment_data
// File: crates/router/src/routes/dummy_connector/types.rs
// Module: router
pub fn build_payment_data(
self,
status: DummyConnectorStatus,
next_action: Option<DummyConnectorNextAction>,
return_url: Option<String>,
) -> DummyConnectorPaymentData
|
crates/router/src/routes/dummy_connector/types.rs
|
router
|
function_signature
| null | null | null | 66
|
build_payment_data
| null | null | null | null | null | null |
// Module Structure
// File: crates/hyperswitch_connectors/src/connectors/placetopay.rs
// Module: hyperswitch_connectors
// Public submodules:
pub mod transformers;
|
crates/hyperswitch_connectors/src/connectors/placetopay.rs
|
hyperswitch_connectors
|
module_structure
| null | null | null | 40
| null | null | null | null | null | 1
| 0
|
// Struct: ConfigMetadata
// File: crates/connector_configs/src/connector.rs
// Module: connector_configs
// Implementations: 0
pub struct ConfigMetadata
|
crates/connector_configs/src/connector.rs
|
connector_configs
|
struct_definition
|
ConfigMetadata
| 0
|
[] | 35
| null | null | null | null | null | null | null |
// Implementation: impl api::RefundSync for for Noon
// File: crates/hyperswitch_connectors/src/connectors/noon.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundSync for for Noon
|
crates/hyperswitch_connectors/src/connectors/noon.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Noon
|
api::RefundSync for
| 0
| 0
| null | null |
// Struct: PaymentListFilters
// File: crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct PaymentListFilters
|
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
|
hyperswitch_domain_models
|
struct_definition
|
PaymentListFilters
| 0
|
[] | 44
| null | null | null | null | null | null | null |
// Implementation: impl api::RefundSync for for Volt
// File: crates/hyperswitch_connectors/src/connectors/volt.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundSync for for Volt
|
crates/hyperswitch_connectors/src/connectors/volt.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Volt
|
api::RefundSync for
| 0
| 0
| null | null |
// Function: payment_method_session_delete_saved_payment_method
// File: crates/openapi/src/routes/payment_method.rs
// Module: openapi
pub fn payment_method_session_delete_saved_payment_method()
|
crates/openapi/src/routes/payment_method.rs
|
openapi
|
function_signature
| null | null | null | 39
|
payment_method_session_delete_saved_payment_method
| null | null | null | null | null | null |
// Struct: FeatureMatrix
// File: crates/router/src/routes/app.rs
// Module: router
// Implementations: 1
pub struct FeatureMatrix
|
crates/router/src/routes/app.rs
|
router
|
struct_definition
|
FeatureMatrix
| 1
|
[] | 32
| null | null | null | null | null | null | null |
// Struct: KlarnaRefundResponse
// File: crates/hyperswitch_connectors/src/connectors/klarna/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct KlarnaRefundResponse
|
crates/hyperswitch_connectors/src/connectors/klarna/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
KlarnaRefundResponse
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Implementation: impl AccountReferenceMap
// File: crates/hyperswitch_domain_models/src/merchant_connector_account.rs
// Module: hyperswitch_domain_models
// Methods: 2 total (1 public)
impl AccountReferenceMap
|
crates/hyperswitch_domain_models/src/merchant_connector_account.rs
|
hyperswitch_domain_models
|
impl_block
| null | null | null | 47
| null |
AccountReferenceMap
| null | 2
| 1
| null | null |
// File: crates/hyperswitch_connectors/src/connectors/jpmorgan.rs
// Module: hyperswitch_connectors
// Public functions: 1
// Public structs: 1
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts, errors,
events::connector_api_logs::ConnectorEvent,
types::{self, RefreshTokenType, Response},
webhooks,
};
use masking::{Mask, Maskable, PeekInterface};
use transformers::{self as jpmorgan, JpmorganErrorResponse};
use crate::{
constants::headers,
types::{RefreshTokenRouterData, ResponseRouterData},
utils,
};
#[derive(Clone)]
pub struct Jpmorgan {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Jpmorgan {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Jpmorgan {}
impl api::PaymentSession for Jpmorgan {}
impl api::ConnectorAccessToken for Jpmorgan {}
impl api::MandateSetup for Jpmorgan {}
impl api::PaymentAuthorize for Jpmorgan {}
impl api::PaymentSync for Jpmorgan {}
impl api::PaymentCapture for Jpmorgan {}
impl api::PaymentVoid for Jpmorgan {}
impl api::Refund for Jpmorgan {}
impl api::RefundExecute for Jpmorgan {}
impl api::RefundSync for Jpmorgan {}
impl api::PaymentToken for Jpmorgan {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Jpmorgan
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Jpmorgan
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut headers = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let auth_header = (
headers::AUTHORIZATION.to_string(),
format!(
"Bearer {}",
req.access_token
.clone()
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?
.token
.peek()
)
.into_masked(),
);
let request_id = (
headers::REQUEST_ID.to_string(),
req.connector_request_reference_id
.clone()
.to_string()
.into_masked(),
);
let merchant_id = (
headers::MERCHANT_ID.to_string(),
req.merchant_id.get_string_repr().to_string().into_masked(),
);
headers.push(auth_header);
headers.push(request_id);
headers.push(merchant_id);
Ok(headers)
}
}
impl ConnectorCommon for Jpmorgan {
fn id(&self) -> &'static str {
"jpmorgan"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.jpmorgan.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: JpmorganErrorResponse = res
.response
.parse_struct("JpmorganErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
router_env::logger::info!(connector_response=?response);
event_builder.map(|i| i.set_response_body(&response));
let response_message = response
.response_message
.as_ref()
.map_or_else(|| consts::NO_ERROR_MESSAGE.to_string(), ToString::to_string);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.response_code,
message: response_message.clone(),
reason: Some(response_message),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Jpmorgan {
fn validate_psync_reference_id(
&self,
data: &PaymentsSyncData,
_is_three_ds: bool,
_status: enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
if data.encoded_data.is_some()
|| data
.connector_transaction_id
.get_connector_transaction_id()
.is_ok()
{
return Ok(());
}
Err(errors::ConnectorError::MissingConnectorTransactionID.into())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Jpmorgan {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Jpmorgan {
fn get_headers(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let client_id = req.request.app_id.clone();
let client_secret = req.request.id.clone();
let creds = format!(
"{}:{}",
client_id.peek(),
client_secret.unwrap_or_default().peek()
);
let encoded_creds = common_utils::consts::BASE64_ENGINE.encode(creds);
let auth_string = format!("Basic {encoded_creds}");
Ok(vec![
(
headers::CONTENT_TYPE.to_string(),
RefreshTokenType::get_content_type(self).to_string().into(),
),
(
headers::AUTHORIZATION.to_string(),
auth_string.into_masked(),
),
])
}
fn get_content_type(&self) -> &'static str {
"application/x-www-form-urlencoded"
}
fn get_url(
&self,
_req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/am/oauth2/alpha/access_token",
connectors
.jpmorgan
.secondary_base_url
.as_ref()
.ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?
))
}
fn get_request_body(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = jpmorgan::JpmorganAuthUpdateRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.attach_default_headers()
.headers(RefreshTokenType::get_headers(self, req, connectors)?)
.url(&RefreshTokenType::get_url(self, req, connectors)?)
.set_body(RefreshTokenType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefreshTokenRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> {
let response: jpmorgan::JpmorganAuthUpdateResponse = res
.response
.parse_struct("jpmorgan JpmorganAuthUpdateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Jpmorgan
{
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for JPMorgan".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Jpmorgan {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/payments", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount: MinorUnit = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = jpmorgan::JpmorganRouterData::from((amount, req));
let connector_req = jpmorgan::JpmorganPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: jpmorgan::JpmorganPaymentsResponse = res
.response
.parse_struct("Jpmorgan PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Jpmorgan {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let tid = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/payments/{}/captures",
self.base_url(connectors),
tid
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount: MinorUnit = utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = jpmorgan::JpmorganRouterData::from((amount, req));
let connector_req = jpmorgan::JpmorganCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: jpmorgan::JpmorganPaymentsResponse = res
.response
.parse_struct("Jpmorgan PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Jpmorgan {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let tid = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!("{}/payments/{}", self.base_url(connectors), tid))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: jpmorgan::JpmorganPaymentsResponse = res
.response
.parse_struct("jpmorgan PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Jpmorgan {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let tid = req.request.connector_transaction_id.clone();
Ok(format!("{}/payments/{}", self.base_url(connectors), tid))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount: MinorUnit = utils::convert_amount(
self.amount_converter,
req.request.minor_amount.unwrap_or_default(),
req.request.currency.unwrap_or_default(),
)?;
let connector_router_data = jpmorgan::JpmorganRouterData::from((amount, req));
let connector_req = jpmorgan::JpmorganCancelRequest::try_from(connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Patch)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsVoidType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: jpmorgan::JpmorganCancelResponse = res
.response
.parse_struct("JpmrorganPaymentsVoidResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Jpmorgan {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/refunds", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = jpmorgan::JpmorganRouterData::from((refund_amount, req));
let connector_req = jpmorgan::JpmorganRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: jpmorgan::JpmorganRefundResponse = res
.response
.parse_struct("JpmorganRefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Jpmorgan {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let tid = req.request.connector_transaction_id.clone();
Ok(format!("{}/refunds/{}", self.base_url(connectors), tid))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: jpmorgan::JpmorganRefundSyncResponse = res
.response
.parse_struct("jpmorgan RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Jpmorgan {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static JPMORGAN_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
];
let supported_card_network = vec![
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Visa,
];
let mut jpmorgan_supported_payment_methods = SupportedPaymentMethods::new();
jpmorgan_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
jpmorgan_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
jpmorgan_supported_payment_methods
});
static JPMORGAN_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Jpmorgan",
description:
"J.P. Morgan is a global financial services firm and investment bank, offering banking, asset management, and payment processing solutions",
connector_type: enums::HyperswitchConnectorCategory::BankAcquirer,
integration_status: enums::ConnectorIntegrationStatus::Beta,
};
static JPMORGAN_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Jpmorgan {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&JPMORGAN_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*JPMORGAN_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&JPMORGAN_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates/hyperswitch_connectors/src/connectors/jpmorgan.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 6,737
| null | null | null | null | null | null | null |
// File: crates/router/src/db/events.rs
// Module: router
use std::collections::HashSet;
use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState};
use error_stack::{report, ResultExt};
use router_env::{instrument, tracing};
use super::{MockDb, Store};
use crate::{
connection,
core::errors::{self, CustomResult},
types::{
domain::{
self,
behaviour::{Conversion, ReverseConversion},
},
storage,
},
};
#[async_trait::async_trait]
pub trait EventInterface
where
domain::Event:
Conversion<DstType = storage::events::Event, NewDstType = storage::events::EventNew>,
{
async fn insert_event(
&self,
state: &KeyManagerState,
event: domain::Event,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError>;
async fn find_event_by_merchant_id_event_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError>;
async fn find_event_by_merchant_id_idempotent_event_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
idempotent_event_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError>;
async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
primary_object_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
#[allow(clippy::too_many_arguments)]
async fn list_initial_events_by_merchant_id_constraints(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
async fn list_events_by_merchant_id_initial_attempt_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
async fn list_initial_events_by_profile_id_primary_object_id(
&self,
state: &KeyManagerState,
profile_id: &common_utils::id_type::ProfileId,
primary_object_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
#[allow(clippy::too_many_arguments)]
async fn list_initial_events_by_profile_id_constraints(
&self,
state: &KeyManagerState,
profile_id: &common_utils::id_type::ProfileId,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
async fn update_event_by_merchant_id_event_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
event: domain::EventUpdate,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError>;
async fn count_initial_events_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: Option<common_utils::id_type::ProfileId>,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
) -> CustomResult<i64, errors::StorageError>;
}
#[async_trait::async_trait]
impl EventInterface for Store {
#[instrument(skip_all)]
async fn insert_event(
&self,
state: &KeyManagerState,
event: domain::Event,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
event
.construct_new()
.await
.change_context(errors::StorageError::EncryptionError)?
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
#[instrument(skip_all)]
async fn find_event_by_merchant_id_event_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Event::find_by_merchant_id_event_id(&conn, merchant_id, event_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
#[instrument(skip_all)]
async fn find_event_by_merchant_id_idempotent_event_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
idempotent_event_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Event::find_by_merchant_id_idempotent_event_id(
&conn,
merchant_id,
idempotent_event_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
#[instrument(skip_all)]
async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
primary_object_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Event::list_initial_attempts_by_merchant_id_primary_object_id(
&conn,
merchant_id,
primary_object_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|events| async {
let mut domain_events = Vec::with_capacity(events.len());
for event in events.into_iter() {
domain_events.push(
event
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
);
}
Ok(domain_events)
})
.await
}
#[instrument(skip_all)]
async fn list_initial_events_by_merchant_id_constraints(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Event::list_initial_attempts_by_merchant_id_constraints(
&conn,
merchant_id,
created_after,
created_before,
limit,
offset,
event_types,
is_delivered,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|events| async {
let mut domain_events = Vec::with_capacity(events.len());
for event in events.into_iter() {
domain_events.push(
event
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
);
}
Ok(domain_events)
})
.await
}
#[instrument(skip_all)]
async fn list_events_by_merchant_id_initial_attempt_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Event::list_by_merchant_id_initial_attempt_id(
&conn,
merchant_id,
initial_attempt_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|events| async {
let mut domain_events = Vec::with_capacity(events.len());
for event in events.into_iter() {
domain_events.push(
event
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
);
}
Ok(domain_events)
})
.await
}
#[instrument(skip_all)]
async fn list_initial_events_by_profile_id_primary_object_id(
&self,
state: &KeyManagerState,
profile_id: &common_utils::id_type::ProfileId,
primary_object_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Event::list_initial_attempts_by_profile_id_primary_object_id(
&conn,
profile_id,
primary_object_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|events| async {
let mut domain_events = Vec::with_capacity(events.len());
for event in events.into_iter() {
domain_events.push(
event
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
);
}
Ok(domain_events)
})
.await
}
#[instrument(skip_all)]
async fn list_initial_events_by_profile_id_constraints(
&self,
state: &KeyManagerState,
profile_id: &common_utils::id_type::ProfileId,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Event::list_initial_attempts_by_profile_id_constraints(
&conn,
profile_id,
created_after,
created_before,
limit,
offset,
event_types,
is_delivered,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|events| async {
let mut domain_events = Vec::with_capacity(events.len());
for event in events.into_iter() {
domain_events.push(
event
.convert(
state,
merchant_key_store.key.get_inner(),
common_utils::types::keymanager::Identifier::Merchant(
merchant_key_store.merchant_id.clone(),
),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
);
}
Ok(domain_events)
})
.await
}
#[instrument(skip_all)]
async fn update_event_by_merchant_id_event_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
event: domain::EventUpdate,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::Event::update_by_merchant_id_event_id(&conn, merchant_id, event_id, event.into())
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
async fn count_initial_events_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: Option<common_utils::id_type::ProfileId>,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
) -> CustomResult<i64, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Event::count_initial_attempts_by_constraints(
&conn,
merchant_id,
profile_id,
created_after,
created_before,
event_types,
is_delivered,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl EventInterface for MockDb {
async fn insert_event(
&self,
state: &KeyManagerState,
event: domain::Event,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
let mut locked_events = self.events.lock().await;
let stored_event = Conversion::convert(event)
.await
.change_context(errors::StorageError::EncryptionError)?;
locked_events.push(stored_event.clone());
stored_event
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
async fn find_event_by_merchant_id_event_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
let locked_events = self.events.lock().await;
locked_events
.iter()
.find(|event| {
event.merchant_id == Some(merchant_id.to_owned()) && event.event_id == event_id
})
.cloned()
.async_map(|event| async {
event
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
})
.await
.transpose()?
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No event available with merchant_id = {merchant_id:?} and event_id = {event_id}"
))
.into(),
)
}
async fn find_event_by_merchant_id_idempotent_event_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
idempotent_event_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
let locked_events = self.events.lock().await;
locked_events
.iter()
.find(|event| {
event.merchant_id == Some(merchant_id.to_owned()) && event.idempotent_event_id == Some(idempotent_event_id.to_string())
})
.cloned()
.async_map(|event| async {
event
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
})
.await
.transpose()?
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No event available with merchant_id = {merchant_id:?} and idempotent_event_id = {idempotent_event_id}"
))
.into(),
)
}
async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
primary_object_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let locked_events = self.events.lock().await;
let events = locked_events
.iter()
.filter(|event| {
event.merchant_id == Some(merchant_id.to_owned())
&& event.initial_attempt_id.as_ref() == Some(&event.event_id)
&& event.primary_object_id == primary_object_id
})
.cloned()
.collect::<Vec<_>>();
let mut domain_events = Vec::with_capacity(events.len());
for event in events {
let domain_event = event
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?;
domain_events.push(domain_event);
}
Ok(domain_events)
}
async fn list_initial_events_by_merchant_id_constraints(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let locked_events = self.events.lock().await;
let events_iter = locked_events.iter().filter(|event| {
let check = event.merchant_id == Some(merchant_id.to_owned())
&& event.initial_attempt_id.as_ref() == Some(&event.event_id)
&& (event.created_at >= created_after)
&& (event.created_at <= created_before)
&& (event_types.is_empty() || event_types.contains(&event.event_type))
&& (event.is_overall_delivery_successful == is_delivered);
check
});
let offset: usize = if let Some(offset) = offset {
if offset < 0 {
Err(errors::StorageError::MockDbError)?;
}
offset
.try_into()
.map_err(|_| errors::StorageError::MockDbError)?
} else {
0
};
let limit: usize = if let Some(limit) = limit {
if limit < 0 {
Err(errors::StorageError::MockDbError)?;
}
limit
.try_into()
.map_err(|_| errors::StorageError::MockDbError)?
} else {
usize::MAX
};
let events = events_iter
.skip(offset)
.take(limit)
.cloned()
.collect::<Vec<_>>();
let mut domain_events = Vec::with_capacity(events.len());
for event in events {
let domain_event = event
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?;
domain_events.push(domain_event);
}
Ok(domain_events)
}
async fn list_events_by_merchant_id_initial_attempt_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let locked_events = self.events.lock().await;
let events = locked_events
.iter()
.filter(|event| {
event.merchant_id == Some(merchant_id.to_owned())
&& event.initial_attempt_id == Some(initial_attempt_id.to_owned())
})
.cloned()
.collect::<Vec<_>>();
let mut domain_events = Vec::with_capacity(events.len());
for event in events {
let domain_event = event
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?;
domain_events.push(domain_event);
}
Ok(domain_events)
}
async fn list_initial_events_by_profile_id_primary_object_id(
&self,
state: &KeyManagerState,
profile_id: &common_utils::id_type::ProfileId,
primary_object_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let locked_events = self.events.lock().await;
let events = locked_events
.iter()
.filter(|event| {
event.business_profile_id == Some(profile_id.to_owned())
&& event.initial_attempt_id.as_ref() == Some(&event.event_id)
&& event.primary_object_id == primary_object_id
})
.cloned()
.collect::<Vec<_>>();
let mut domain_events = Vec::with_capacity(events.len());
for event in events {
let domain_event = event
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?;
domain_events.push(domain_event);
}
Ok(domain_events)
}
async fn list_initial_events_by_profile_id_constraints(
&self,
state: &KeyManagerState,
profile_id: &common_utils::id_type::ProfileId,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let locked_events = self.events.lock().await;
let events_iter = locked_events.iter().filter(|event| {
let check = event.business_profile_id == Some(profile_id.to_owned())
&& event.initial_attempt_id.as_ref() == Some(&event.event_id)
&& (event.created_at >= created_after)
&& (event.created_at <= created_before)
&& (event_types.is_empty() || event_types.contains(&event.event_type))
&& (event.is_overall_delivery_successful == is_delivered);
check
});
let offset: usize = if let Some(offset) = offset {
if offset < 0 {
Err(errors::StorageError::MockDbError)?;
}
offset
.try_into()
.map_err(|_| errors::StorageError::MockDbError)?
} else {
0
};
let limit: usize = if let Some(limit) = limit {
if limit < 0 {
Err(errors::StorageError::MockDbError)?;
}
limit
.try_into()
.map_err(|_| errors::StorageError::MockDbError)?
} else {
usize::MAX
};
let events = events_iter
.skip(offset)
.take(limit)
.cloned()
.collect::<Vec<_>>();
let mut domain_events = Vec::with_capacity(events.len());
for event in events {
let domain_event = event
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?;
domain_events.push(domain_event);
}
Ok(domain_events)
}
async fn update_event_by_merchant_id_event_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
event: domain::EventUpdate,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
let mut locked_events = self.events.lock().await;
let event_to_update = locked_events
.iter_mut()
.find(|event| {
event.merchant_id == Some(merchant_id.to_owned()) && event.event_id == event_id
})
.ok_or(errors::StorageError::MockDbError)?;
match event {
domain::EventUpdate::UpdateResponse {
is_webhook_notified,
response,
} => {
event_to_update.is_webhook_notified = is_webhook_notified;
event_to_update.response = response.map(Into::into);
}
domain::EventUpdate::OverallDeliveryStatusUpdate {
is_overall_delivery_successful,
} => {
event_to_update.is_overall_delivery_successful =
Some(is_overall_delivery_successful)
}
}
event_to_update
.clone()
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
async fn count_initial_events_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: Option<common_utils::id_type::ProfileId>,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
) -> CustomResult<i64, errors::StorageError> {
let locked_events = self.events.lock().await;
let iter_events = locked_events.iter().filter(|event| {
let check = event.initial_attempt_id.as_ref() == Some(&event.event_id)
&& (event.merchant_id == Some(merchant_id.to_owned()))
&& (event.business_profile_id == profile_id)
&& (event.created_at >= created_after)
&& (event.created_at <= created_before)
&& (event_types.is_empty() || event_types.contains(&event.event_type))
&& (event.is_overall_delivery_successful == is_delivered);
check
});
let events = iter_events.cloned().collect::<Vec<_>>();
i64::try_from(events.len())
.change_context(errors::StorageError::MockDbError)
.attach_printable("Failed to convert usize to i64")
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use api_models::webhooks as api_webhooks;
use common_enums::IntentStatus;
use common_utils::{
generate_organization_id_of_default_length, type_name,
types::{keymanager::Identifier, MinorUnit},
};
use diesel_models::{
business_profile::WebhookDetails,
enums::{self},
events::EventMetadata,
};
use futures::future::join_all;
use hyperswitch_domain_models::merchant_account::MerchantAccountSetter;
use time::macros::datetime;
use tokio::time::{timeout, Duration};
use crate::{
core::webhooks as webhooks_core,
db::{
events::EventInterface, merchant_key_store::MerchantKeyStoreInterface,
MasterKeyInterface, MockDb,
},
routes::{
self,
app::{settings::Settings, StorageImpl},
},
services,
types::{
api,
domain::{self, MerchantAccount},
},
};
#[allow(clippy::unwrap_used)]
#[tokio::test]
#[cfg(feature = "v1")]
async fn test_mockdb_event_interface() {
#[allow(clippy::expect_used)]
let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
.await
.expect("Failed to create Mock store");
let event_id = "test_event_id";
let (tx, _) = tokio::sync::oneshot::channel();
let app_state = Box::pin(routes::AppState::with_storage(
Settings::default(),
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 merchant_id =
common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("merchant_1"))
.unwrap();
let business_profile_id =
common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from("profile1")).unwrap();
let payment_id = "test_payment_id";
let key_manager_state = &state.into();
let master_key = mockdb.get_master_key();
mockdb
.insert_merchant_key_store(
key_manager_state,
domain::MerchantKeyStore {
merchant_id: merchant_id.clone(),
key: domain::types::crypto_operation(
key_manager_state,
type_name!(domain::MerchantKeyStore),
domain::types::CryptoOperation::Encrypt(
services::generate_aes256_key().unwrap().to_vec().into(),
),
Identifier::Merchant(merchant_id.to_owned()),
master_key,
)
.await
.and_then(|val| val.try_into_operation())
.unwrap(),
created_at: datetime!(2023-02-01 0:00),
},
&master_key.to_vec().into(),
)
.await
.unwrap();
let merchant_key_store = mockdb
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&master_key.to_vec().into(),
)
.await
.unwrap();
let event1 = mockdb
.insert_event(
key_manager_state,
domain::Event {
event_id: event_id.into(),
event_type: enums::EventType::PaymentSucceeded,
event_class: enums::EventClass::Payments,
is_webhook_notified: false,
primary_object_id: payment_id.into(),
primary_object_type: enums::EventObjectType::PaymentDetails,
created_at: common_utils::date_time::now(),
merchant_id: Some(merchant_id.to_owned()),
business_profile_id: Some(business_profile_id.to_owned()),
primary_object_created_at: Some(common_utils::date_time::now()),
idempotent_event_id: Some(event_id.into()),
initial_attempt_id: Some(event_id.into()),
request: None,
response: None,
delivery_attempt: Some(enums::WebhookDeliveryAttempt::InitialAttempt),
metadata: Some(EventMetadata::Payment {
payment_id: common_utils::id_type::PaymentId::try_from(
std::borrow::Cow::Borrowed(payment_id),
)
.unwrap(),
}),
is_overall_delivery_successful: Some(false),
},
&merchant_key_store,
)
.await
.unwrap();
assert_eq!(event1.event_id, event_id);
let updated_event = mockdb
.update_event_by_merchant_id_event_id(
key_manager_state,
&merchant_id,
event_id,
domain::EventUpdate::UpdateResponse {
is_webhook_notified: true,
response: None,
},
&merchant_key_store,
)
.await
.unwrap();
assert!(updated_event.is_webhook_notified);
assert_eq!(updated_event.primary_object_id, payment_id);
assert_eq!(updated_event.event_id, event_id);
}
#[allow(clippy::unwrap_used)]
#[tokio::test]
#[cfg(feature = "v2")]
async fn test_mockdb_event_interface() {
#[allow(clippy::expect_used)]
let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
.await
.expect("Failed to create Mock store");
let event_id = "test_event_id";
let (tx, _) = tokio::sync::oneshot::channel();
let app_state = Box::pin(routes::AppState::with_storage(
Settings::default(),
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 merchant_id =
common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("merchant_1"))
.unwrap();
let business_profile_id =
common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from("profile1")).unwrap();
let payment_id = "test_payment_id";
let key_manager_state = &state.into();
let master_key = mockdb.get_master_key();
mockdb
.insert_merchant_key_store(
key_manager_state,
domain::MerchantKeyStore {
merchant_id: merchant_id.clone(),
key: domain::types::crypto_operation(
key_manager_state,
type_name!(domain::MerchantKeyStore),
domain::types::CryptoOperation::Encrypt(
services::generate_aes256_key().unwrap().to_vec().into(),
),
Identifier::Merchant(merchant_id.to_owned()),
master_key,
)
.await
.and_then(|val| val.try_into_operation())
.unwrap(),
created_at: datetime!(2023-02-01 0:00),
},
&master_key.to_vec().into(),
)
.await
.unwrap();
let merchant_key_store = mockdb
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&master_key.to_vec().into(),
)
.await
.unwrap();
let event1 = mockdb
.insert_event(
key_manager_state,
domain::Event {
event_id: event_id.into(),
event_type: enums::EventType::PaymentSucceeded,
event_class: enums::EventClass::Payments,
is_webhook_notified: false,
primary_object_id: payment_id.into(),
primary_object_type: enums::EventObjectType::PaymentDetails,
created_at: common_utils::date_time::now(),
merchant_id: Some(merchant_id.to_owned()),
business_profile_id: Some(business_profile_id.to_owned()),
primary_object_created_at: Some(common_utils::date_time::now()),
idempotent_event_id: Some(event_id.into()),
initial_attempt_id: Some(event_id.into()),
request: None,
response: None,
delivery_attempt: Some(enums::WebhookDeliveryAttempt::InitialAttempt),
metadata: Some(EventMetadata::Payment {
payment_id: common_utils::id_type::GlobalPaymentId::try_from(
std::borrow::Cow::Borrowed(payment_id),
)
|
crates/router/src/db/events.rs#chunk0
|
router
|
chunk
| null | null | null | 8,189
| null | null | null | null | null | null | null |
// File: crates/router/tests/connectors/paytm.rs
// Module: router
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 PaytmTest;
impl ConnectorActions for PaytmTest {}
impl utils::Connector for PaytmTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Paytm;
utils::construct_connector_data_old(
Box::new(Paytm::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.paytm
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"paytm".to_string()
}
}
static CONNECTOR: PaytmTest = PaytmTest {};
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
|
crates/router/tests/connectors/paytm.rs
|
router
|
full_file
| null | null | null | 2,931
| null | null | null | null | null | null | null |
// File: crates/drainer/src/lib.rs
// Module: drainer
// Public functions: 2
mod connection;
pub mod errors;
mod handler;
mod health_check;
pub mod logger;
pub(crate) mod metrics;
mod query;
pub mod services;
pub mod settings;
mod stream;
mod types;
mod utils;
use std::{collections::HashMap, sync::Arc};
mod secrets_transformers;
use actix_web::dev::Server;
use common_utils::{id_type, signals::get_allowed_signals};
use diesel_models::kv;
use error_stack::ResultExt;
use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret;
use router_env::{
instrument,
tracing::{self, Instrument},
};
use tokio::sync::mpsc;
pub(crate) type Settings = settings::Settings<RawSecret>;
use crate::{
connection::pg_connection, services::Store, settings::DrainerSettings, types::StreamData,
};
pub async fn start_drainer(
stores: HashMap<id_type::TenantId, Arc<Store>>,
conf: DrainerSettings,
) -> errors::DrainerResult<()> {
let drainer_handler = handler::Handler::from_conf(conf, stores);
let (tx, rx) = mpsc::channel::<()>(1);
let signal = get_allowed_signals().change_context(errors::DrainerError::SignalError(
"Failed while getting allowed signals".to_string(),
))?;
let handle = signal.handle();
let task_handle =
tokio::spawn(common_utils::signals::signal_handler(signal, tx.clone()).in_current_span());
let handler_clone = drainer_handler.clone();
tokio::task::spawn(async move { handler_clone.shutdown_listener(rx).await });
drainer_handler.spawn_error_handlers(tx)?;
drainer_handler.spawn().await?;
handle.close();
let _ = task_handle
.await
.map_err(|err| logger::error!("Failed while joining signal handler: {:?}", err));
Ok(())
}
pub async fn start_web_server(
conf: Settings,
stores: HashMap<id_type::TenantId, Arc<Store>>,
) -> Result<Server, errors::DrainerError> {
let server = conf.server.clone();
let web_server = actix_web::HttpServer::new(move || {
actix_web::App::new().service(health_check::Health::server(conf.clone(), stores.clone()))
})
.bind((server.host.as_str(), server.port))?
.run();
let _ = web_server.handle();
Ok(web_server)
}
|
crates/drainer/src/lib.rs
|
drainer
|
full_file
| null | null | null | 536
| null | null | null | null | null | null | null |
// Implementation: impl api::MandateSetup for for Deutschebank
// File: crates/hyperswitch_connectors/src/connectors/deutschebank.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::MandateSetup for for Deutschebank
|
crates/hyperswitch_connectors/src/connectors/deutschebank.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 62
| null |
Deutschebank
|
api::MandateSetup for
| 0
| 0
| null | null |
// Implementation: impl api::PaymentSync for for Tesouro
// File: crates/hyperswitch_connectors/src/connectors/tesouro.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSync for for Tesouro
|
crates/hyperswitch_connectors/src/connectors/tesouro.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Tesouro
|
api::PaymentSync for
| 0
| 0
| null | null |
// Implementation: impl Responder
// File: crates/router/src/routes/payments.rs
// Module: router
// Methods: 0 total (0 public)
impl Responder
|
crates/router/src/routes/payments.rs
|
router
|
impl_block
| null | null | null | 36
| null |
Responder
| null | 0
| 0
| null | null |
// Function: list_customer_payment_method_api
// File: crates/router/src/compatibility/stripe/customers.rs
// Module: router
pub fn list_customer_payment_method_api(
state: web::Data<routes::AppState>,
req: HttpRequest,
path: web::Path<id_type::CustomerId>,
json_payload: web::Query<payment_methods::PaymentMethodListRequest>,
) -> HttpResponse
|
crates/router/src/compatibility/stripe/customers.rs
|
router
|
function_signature
| null | null | null | 84
|
list_customer_payment_method_api
| null | null | null | null | null | null |
// Implementation: impl api::Payment for for Santander
// File: crates/hyperswitch_connectors/src/connectors/santander.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::Payment for for Santander
|
crates/hyperswitch_connectors/src/connectors/santander.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 56
| null |
Santander
|
api::Payment for
| 0
| 0
| null | null |
// Struct: GsmRetrieveRequest
// File: crates/api_models/src/gsm.rs
// Module: api_models
// Implementations: 0
pub struct GsmRetrieveRequest
|
crates/api_models/src/gsm.rs
|
api_models
|
struct_definition
|
GsmRetrieveRequest
| 0
|
[] | 38
| null | null | null | null | null | null | null |
// Struct: ConnectorVolumeSplitV0
// File: crates/router/src/types/api/routing.rs
// Module: router
// Implementations: 0
pub struct ConnectorVolumeSplitV0
|
crates/router/src/types/api/routing.rs
|
router
|
struct_definition
|
ConnectorVolumeSplitV0
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Struct: SwitchMerchantRequest
// File: crates/api_models/src/user.rs
// Module: api_models
// Implementations: 0
pub struct SwitchMerchantRequest
|
crates/api_models/src/user.rs
|
api_models
|
struct_definition
|
SwitchMerchantRequest
| 0
|
[] | 35
| null | null | null | null | null | null | null |
// Struct: CountAccumulator
// File: crates/analytics/src/payment_intents/accumulator.rs
// Module: analytics
// Implementations: 1
// Traits: PaymentIntentMetricAccumulator
pub struct CountAccumulator
|
crates/analytics/src/payment_intents/accumulator.rs
|
analytics
|
struct_definition
|
CountAccumulator
| 1
|
[
"PaymentIntentMetricAccumulator"
] | 50
| null | null | null | null | null | null | null |
// Struct: WisePayoutResponse
// File: crates/hyperswitch_connectors/src/connectors/wise/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct WisePayoutResponse
|
crates/hyperswitch_connectors/src/connectors/wise/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
WisePayoutResponse
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentCapture for for Worldpayvantiv
// File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentCapture for for Worldpayvantiv
|
crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 63
| null |
Worldpayvantiv
|
api::PaymentCapture for
| 0
| 0
| null | null |
// Function: find_last_successful_or_partially_captured_attempt_by_payment_id
// File: crates/diesel_models/src/query/payment_attempt.rs
// Module: diesel_models
pub fn find_last_successful_or_partially_captured_attempt_by_payment_id(
conn: &PgPooledConn,
payment_id: &common_utils::id_type::GlobalPaymentId,
) -> StorageResult<Self>
|
crates/diesel_models/src/query/payment_attempt.rs
|
diesel_models
|
function_signature
| null | null | null | 81
|
find_last_successful_or_partially_captured_attempt_by_payment_id
| null | null | null | null | null | null |
// Function: new
// File: crates/hyperswitch_connectors/src/connectors/tsys.rs
// Module: hyperswitch_connectors
pub fn new() -> &'static Self
|
crates/hyperswitch_connectors/src/connectors/tsys.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 38
|
new
| null | null | null | null | null | null |
// Struct: BHNGiftCardDetails
// File: crates/hyperswitch_domain_models/src/payment_method_data.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct BHNGiftCardDetails
|
crates/hyperswitch_domain_models/src/payment_method_data.rs
|
hyperswitch_domain_models
|
struct_definition
|
BHNGiftCardDetails
| 0
|
[] | 47
| null | null | null | null | null | null | null |
expiry_date,
} => Self::Pix(Box::new(
api_models::payments::additional_info::PixBankTransferAdditionalData {
pix_key: pix_key.map(MaskedBankAccount::from),
cpf: cpf.map(MaskedBankAccount::from),
cnpj: cnpj.map(MaskedBankAccount::from),
source_bank_account_id,
destination_bank_account_id,
expiry_date,
},
)),
BankTransferData::Pse {} => Self::Pse {},
BankTransferData::LocalBankTransfer { bank_code } => Self::LocalBankTransfer(Box::new(
api_models::payments::additional_info::LocalBankTransferAdditionalData {
bank_code: bank_code.map(MaskedBankAccount::from),
},
)),
BankTransferData::InstantBankTransfer {} => Self::InstantBankTransfer {},
BankTransferData::InstantBankTransferFinland {} => Self::InstantBankTransferFinland {},
BankTransferData::InstantBankTransferPoland {} => Self::InstantBankTransferPoland {},
BankTransferData::IndonesianBankTransfer { bank_name } => {
Self::IndonesianBankTransfer { bank_name }
}
}
}
}
impl From<api_models::payments::RealTimePaymentData> for RealTimePaymentData {
fn from(value: api_models::payments::RealTimePaymentData) -> Self {
match value {
api_models::payments::RealTimePaymentData::Fps {} => Self::Fps {},
api_models::payments::RealTimePaymentData::DuitNow {} => Self::DuitNow {},
api_models::payments::RealTimePaymentData::PromptPay {} => Self::PromptPay {},
api_models::payments::RealTimePaymentData::VietQr {} => Self::VietQr {},
}
}
}
impl From<RealTimePaymentData> for api_models::payments::RealTimePaymentData {
fn from(value: RealTimePaymentData) -> Self {
match value {
RealTimePaymentData::Fps {} => Self::Fps {},
RealTimePaymentData::DuitNow {} => Self::DuitNow {},
RealTimePaymentData::PromptPay {} => Self::PromptPay {},
RealTimePaymentData::VietQr {} => Self::VietQr {},
}
}
}
impl From<api_models::payments::OpenBankingData> for OpenBankingData {
fn from(value: api_models::payments::OpenBankingData) -> Self {
match value {
api_models::payments::OpenBankingData::OpenBankingPIS {} => Self::OpenBankingPIS {},
}
}
}
impl From<OpenBankingData> for api_models::payments::OpenBankingData {
fn from(value: OpenBankingData) -> Self {
match value {
OpenBankingData::OpenBankingPIS {} => Self::OpenBankingPIS {},
}
}
}
impl From<api_models::payments::MobilePaymentData> for MobilePaymentData {
fn from(value: api_models::payments::MobilePaymentData) -> Self {
match value {
api_models::payments::MobilePaymentData::DirectCarrierBilling {
msisdn,
client_uid,
} => Self::DirectCarrierBilling { msisdn, client_uid },
}
}
}
impl From<MobilePaymentData> for api_models::payments::MobilePaymentData {
fn from(value: MobilePaymentData) -> Self {
match value {
MobilePaymentData::DirectCarrierBilling { msisdn, client_uid } => {
Self::DirectCarrierBilling { msisdn, client_uid }
}
}
}
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizedCardValue1 {
pub card_number: String,
pub exp_year: String,
pub exp_month: String,
pub nickname: Option<String>,
pub card_last_four: Option<String>,
pub card_token: Option<String>,
pub card_holder_name: Option<Secret<String>>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizedCardValue2 {
pub card_security_code: Option<String>,
pub card_fingerprint: Option<String>,
pub external_id: Option<String>,
pub customer_id: Option<id_type::CustomerId>,
pub payment_method_id: Option<String>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedWalletValue1 {
pub data: WalletData,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedWalletValue2 {
pub customer_id: Option<id_type::CustomerId>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankTransferValue1 {
pub data: BankTransferData,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankTransferValue2 {
pub customer_id: Option<id_type::CustomerId>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankRedirectValue1 {
pub data: BankRedirectData,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankRedirectValue2 {
pub customer_id: Option<id_type::CustomerId>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankDebitValue2 {
pub customer_id: Option<id_type::CustomerId>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankDebitValue1 {
pub data: BankDebitData,
}
pub trait GetPaymentMethodType {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType;
}
impl GetPaymentMethodType for CardRedirectData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::Knet {} => api_enums::PaymentMethodType::Knet,
Self::Benefit {} => api_enums::PaymentMethodType::Benefit,
Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm,
Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect,
}
}
}
impl GetPaymentMethodType for WalletData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay,
Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk,
Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay,
Self::Skrill(_) => api_enums::PaymentMethodType::Skrill,
Self::Paysera(_) => api_enums::PaymentMethodType::Paysera,
Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo,
Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay,
Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay,
Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash,
Self::AmazonPay(_) => api_enums::PaymentMethodType::AmazonPay,
Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => {
api_enums::PaymentMethodType::ApplePay
}
Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana,
Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => {
api_enums::PaymentMethodType::GooglePay
}
Self::BluecodeRedirect {} => api_enums::PaymentMethodType::Bluecode,
Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay,
Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay,
Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal,
Self::Paze(_) => api_enums::PaymentMethodType::Paze,
Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay,
Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint,
Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps,
Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo,
Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => {
api_enums::PaymentMethodType::WeChatPay
}
Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp,
Self::SwishQr(_) => api_enums::PaymentMethodType::Swish,
Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity,
Self::RevolutPay(_) => api_enums::PaymentMethodType::RevolutPay,
}
}
}
impl GetPaymentMethodType for PayLaterData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna,
Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna,
Self::FlexitiRedirect { .. } => api_enums::PaymentMethodType::Flexiti,
Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm,
Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay,
Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright,
Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley,
Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma,
Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome,
Self::BreadpayRedirect {} => api_enums::PaymentMethodType::Breadpay,
}
}
}
impl GetPaymentMethodType for BankRedirectData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard,
Self::Bizum {} => api_enums::PaymentMethodType::Bizum,
Self::Blik { .. } => api_enums::PaymentMethodType::Blik,
Self::Eft { .. } => api_enums::PaymentMethodType::Eft,
Self::Eps { .. } => api_enums::PaymentMethodType::Eps,
Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay,
Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal,
Self::Interac { .. } => api_enums::PaymentMethodType::Interac,
Self::OnlineBankingCzechRepublic { .. } => {
api_enums::PaymentMethodType::OnlineBankingCzechRepublic
}
Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland,
Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland,
Self::OnlineBankingSlovakia { .. } => {
api_enums::PaymentMethodType::OnlineBankingSlovakia
}
Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk,
Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24,
Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort,
Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly,
Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx,
Self::OnlineBankingThailand { .. } => {
api_enums::PaymentMethodType::OnlineBankingThailand
}
Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect,
}
}
}
impl GetPaymentMethodType for BankDebitData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach,
Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa,
Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs,
Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs,
}
}
}
impl GetPaymentMethodType for BankTransferData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach,
Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::Sepa,
Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs,
Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco,
Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer,
Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer,
Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa,
Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa,
Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa,
Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa,
Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa,
Self::Pix { .. } => api_enums::PaymentMethodType::Pix,
Self::Pse {} => api_enums::PaymentMethodType::Pse,
Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer,
Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer,
Self::InstantBankTransferFinland {} => {
api_enums::PaymentMethodType::InstantBankTransferFinland
}
Self::InstantBankTransferPoland {} => {
api_enums::PaymentMethodType::InstantBankTransferPoland
}
Self::IndonesianBankTransfer { .. } => {
api_enums::PaymentMethodType::IndonesianBankTransfer
}
}
}
}
impl GetPaymentMethodType for CryptoData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
api_enums::PaymentMethodType::CryptoCurrency
}
}
impl GetPaymentMethodType for RealTimePaymentData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::Fps {} => api_enums::PaymentMethodType::Fps,
Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow,
Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay,
Self::VietQr {} => api_enums::PaymentMethodType::VietQr,
}
}
}
impl GetPaymentMethodType for UpiData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect,
Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent,
}
}
}
impl GetPaymentMethodType for VoucherData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::Boleto(_) => api_enums::PaymentMethodType::Boleto,
Self::Efecty => api_enums::PaymentMethodType::Efecty,
Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo,
Self::RedCompra => api_enums::PaymentMethodType::RedCompra,
Self::RedPagos => api_enums::PaymentMethodType::RedPagos,
Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart,
Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret,
Self::Oxxo => api_enums::PaymentMethodType::Oxxo,
Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven,
Self::Lawson(_) => api_enums::PaymentMethodType::Lawson,
Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop,
Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart,
Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart,
Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy,
}
}
}
impl GetPaymentMethodType for GiftCardData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::Givex(_) => api_enums::PaymentMethodType::Givex,
Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard,
Self::BhnCardNetwork(_) => api_enums::PaymentMethodType::BhnCardNetwork,
}
}
}
impl GetPaymentMethodType for OpenBankingData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS,
}
}
}
impl GetPaymentMethodType for MobilePaymentData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling,
}
}
}
impl From<Card> for ExtendedCardInfo {
fn from(value: Card) -> Self {
Self {
card_number: value.card_number,
card_exp_month: value.card_exp_month,
card_exp_year: value.card_exp_year,
card_holder_name: None,
card_cvc: value.card_cvc,
card_issuer: value.card_issuer,
card_network: value.card_network,
card_type: value.card_type,
card_issuing_country: value.card_issuing_country,
bank_code: value.bank_code,
}
}
}
impl From<ApplePayWalletData> for payment_methods::PaymentMethodDataWalletInfo {
fn from(item: ApplePayWalletData) -> Self {
Self {
last4: item
.payment_method
.display_name
.chars()
.rev()
.take(4)
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect(),
card_network: item.payment_method.network,
card_type: Some(item.payment_method.pm_type),
}
}
}
impl From<GooglePayWalletData> for payment_methods::PaymentMethodDataWalletInfo {
fn from(item: GooglePayWalletData) -> Self {
Self {
last4: item.info.card_details,
card_network: item.info.card_network,
card_type: Some(item.pm_type),
}
}
}
#[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)]
pub enum PaymentMethodsData {
Card(CardDetailsPaymentMethod),
BankDetails(payment_methods::PaymentMethodDataBankCreds), //PaymentMethodDataBankCreds and its transformations should be moved to the domain models
WalletDetails(payment_methods::PaymentMethodDataWalletInfo), //PaymentMethodDataWalletInfo and its transformations should be moved to the domain models
NetworkToken(NetworkTokenDetailsPaymentMethod),
}
impl PaymentMethodsData {
#[cfg(feature = "v1")]
pub fn get_co_badged_card_data(&self) -> Option<payment_methods::CoBadgedCardData> {
if let Self::Card(card) = self {
card.co_badged_card_data.clone()
} else {
None
}
}
#[cfg(feature = "v2")]
pub fn get_co_badged_card_data(&self) -> Option<payment_methods::CoBadgedCardData> {
todo!()
}
#[cfg(feature = "v1")]
pub fn get_additional_payout_method_data(
&self,
) -> Option<payout_method_utils::AdditionalPayoutMethodData> {
match self {
Self::Card(card_details) => {
router_env::logger::info!("Populating AdditionalPayoutMethodData from Card payment method data for recurring payout");
Some(payout_method_utils::AdditionalPayoutMethodData::Card(
Box::new(payout_method_utils::CardAdditionalData {
card_issuer: card_details.card_issuer.clone(),
card_network: card_details.card_network.clone(),
bank_code: None,
card_type: card_details.card_type.clone(),
card_issuing_country: card_details.issuer_country.clone(),
last4: card_details.last4_digits.clone(),
card_isin: card_details.card_isin.clone(),
card_extended_bin: None,
card_exp_month: card_details.expiry_month.clone(),
card_exp_year: card_details.expiry_year.clone(),
card_holder_name: card_details.card_holder_name.clone(),
}),
))
}
Self::BankDetails(_) | Self::WalletDetails(_) | Self::NetworkToken(_) => None,
}
}
pub fn get_card_details(&self) -> Option<CardDetailsPaymentMethod> {
if let Self::Card(card) = self {
Some(card.clone())
} else {
None
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct NetworkTokenDetailsPaymentMethod {
pub last4_digits: Option<String>,
pub issuer_country: Option<common_enums::CountryAlpha2>,
pub network_token_expiry_month: Option<Secret<String>>,
pub network_token_expiry_year: Option<Secret<String>>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
pub card_isin: Option<String>,
pub card_issuer: Option<String>,
pub card_network: Option<api_enums::CardNetwork>,
pub card_type: Option<String>,
#[serde(default = "saved_in_locker_default")]
pub saved_to_locker: bool,
}
fn saved_in_locker_default() -> bool {
true
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct CardDetailsPaymentMethod {
pub last4_digits: Option<String>,
pub issuer_country: Option<String>,
pub expiry_month: Option<Secret<String>>,
pub expiry_year: Option<Secret<String>>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
pub card_isin: Option<String>,
pub card_issuer: Option<String>,
pub card_network: Option<api_enums::CardNetwork>,
pub card_type: Option<String>,
#[serde(default = "saved_in_locker_default")]
pub saved_to_locker: bool,
pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct CardDetailsPaymentMethod {
pub last4_digits: Option<String>,
pub issuer_country: Option<String>,
pub expiry_month: Option<Secret<String>>,
pub expiry_year: Option<Secret<String>>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
pub card_isin: Option<String>,
pub card_issuer: Option<String>,
pub card_network: Option<api_enums::CardNetwork>,
pub card_type: Option<String>,
#[serde(default = "saved_in_locker_default")]
pub saved_to_locker: bool,
}
#[cfg(feature = "v2")]
impl CardDetailsPaymentMethod {
pub fn to_card_details_from_locker(self) -> payment_methods::CardDetailFromLocker {
payment_methods::CardDetailFromLocker {
card_number: None,
card_holder_name: self.card_holder_name.clone(),
card_issuer: self.card_issuer.clone(),
card_network: self.card_network.clone(),
card_type: self.card_type.clone(),
issuer_country: self.clone().get_issuer_country_alpha2(),
last4_digits: self.last4_digits,
expiry_month: self.expiry_month,
expiry_year: self.expiry_year,
card_fingerprint: None,
nick_name: self.nick_name,
card_isin: self.card_isin,
saved_to_locker: self.saved_to_locker,
}
}
pub fn get_issuer_country_alpha2(self) -> Option<common_enums::CountryAlpha2> {
self.issuer_country
.as_ref()
.map(|c| api_enums::CountryAlpha2::from_str(c))
.transpose()
.ok()
.flatten()
}
}
#[cfg(feature = "v1")]
impl From<payment_methods::CardDetail> for CardDetailsPaymentMethod {
fn from(item: payment_methods::CardDetail) -> Self {
Self {
issuer_country: item.card_issuing_country.map(|c| c.to_string()),
last4_digits: Some(item.card_number.get_last4()),
expiry_month: Some(item.card_exp_month),
expiry_year: Some(item.card_exp_year),
card_holder_name: item.card_holder_name,
nick_name: item.nick_name,
card_isin: None,
card_issuer: item.card_issuer,
card_network: item.card_network,
card_type: item.card_type.map(|card| card.to_string()),
saved_to_locker: true,
co_badged_card_data: None,
}
}
}
#[cfg(feature = "v2")]
impl From<payment_methods::CardDetail> for CardDetailsPaymentMethod {
fn from(item: payment_methods::CardDetail) -> Self {
Self {
issuer_country: item.card_issuing_country.map(|c| c.to_string()),
last4_digits: Some(item.card_number.get_last4()),
expiry_month: Some(item.card_exp_month),
expiry_year: Some(item.card_exp_year),
card_holder_name: item.card_holder_name,
nick_name: item.nick_name,
card_isin: None,
card_issuer: item.card_issuer,
card_network: item.card_network,
card_type: item.card_type.map(|card| card.to_string()),
saved_to_locker: true,
}
}
}
#[cfg(feature = "v2")]
impl From<NetworkTokenDetails> for NetworkTokenDetailsPaymentMethod {
fn from(item: NetworkTokenDetails) -> Self {
Self {
issuer_country: item.card_issuing_country,
last4_digits: Some(item.network_token.get_last4()),
network_token_expiry_month: Some(item.network_token_exp_month),
network_token_expiry_year: Some(item.network_token_exp_year),
card_holder_name: item.card_holder_name,
nick_name: item.nick_name,
card_isin: None,
card_issuer: item.card_issuer,
card_network: item.card_network,
card_type: item.card_type.map(|card| card.to_string()),
saved_to_locker: true,
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct SingleUsePaymentMethodToken {
pub token: Secret<String>,
pub merchant_connector_id: id_type::MerchantConnectorAccountId,
}
#[cfg(feature = "v2")]
impl SingleUsePaymentMethodToken {
pub fn get_single_use_token_from_payment_method_token(
token: Secret<String>,
mca_id: id_type::MerchantConnectorAccountId,
) -> Self {
Self {
token,
merchant_connector_id: mca_id,
}
}
}
impl From<NetworkTokenDetailsPaymentMethod> for payment_methods::NetworkTokenDetailsPaymentMethod {
fn from(item: NetworkTokenDetailsPaymentMethod) -> Self {
Self {
last4_digits: item.last4_digits,
issuer_country: item.issuer_country,
network_token_expiry_month: item.network_token_expiry_month,
network_token_expiry_year: item.network_token_expiry_year,
nick_name: item.nick_name,
card_holder_name: item.card_holder_name,
card_isin: item.card_isin,
card_issuer: item.card_issuer,
card_network: item.card_network,
card_type: item.card_type,
saved_to_locker: item.saved_to_locker,
}
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct SingleUseTokenKey(String);
#[cfg(feature = "v2")]
impl SingleUseTokenKey {
pub fn store_key(payment_method_id: &id_type::GlobalPaymentMethodId) -> Self {
let new_token = format!("single_use_token_{}", payment_method_id.get_string_repr());
Self(new_token)
}
pub fn get_store_key(&self) -> &str {
&self.0
}
}
#[cfg(feature = "v1")]
impl From<Card> for payment_methods::CardDetail {
fn from(card_data: Card) -> Self {
Self {
card_number: card_data.card_number.clone(),
card_exp_month: card_data.card_exp_month.clone(),
card_exp_year: card_data.card_exp_year.clone(),
card_holder_name: None,
nick_name: None,
card_issuing_country: None,
card_network: card_data.card_network.clone(),
card_issuer: None,
card_type: None,
}
}
}
#[cfg(feature = "v1")]
impl From<NetworkTokenData> for payment_methods::CardDetail {
fn from(network_token_data: NetworkTokenData) -> Self {
Self {
card_number: network_token_data.token_number.clone(),
card_exp_month: network_token_data.token_exp_month.clone(),
card_exp_year: network_token_data.token_exp_year.clone(),
card_holder_name: None,
nick_name: None,
card_issuing_country: None,
card_network: network_token_data.card_network.clone(),
card_issuer: None,
card_type: None,
}
}
}
#[cfg(feature = "v1")]
impl
From<(
payment_methods::CardDetail,
Option<&CardToken>,
Option<payment_methods::CoBadgedCardData>,
)> for Card
{
fn from(
value: (
payment_methods::CardDetail,
Option<&CardToken>,
Option<payment_methods::CoBadgedCardData>,
),
) -> Self {
let (
payment_methods::CardDetail {
card_number,
card_exp_month,
card_exp_year,
card_holder_name,
nick_name,
card_network,
card_issuer,
card_issuing_country,
card_type,
},
card_token_data,
co_badged_card_data,
) = value;
// The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked
let name_on_card = if let Some(name) = card_holder_name.clone() {
if name.clone().expose().is_empty() {
card_token_data
.and_then(|token_data| token_data.card_holder_name.clone())
.or(Some(name))
} else {
card_holder_name
}
} else {
card_token_data.and_then(|token_data| token_data.card_holder_name.clone())
};
Self {
card_number,
card_exp_month,
card_exp_year,
card_holder_name: name_on_card,
card_cvc: card_token_data
.cloned()
.unwrap_or_default()
.card_cvc
.unwrap_or_default(),
card_issuer,
card_network,
card_type,
card_issuing_country,
bank_code: None,
nick_name,
co_badged_card_data,
}
}
}
#[cfg(feature = "v1")]
impl
TryFrom<(
cards::CardNumber,
Option<&CardToken>,
Option<payment_methods::CoBadgedCardData>,
CardDetailsPaymentMethod,
)> for Card
{
type Error = error_stack::Report<common_utils::errors::ValidationError>;
fn try_from(
value: (
cards::CardNumber,
Option<&CardToken>,
Option<payment_methods::CoBadgedCardData>,
CardDetailsPaymentMethod,
),
) -> Result<Self, Self::Error> {
let (card_number, card_token_data, co_badged_card_data, card_details) = value;
// The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked
let name_on_card = if let Some(name) = card_details.card_holder_name.clone() {
if name.clone().expose().is_empty() {
card_token_data
.and_then(|token_data| token_data.card_holder_name.clone())
.or(Some(name))
} else {
Some(name)
}
} else {
card_token_data.and_then(|token_data| token_data.card_holder_name.clone())
};
Ok(Self {
card_number,
card_exp_month: card_details
.expiry_month
.get_required_value("expiry_month")?
.clone(),
card_exp_year: card_details
.expiry_year
.get_required_value("expiry_year")?
.clone(),
card_holder_name: name_on_card,
card_cvc: card_token_data
.cloned()
.unwrap_or_default()
.card_cvc
.unwrap_or_default(),
card_issuer: card_details.card_issuer,
card_network: card_details.card_network,
card_type: card_details.card_type,
card_issuing_country: card_details.issuer_country,
bank_code: None,
nick_name: card_details.nick_name,
co_badged_card_data,
})
}
}
|
crates/hyperswitch_domain_models/src/payment_method_data.rs#chunk2
|
hyperswitch_domain_models
|
chunk
| null | null | null | 7,571
| null | null | null | null | null | null | null |
// Struct: Customer
// File: crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct Customer
|
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
Customer
| 0
|
[] | 43
| null | null | null | null | null | null | null |
// Function: payments_connector_session
// File: crates/router/src/routes/payments.rs
// Module: router
pub fn payments_connector_session(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsSessionRequest>,
) -> impl Responder
|
crates/router/src/routes/payments.rs
|
router
|
function_signature
| null | null | null | 69
|
payments_connector_session
| null | null | null | null | null | null |
// Struct: PaypalMandateStruct
// File: crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaypalMandateStruct
|
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaypalMandateStruct
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Implementation: impl Responder
// File: crates/router/src/routes/routing.rs
// Module: router
// Methods: 0 total (0 public)
impl Responder
|
crates/router/src/routes/routing.rs
|
router
|
impl_block
| null | null | null | 36
| null |
Responder
| null | 0
| 0
| null | null |
// Implementation: impl Profile
// File: crates/router/src/routes/app.rs
// Module: router
// Methods: 1 total (1 public)
impl Profile
|
crates/router/src/routes/app.rs
|
router
|
impl_block
| null | null | null | 33
| null |
Profile
| null | 1
| 1
| null | null |
// File: crates/router_derive/src/macros/to_encryptable.rs
// Module: router_derive
// Public functions: 1
// Public structs: 1
use std::iter::Iterator;
use quote::{format_ident, quote};
use syn::{parse::Parse, punctuated::Punctuated, token::Comma, Field, Ident, Type as SynType};
use crate::macros::{helpers::get_struct_fields, misc::get_field_type};
pub struct FieldMeta {
_meta_type: Ident,
pub value: Ident,
}
impl Parse for FieldMeta {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let _meta_type: Ident = input.parse()?;
input.parse::<syn::Token![=]>()?;
let value: Ident = input.parse()?;
Ok(Self { _meta_type, value })
}
}
impl quote::ToTokens for FieldMeta {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
self.value.to_tokens(tokens);
}
}
fn get_encryption_ty_meta(field: &Field) -> Option<FieldMeta> {
let attrs = &field.attrs;
attrs
.iter()
.flat_map(|s| s.parse_args::<FieldMeta>())
.find(|s| s._meta_type.eq("ty"))
}
fn get_inner_type(path: &syn::TypePath) -> syn::Result<syn::TypePath> {
path.path
.segments
.last()
.and_then(|segment| match &segment.arguments {
syn::PathArguments::AngleBracketed(args) => args.args.first(),
_ => None,
})
.and_then(|arg| match arg {
syn::GenericArgument::Type(SynType::Path(path)) => Some(path.clone()),
_ => None,
})
.ok_or_else(|| {
syn::Error::new(
proc_macro2::Span::call_site(),
"Only path fields are supported",
)
})
}
/// This function returns the inner most type recursively
/// For example:
///
/// In the case of `Encryptable<Secret<String>>> this returns String
fn get_inner_most_type(ty: SynType) -> syn::Result<Ident> {
fn get_inner_type_recursive(path: syn::TypePath) -> syn::Result<syn::TypePath> {
match get_inner_type(&path) {
Ok(inner_path) => get_inner_type_recursive(inner_path),
Err(_) => Ok(path),
}
}
match ty {
SynType::Path(path) => {
let inner_path = get_inner_type_recursive(path)?;
inner_path
.path
.segments
.last()
.map(|last_segment| last_segment.ident.to_owned())
.ok_or_else(|| {
syn::Error::new(
proc_macro2::Span::call_site(),
"At least one ident must be specified",
)
})
}
_ => Err(syn::Error::new(
proc_macro2::Span::call_site(),
"Only path fields are supported",
)),
}
}
/// This returns the field which implement #[encrypt] attribute
fn get_encryptable_fields(fields: Punctuated<Field, Comma>) -> Vec<Field> {
fields
.into_iter()
.filter(|field| {
field
.attrs
.iter()
.any(|attr| attr.path().is_ident("encrypt"))
})
.collect()
}
/// This function returns the inner most type of a field
fn get_field_and_inner_types(fields: &[Field]) -> Vec<(Field, Ident)> {
fields
.iter()
.flat_map(|field| {
get_inner_most_type(field.ty.clone()).map(|field_name| (field.to_owned(), field_name))
})
.collect()
}
/// The type of the struct for which the batch encryption/decryption needs to be implemented
#[derive(PartialEq, Copy, Clone)]
enum StructType {
Encrypted,
Decrypted,
DecryptedUpdate,
FromRequest,
Updated,
}
impl StructType {
/// Generates the fields for temporary structs which consists of the fields that should be
/// encrypted/decrypted
fn generate_struct_fields(self, fields: &[(Field, Ident)]) -> Vec<proc_macro2::TokenStream> {
fields
.iter()
.map(|(field, inner_ty)| {
let provided_ty = get_encryption_ty_meta(field);
let is_option = get_field_type(field.ty.clone())
.map(|f| f.eq("Option"))
.unwrap_or_default();
let ident = &field.ident;
let inner_ty = if let Some(ref ty) = provided_ty {
&ty.value
} else {
inner_ty
};
match (self, is_option) {
(Self::Encrypted, true) => quote! { pub #ident: Option<Encryption> },
(Self::Encrypted, false) => quote! { pub #ident: Encryption },
(Self::Decrypted, true) => {
quote! { pub #ident: Option<Encryptable<Secret<#inner_ty>>> }
}
(Self::Decrypted, false) => {
quote! { pub #ident: Encryptable<Secret<#inner_ty>> }
}
(Self::DecryptedUpdate, _) => {
quote! { pub #ident: Option<Encryptable<Secret<#inner_ty>>> }
}
(Self::FromRequest, true) => {
quote! { pub #ident: Option<Secret<#inner_ty>> }
}
(Self::FromRequest, false) => quote! { pub #ident: Secret<#inner_ty> },
(Self::Updated, _) => quote! { pub #ident: Option<Secret<#inner_ty>> },
}
})
.collect()
}
/// Generates the ToEncryptable trait implementation
fn generate_impls(
self,
gen1: proc_macro2::TokenStream,
gen2: proc_macro2::TokenStream,
gen3: proc_macro2::TokenStream,
impl_st: proc_macro2::TokenStream,
inner: &[Field],
) -> proc_macro2::TokenStream {
let map_length = inner.len();
let to_encryptable_impl = inner.iter().flat_map(|field| {
get_field_type(field.ty.clone()).map(|field_ty| {
let is_option = field_ty.eq("Option");
let field_ident = &field.ident;
let field_ident_string = field_ident.as_ref().map(|s| s.to_string());
if is_option || self == Self::Updated {
quote! { self.#field_ident.map(|s| map.insert(#field_ident_string.to_string(), s)) }
} else {
quote! { map.insert(#field_ident_string.to_string(), self.#field_ident) }
}
})
});
let from_encryptable_impl = inner.iter().flat_map(|field| {
get_field_type(field.ty.clone()).map(|field_ty| {
let is_option = field_ty.eq("Option");
let field_ident = &field.ident;
let field_ident_string = field_ident.as_ref().map(|s| s.to_string());
if is_option || self == Self::Updated {
quote! { #field_ident: map.remove(#field_ident_string) }
} else {
quote! {
#field_ident: map.remove(#field_ident_string).ok_or(
error_stack::report!(common_utils::errors::ParsingError::EncodeError(
"Unable to convert from HashMap",
))
)?
}
}
})
});
quote! {
impl ToEncryptable<#gen1, #gen2, #gen3> for #impl_st {
fn to_encryptable(self) -> FxHashMap<String, #gen3> {
let mut map = FxHashMap::with_capacity_and_hasher(#map_length, Default::default());
#(#to_encryptable_impl;)*
map
}
fn from_encryptable(
mut map: FxHashMap<String, Encryptable<#gen2>>,
) -> CustomResult<#gen1, common_utils::errors::ParsingError> {
Ok(#gen1 {
#(#from_encryptable_impl,)*
})
}
}
}
}
}
/// This function generates the temporary struct and ToEncryptable impls for the temporary structs
fn generate_to_encryptable(
struct_name: Ident,
fields: Vec<Field>,
) -> syn::Result<proc_macro2::TokenStream> {
let struct_types = [
// The first two are to be used as return types we do not need to implement ToEncryptable
// on it
("Decrypted", StructType::Decrypted),
("DecryptedUpdate", StructType::DecryptedUpdate),
("FromRequestEncryptable", StructType::FromRequest),
("Encrypted", StructType::Encrypted),
("UpdateEncryptable", StructType::Updated),
];
let inner_types = get_field_and_inner_types(&fields);
let inner_type = inner_types.first().ok_or_else(|| {
syn::Error::new(
proc_macro2::Span::call_site(),
"Please use the macro with attribute #[encrypt] on the fields you want to encrypt",
)
})?;
let provided_ty = get_encryption_ty_meta(&inner_type.0)
.map(|ty| ty.value.clone())
.unwrap_or(inner_type.1.clone());
let structs = struct_types.iter().map(|(prefix, struct_type)| {
let name = format_ident!("{}{}", prefix, struct_name);
let temp_fields = struct_type.generate_struct_fields(&inner_types);
quote! {
pub struct #name {
#(#temp_fields,)*
}
}
});
// These implementations shouldn't be implemented Decrypted and DecryptedUpdate temp structs
// So skip the first two entries in the list
let impls = struct_types
.iter()
.skip(2)
.map(|(prefix, struct_type)| {
let name = format_ident!("{}{}", prefix, struct_name);
let impl_block = if *struct_type != StructType::DecryptedUpdate
|| *struct_type != StructType::Decrypted
{
let (gen1, gen2, gen3) = match struct_type {
StructType::FromRequest => {
let decrypted_name = format_ident!("Decrypted{}", struct_name);
(
quote! { #decrypted_name },
quote! { Secret<#provided_ty> },
quote! { Secret<#provided_ty> },
)
}
StructType::Encrypted => {
let decrypted_name = format_ident!("Decrypted{}", struct_name);
(
quote! { #decrypted_name },
quote! { Secret<#provided_ty> },
quote! { Encryption },
)
}
StructType::Updated => {
let decrypted_update_name = format_ident!("DecryptedUpdate{}", struct_name);
(
quote! { #decrypted_update_name },
quote! { Secret<#provided_ty> },
quote! { Secret<#provided_ty> },
)
}
//Unreachable statement
_ => (quote! {}, quote! {}, quote! {}),
};
struct_type.generate_impls(gen1, gen2, gen3, quote! { #name }, &fields)
} else {
quote! {}
};
Ok(quote! {
#impl_block
})
})
.collect::<syn::Result<Vec<_>>>()?;
Ok(quote! {
#(#structs)*
#(#impls)*
})
}
pub fn derive_to_encryption(
input: syn::DeriveInput,
) -> Result<proc_macro2::TokenStream, syn::Error> {
let struct_name = input.ident;
let fields = get_encryptable_fields(get_struct_fields(input.data)?);
generate_to_encryptable(struct_name, fields)
}
|
crates/router_derive/src/macros/to_encryptable.rs
|
router_derive
|
full_file
| null | null | null | 2,570
| null | null | null | null | null | null | null |
// Implementation: impl DummyConnectorRefundResponse
// File: crates/router/src/routes/dummy_connector/types.rs
// Module: router
// Methods: 1 total (1 public)
impl DummyConnectorRefundResponse
|
crates/router/src/routes/dummy_connector/types.rs
|
router
|
impl_block
| null | null | null | 44
| null |
DummyConnectorRefundResponse
| null | 1
| 1
| null | null |
// Function: find_by_merchant_id_customer_id
// File: crates/diesel_models/src/query/mandate.rs
// Module: diesel_models
pub fn find_by_merchant_id_customer_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
customer_id: &common_utils::id_type::CustomerId,
) -> StorageResult<Vec<Self>>
|
crates/diesel_models/src/query/mandate.rs
|
diesel_models
|
function_signature
| null | null | null | 85
|
find_by_merchant_id_customer_id
| null | null | null | null | null | null |
// Function: receive_incoming_relay_webhook
// File: crates/router/src/routes/webhooks.rs
// Module: router
pub fn receive_incoming_relay_webhook<W: types::OutgoingWebhookType>(
state: web::Data<AppState>,
req: HttpRequest,
body: web::Bytes,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::MerchantConnectorAccountId,
)
|
crates/router/src/routes/webhooks.rs
|
router
|
function_signature
| null | null | null | 98
|
receive_incoming_relay_webhook
| null | null | null | null | null | null |
// Function: refunds_retrieve
// File: crates/router/src/routes/refunds.rs
// Module: router
pub fn refunds_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
query_params: web::Query<api_models::refunds::RefundsRetrieveBody>,
) -> HttpResponse
|
crates/router/src/routes/refunds.rs
|
router
|
function_signature
| null | null | null | 73
|
refunds_retrieve
| null | null | null | null | null | null |
// Implementation: impl api::ConnectorAccessToken for for Aci
// File: crates/hyperswitch_connectors/src/connectors/aci.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::ConnectorAccessToken for for Aci
|
crates/hyperswitch_connectors/src/connectors/aci.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Aci
|
api::ConnectorAccessToken for
| 0
| 0
| null | null |
// Implementation: impl api::ConnectorAccessToken for for Tokenio
// File: crates/hyperswitch_connectors/src/connectors/tokenio.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::ConnectorAccessToken for for Tokenio
|
crates/hyperswitch_connectors/src/connectors/tokenio.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Tokenio
|
api::ConnectorAccessToken for
| 0
| 0
| null | null |
// Struct: TestPayment
// File: crates/api_models/src/user/dashboard_metadata.rs
// Module: api_models
// Implementations: 0
pub struct TestPayment
|
crates/api_models/src/user/dashboard_metadata.rs
|
api_models
|
struct_definition
|
TestPayment
| 0
|
[] | 35
| null | null | null | null | null | null | null |
// Function: validate
// File: crates/router/src/configs/validations.rs
// Module: router
pub fn validate(&self) -> Result<(), ApplicationError>
|
crates/router/src/configs/validations.rs
|
router
|
function_signature
| null | null | null | 35
|
validate
| null | null | null | null | null | null |
// Struct: GlobalpayCancelRouterData
// File: crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct GlobalpayCancelRouterData<T>
|
crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs
|
hyperswitch_connectors
|
struct_definition
|
GlobalpayCancelRouterData
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Implementation: impl Responder
// File: crates/router/src/analytics.rs
// Module: router
// Methods: 0 total (0 public)
impl Responder
|
crates/router/src/analytics.rs
|
router
|
impl_block
| null | null | null | 35
| null |
Responder
| null | 0
| 0
| null | null |
// File: crates/analytics/src/payments/metrics/retries_count.rs
// Module: analytics
use std::collections::HashSet;
use api_models::{
analytics::{
payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier},
Granularity, TimeRange,
},
enums::IntentStatus,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::PaymentMetricRow;
use crate::{
enums::AuthInfo,
query::{
Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql,
Window,
},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(super) struct RetriesCount;
#[async_trait::async_trait]
impl<T> super::PaymentMetric<T> for RetriesCount
where
T: AnalyticsDataSource + super::PaymentMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
_dimensions: &[PaymentDimensions],
auth: &AuthInfo,
_filters: &PaymentFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> {
let mut query_builder: QueryBuilder<T> =
QueryBuilder::new(AnalyticsCollection::PaymentIntent);
query_builder
.add_select_column(Aggregate::Count {
field: None,
alias: Some("count"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Sum {
field: "amount",
alias: Some("total"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
auth.set_filter_clause(&mut query_builder).switch()?;
query_builder
.add_custom_filter_clause("attempt_count", "1", FilterTypes::Gt)
.switch()?;
query_builder
.add_custom_filter_clause("status", IntentStatus::Succeeded, FilterTypes::Equal)
.switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.attach_printable("Error adding granularity")
.switch()?;
}
query_builder
.execute_query::<PaymentMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
PaymentMetricsBucketIdentifier::new(
i.currency.as_ref().map(|i| i.0),
None,
i.connector.clone(),
i.authentication_type.as_ref().map(|i| i.0),
i.payment_method.clone(),
i.payment_method_type.clone(),
i.client_source.clone(),
i.client_version.clone(),
i.profile_id.clone(),
i.card_network.clone(),
i.merchant_id.clone(),
i.card_last_4.clone(),
i.card_issuer.clone(),
i.error_reason.clone(),
i.routing_approach.as_ref().map(|i| i.0.clone()),
i.signature_network.clone(),
i.is_issuer_regulated,
i.is_debit_routed,
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
},
),
i,
))
})
.collect::<error_stack::Result<
HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>,
crate::query::PostProcessingError,
>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
|
crates/analytics/src/payments/metrics/retries_count.rs
|
analytics
|
full_file
| null | null | null | 974
| null | null | null | null | null | null | null |
// Function: flat_struct_derive
// File: crates/router_derive/src/lib.rs
// Module: router_derive
pub fn flat_struct_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream
|
crates/router_derive/src/lib.rs
|
router_derive
|
function_signature
| null | null | null | 46
|
flat_struct_derive
| null | null | null | null | null | null |
// Function: accept_dispute
// File: crates/router/src/routes/disputes.rs
// Module: router
pub fn accept_dispute(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse
|
crates/router/src/routes/disputes.rs
|
router
|
function_signature
| null | null | null | 55
|
accept_dispute
| null | null | null | null | null | null |
// Struct: BankDebitTypes
// File: crates/api_models/src/payment_methods.rs
// Module: api_models
// Implementations: 0
pub struct BankDebitTypes
|
crates/api_models/src/payment_methods.rs
|
api_models
|
struct_definition
|
BankDebitTypes
| 0
|
[] | 38
| null | null | null | null | null | null | null |
// Implementation: impl api::Payouts for for Paypal
// File: crates/hyperswitch_connectors/src/connectors/paypal.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::Payouts for for Paypal
|
crates/hyperswitch_connectors/src/connectors/paypal.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Paypal
|
api::Payouts for
| 0
| 0
| null | null |
// Implementation: impl PaymentConfirmData
// File: crates/hyperswitch_domain_models/src/payments.rs
// Module: hyperswitch_domain_models
// Methods: 3 total (3 public)
impl PaymentConfirmData
|
crates/hyperswitch_domain_models/src/payments.rs
|
hyperswitch_domain_models
|
impl_block
| null | null | null | 45
| null |
PaymentConfirmData
| null | 3
| 3
| null | null |
// Struct: CustomerDetails
// File: crates/hyperswitch_domain_models/src/router_request_types.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct CustomerDetails
|
crates/hyperswitch_domain_models/src/router_request_types.rs
|
hyperswitch_domain_models
|
struct_definition
|
CustomerDetails
| 0
|
[] | 41
| null | null | null | null | null | null | null |
// Implementation: impl WebhookResponseTracker
// File: crates/api_models/src/webhooks.rs
// Module: api_models
// Methods: 3 total (3 public)
impl WebhookResponseTracker
|
crates/api_models/src/webhooks.rs
|
api_models
|
impl_block
| null | null | null | 41
| null |
WebhookResponseTracker
| null | 3
| 3
| null | null |
// File: crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs
// Module: hyperswitch_connectors
// Public structs: 30
use api_models::{payments::AdditionalPaymentData, webhooks::IncomingWebhookEvent};
use common_enums::{Currency, FraudCheckStatus};
use common_utils::{
ext_traits::ValueExt,
id_type,
pii::Email,
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{self, ResultExt};
use hyperswitch_domain_models::{
router_data::RouterData,
router_flow_types::Fulfillment,
router_request_types::{
fraud_check::{FraudCheckFulfillmentData, FulfillmentStatus},
BrowserInformation, ResponseId,
},
router_response_types::fraud_check::FraudCheckResponseData,
};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{
types::{
FrmCheckoutRouterData, FrmFulfillmentRouterData, FrmTransactionRouterData,
ResponseRouterData,
},
utils::{
convert_amount, AddressDetailsData as _, FraudCheckCheckoutRequest,
FraudCheckTransactionRequest, RouterData as _,
},
};
type Error = error_stack::Report<ConnectorError>;
pub struct RiskifiedRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl<T> From<(StringMajorUnit, T)> for RiskifiedRouterData<T> {
fn from((amount, router_data): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data,
amount_converter: &StringMajorUnitForConnector,
}
}
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct RiskifiedPaymentsCheckoutRequest {
order: CheckoutRequest,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct CheckoutRequest {
id: String,
note: Option<String>,
email: Option<Email>,
#[serde(with = "common_utils::custom_serde::iso8601")]
created_at: PrimitiveDateTime,
currency: Option<Currency>,
#[serde(with = "common_utils::custom_serde::iso8601")]
updated_at: PrimitiveDateTime,
gateway: Option<String>,
browser_ip: Option<std::net::IpAddr>,
total_price: StringMajorUnit,
total_discounts: i64,
cart_token: String,
referring_site: String,
line_items: Vec<LineItem>,
discount_codes: Vec<DiscountCodes>,
shipping_lines: Vec<ShippingLines>,
payment_details: Option<PaymentDetails>,
customer: RiskifiedCustomer,
billing_address: Option<OrderAddress>,
shipping_address: Option<OrderAddress>,
source: Source,
client_details: ClientDetails,
vendor_name: String,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct PaymentDetails {
credit_card_bin: Option<Secret<String>>,
credit_card_number: Option<Secret<String>>,
credit_card_company: Option<api_models::enums::CardNetwork>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct ShippingLines {
price: StringMajorUnit,
title: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct DiscountCodes {
amount: StringMajorUnit,
code: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct ClientDetails {
user_agent: Option<String>,
accept_language: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct RiskifiedCustomer {
email: Option<Email>,
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
#[serde(with = "common_utils::custom_serde::iso8601")]
created_at: PrimitiveDateTime,
verified_email: bool,
id: id_type::CustomerId,
account_type: CustomerAccountType,
orders_count: i32,
phone: Option<Secret<String>>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "lowercase")]
pub enum CustomerAccountType {
Guest,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct OrderAddress {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
address1: Option<Secret<String>>,
country_code: Option<common_enums::CountryAlpha2>,
city: Option<String>,
province: Option<Secret<String>>,
phone: Option<Secret<String>>,
zip: Option<Secret<String>>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct LineItem {
price: StringMajorUnit,
quantity: i32,
title: String,
product_type: Option<common_enums::ProductType>,
requires_shipping: Option<bool>,
product_id: Option<String>,
category: Option<String>,
brand: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "snake_case")]
pub enum Source {
DesktopWeb,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct RiskifiedMetadata {
vendor_name: String,
shipping_lines: Vec<ShippingLines>,
}
impl TryFrom<&RiskifiedRouterData<&FrmCheckoutRouterData>> for RiskifiedPaymentsCheckoutRequest {
type Error = Error;
fn try_from(
payment: &RiskifiedRouterData<&FrmCheckoutRouterData>,
) -> Result<Self, Self::Error> {
let payment_data = payment.router_data.clone();
let metadata: RiskifiedMetadata = payment_data
.frm_metadata
.clone()
.ok_or(ConnectorError::MissingRequiredField {
field_name: "frm_metadata",
})?
.parse_value("Riskified Metadata")
.change_context(ConnectorError::InvalidDataFormat {
field_name: "frm_metadata",
})?;
let billing_address = payment_data.get_billing()?;
let shipping_address = payment_data.get_shipping_address_with_phone_number()?;
let address = payment_data.get_billing_address()?;
let line_items = payment_data
.request
.get_order_details()?
.iter()
.map(|order_detail| {
let price = convert_amount(
payment.amount_converter,
order_detail.amount,
payment_data.request.currency.ok_or_else(|| {
ConnectorError::MissingRequiredField {
field_name: "currency",
}
})?,
)?;
Ok(LineItem {
price,
quantity: i32::from(order_detail.quantity),
title: order_detail.product_name.clone(),
product_type: order_detail.product_type.clone(),
requires_shipping: order_detail.requires_shipping,
product_id: order_detail.product_id.clone(),
category: order_detail.category.clone(),
brand: order_detail.brand.clone(),
})
})
.collect::<Result<Vec<_>, Self::Error>>()?;
Ok(Self {
order: CheckoutRequest {
id: payment_data.attempt_id.clone(),
email: payment_data.request.email.clone(),
created_at: common_utils::date_time::now(),
updated_at: common_utils::date_time::now(),
gateway: payment_data.request.gateway.clone(),
total_price: payment.amount.clone(),
cart_token: payment_data.attempt_id.clone(),
line_items,
source: Source::DesktopWeb,
billing_address: OrderAddress::try_from(billing_address).ok(),
shipping_address: OrderAddress::try_from(shipping_address).ok(),
total_discounts: 0,
currency: payment_data.request.currency,
referring_site: "hyperswitch.io".to_owned(),
discount_codes: Vec::new(),
shipping_lines: metadata.shipping_lines,
customer: RiskifiedCustomer {
email: payment_data.request.email.clone(),
first_name: address.get_first_name().ok().cloned(),
last_name: address.get_last_name().ok().cloned(),
created_at: common_utils::date_time::now(),
verified_email: false,
id: payment_data.get_customer_id()?,
account_type: CustomerAccountType::Guest,
orders_count: 0,
phone: billing_address
.clone()
.phone
.and_then(|phone_data| phone_data.number),
},
browser_ip: payment_data
.request
.browser_info
.as_ref()
.and_then(|browser_info| browser_info.ip_address),
client_details: ClientDetails {
user_agent: payment_data
.request
.browser_info
.as_ref()
.and_then(|browser_info| browser_info.user_agent.clone()),
accept_language: payment_data.request.browser_info.as_ref().and_then(
|browser_info: &BrowserInformation| browser_info.language.clone(),
),
},
note: payment_data.description.clone(),
vendor_name: metadata.vendor_name,
payment_details: match payment_data.request.payment_method_data.as_ref() {
Some(AdditionalPaymentData::Card(card_info)) => Some(PaymentDetails {
credit_card_bin: card_info.card_isin.clone().map(Secret::new),
credit_card_number: card_info
.last4
.clone()
.map(|last_four| format!("XXXX-XXXX-XXXX-{last_four}"))
.map(Secret::new),
credit_card_company: card_info.card_network.clone(),
}),
Some(_) | None => None,
},
},
})
}
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct RiskifiedPaymentsResponse {
order: OrderResponse,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct OrderResponse {
id: String,
status: PaymentStatus,
description: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct RiskifiedFulfilmentResponse {
order: OrderFulfilmentResponse,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct OrderFulfilmentResponse {
id: String,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "lowercase")]
pub enum FulfilmentStatus {
Fulfilled,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "lowercase")]
pub enum PaymentStatus {
Captured,
Created,
Submitted,
Approved,
Declined,
Processing,
}
impl<F, T> TryFrom<ResponseRouterData<F, RiskifiedPaymentsResponse, T, FraudCheckResponseData>>
for RouterData<F, T, FraudCheckResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, RiskifiedPaymentsResponse, T, FraudCheckResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(FraudCheckResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order.id),
status: FraudCheckStatus::from(item.response.order.status),
connector_metadata: None,
score: None,
reason: item.response.order.description.map(serde_json::Value::from),
}),
..item.data
})
}
}
impl From<PaymentStatus> for FraudCheckStatus {
fn from(item: PaymentStatus) -> Self {
match item {
PaymentStatus::Approved => Self::Legit,
PaymentStatus::Declined => Self::Fraud,
_ => Self::Pending,
}
}
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct TransactionFailedRequest {
checkout: FailedTransactionData,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct FailedTransactionData {
id: String,
payment_details: Vec<DeclinedPaymentDetails>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct DeclinedPaymentDetails {
authorization_error: AuthorizationError,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct AuthorizationError {
#[serde(with = "common_utils::custom_serde::iso8601")]
created_at: PrimitiveDateTime,
error_code: Option<String>,
message: Option<String>,
}
impl TryFrom<&FrmTransactionRouterData> for TransactionFailedRequest {
type Error = Error;
fn try_from(item: &FrmTransactionRouterData) -> Result<Self, Self::Error> {
Ok(Self {
checkout: FailedTransactionData {
id: item.attempt_id.clone(),
payment_details: [DeclinedPaymentDetails {
authorization_error: AuthorizationError {
created_at: common_utils::date_time::now(),
error_code: item.request.error_code.clone(),
message: item.request.error_message.clone(),
},
}]
.to_vec(),
},
})
}
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct RiskifiedFailedTransactionResponse {
checkout: OrderResponse,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
#[serde(untagged)]
pub enum RiskifiedTransactionResponse {
FailedResponse(RiskifiedFailedTransactionResponse),
SuccessResponse(RiskifiedPaymentsResponse),
}
impl<F, T>
TryFrom<ResponseRouterData<F, RiskifiedFailedTransactionResponse, T, FraudCheckResponseData>>
for RouterData<F, T, FraudCheckResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, RiskifiedFailedTransactionResponse, T, FraudCheckResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(FraudCheckResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.checkout.id),
status: FraudCheckStatus::from(item.response.checkout.status),
connector_metadata: None,
score: None,
reason: item
.response
.checkout
.description
.map(serde_json::Value::from),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct TransactionSuccessRequest {
order: SuccessfulTransactionData,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct SuccessfulTransactionData {
id: String,
decision: TransactionDecisionData,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct TransactionDecisionData {
external_status: TransactionStatus,
reason: Option<String>,
amount: StringMajorUnit,
currency: Currency,
#[serde(with = "common_utils::custom_serde::iso8601")]
decided_at: PrimitiveDateTime,
payment_details: Vec<TransactionPaymentDetails>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct TransactionPaymentDetails {
authorization_id: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "lowercase")]
pub enum TransactionStatus {
Approved,
}
impl TryFrom<&RiskifiedRouterData<&FrmTransactionRouterData>> for TransactionSuccessRequest {
type Error = Error;
fn try_from(
item_data: &RiskifiedRouterData<&FrmTransactionRouterData>,
) -> Result<Self, Self::Error> {
let item = item_data.router_data.clone();
Ok(Self {
order: SuccessfulTransactionData {
id: item.attempt_id.clone(),
decision: TransactionDecisionData {
external_status: TransactionStatus::Approved,
reason: None,
amount: item_data.amount.clone(),
currency: item.request.get_currency()?,
decided_at: common_utils::date_time::now(),
payment_details: [TransactionPaymentDetails {
authorization_id: item.request.connector_transaction_id.clone(),
}]
.to_vec(),
},
},
})
}
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct RiskifiedFulfillmentRequest {
order: OrderFulfillment,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "lowercase")]
pub enum FulfillmentRequestStatus {
Success,
Cancelled,
Error,
Failure,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct OrderFulfillment {
id: String,
fulfillments: FulfilmentData,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct FulfilmentData {
fulfillment_id: String,
#[serde(with = "common_utils::custom_serde::iso8601")]
created_at: PrimitiveDateTime,
status: Option<FulfillmentRequestStatus>,
tracking_company: String,
tracking_number: String,
tracking_url: Option<String>,
}
impl TryFrom<&FrmFulfillmentRouterData> for RiskifiedFulfillmentRequest {
type Error = Error;
fn try_from(item: &FrmFulfillmentRouterData) -> Result<Self, Self::Error> {
let tracking_number = item
.request
.fulfillment_req
.tracking_numbers
.as_ref()
.and_then(|numbers| numbers.first().cloned())
.ok_or(ConnectorError::MissingRequiredField {
field_name: "tracking_number",
})?;
let tracking_url = item
.request
.fulfillment_req
.tracking_urls
.as_ref()
.and_then(|urls| urls.first().cloned().map(|url| url.to_string()));
Ok(Self {
order: OrderFulfillment {
id: item.attempt_id.clone(),
fulfillments: FulfilmentData {
fulfillment_id: item.payment_id.clone(),
created_at: common_utils::date_time::now(),
status: item
.request
.fulfillment_req
.fulfillment_status
.clone()
.and_then(get_fulfillment_status),
tracking_company: item
.request
.fulfillment_req
.tracking_company
.clone()
.ok_or(ConnectorError::MissingRequiredField {
field_name: "tracking_company",
})?,
tracking_number,
tracking_url,
},
},
})
}
}
impl
TryFrom<
ResponseRouterData<
Fulfillment,
RiskifiedFulfilmentResponse,
FraudCheckFulfillmentData,
FraudCheckResponseData,
>,
> for RouterData<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<
Fulfillment,
RiskifiedFulfilmentResponse,
FraudCheckFulfillmentData,
FraudCheckResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(FraudCheckResponseData::FulfillmentResponse {
order_id: item.response.order.id,
shipment_ids: Vec::new(),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct ErrorResponse {
pub error: ErrorData,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct ErrorData {
pub message: String,
}
impl TryFrom<&hyperswitch_domain_models::address::Address> for OrderAddress {
type Error = Error;
fn try_from(
address_info: &hyperswitch_domain_models::address::Address,
) -> Result<Self, Self::Error> {
let address = address_info
.clone()
.address
.ok_or(ConnectorError::MissingRequiredField {
field_name: "address",
})?;
Ok(Self {
first_name: address.first_name.clone(),
last_name: address.last_name.clone(),
address1: address.line1.clone(),
country_code: address.country,
city: address.city.clone(),
province: address.state.clone(),
zip: address.zip.clone(),
phone: address_info
.phone
.clone()
.and_then(|phone_data| phone_data.number),
})
}
}
fn get_fulfillment_status(status: FulfillmentStatus) -> Option<FulfillmentRequestStatus> {
match status {
FulfillmentStatus::COMPLETE => Some(FulfillmentRequestStatus::Success),
FulfillmentStatus::CANCELED => Some(FulfillmentRequestStatus::Cancelled),
FulfillmentStatus::PARTIAL | FulfillmentStatus::REPLACEMENT => None,
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RiskifiedWebhookBody {
pub id: String,
pub status: RiskifiedWebhookStatus,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum RiskifiedWebhookStatus {
Approved,
Declined,
}
impl From<RiskifiedWebhookStatus> for IncomingWebhookEvent {
fn from(value: RiskifiedWebhookStatus) -> Self {
match value {
RiskifiedWebhookStatus::Declined => Self::FrmRejected,
RiskifiedWebhookStatus::Approved => Self::FrmApproved,
}
}
}
|
crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 4,548
| null | null | null | null | null | null | null |
// Implementation: impl api::RefundExecute for for Razorpay
// File: crates/hyperswitch_connectors/src/connectors/razorpay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundExecute for for Razorpay
|
crates/hyperswitch_connectors/src/connectors/razorpay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Razorpay
|
api::RefundExecute for
| 0
| 0
| null | null |
// Struct: SavePaymentMethodDataResponse
// File: crates/router/src/core/payments/tokenization.rs
// Module: router
// Implementations: 0
pub struct SavePaymentMethodDataResponse
|
crates/router/src/core/payments/tokenization.rs
|
router
|
struct_definition
|
SavePaymentMethodDataResponse
| 0
|
[] | 41
| null | null | null | null | null | null | null |
// Function: new
// File: crates/hyperswitch_domain_models/src/payment_address.rs
// Module: hyperswitch_domain_models
pub fn new(
shipping: Option<Address>,
billing: Option<Address>,
payment_method_billing: Option<Address>,
should_unify_address: Option<bool>,
) -> Self
|
crates/hyperswitch_domain_models/src/payment_address.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 65
|
new
| null | null | null | null | null | null |
// Struct: SchemaParameters
// File: crates/router_derive/src/macros/schema/helpers.rs
// Module: router_derive
// Implementations: 0
pub struct SchemaParameters
|
crates/router_derive/src/macros/schema/helpers.rs
|
router_derive
|
struct_definition
|
SchemaParameters
| 0
|
[] | 38
| null | null | null | null | null | null | null |
// Function: validate_auth_and_metadata_type
// File: crates/router/src/core/connector_validation.rs
// Module: router
pub fn validate_auth_and_metadata_type(
&self,
) -> Result<(), error_stack::Report<errors::ApiErrorResponse>>
|
crates/router/src/core/connector_validation.rs
|
router
|
function_signature
| null | null | null | 53
|
validate_auth_and_metadata_type
| null | null | null | null | null | null |
// Implementation: impl api::PaymentVoid for for Shift4
// File: crates/hyperswitch_connectors/src/connectors/shift4.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Shift4
|
crates/hyperswitch_connectors/src/connectors/shift4.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Shift4
|
api::PaymentVoid for
| 0
| 0
| null | null |
// Struct: ChargebackRetrievalResponse
// File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ChargebackRetrievalResponse
|
crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ChargebackRetrievalResponse
| 0
|
[] | 55
| null | null | null | null | null | null | null |
// Struct: SecretBytesMut
// File: crates/masking/src/bytes.rs
// Module: masking
// Implementations: 3
// Traits: fmt::Debug, Drop
pub struct SecretBytesMut
|
crates/masking/src/bytes.rs
|
masking
|
struct_definition
|
SecretBytesMut
| 3
|
[
"fmt::Debug",
"Drop"
] | 44
| null | null | null | null | null | null | null |
// Struct: BillingConnectorAdditionalCardInfo
// File: crates/diesel_models/src/types.rs
// Module: diesel_models
// Implementations: 0
pub struct BillingConnectorAdditionalCardInfo
|
crates/diesel_models/src/types.rs
|
diesel_models
|
struct_definition
|
BillingConnectorAdditionalCardInfo
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Struct: WorldlineRouterData
// File: crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct WorldlineRouterData<T>
|
crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
WorldlineRouterData
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Struct: Memoization
// File: crates/hyperswitch_constraint_graph/src/types.rs
// Module: hyperswitch_constraint_graph
// Implementations: 4
// Traits: Default, Deref, DerefMut
pub struct Memoization<V: ValueNode>
|
crates/hyperswitch_constraint_graph/src/types.rs
|
hyperswitch_constraint_graph
|
struct_definition
|
Memoization
| 4
|
[
"Default",
"Deref",
"DerefMut"
] | 56
| null | null | null | null | null | null | null |
// Module Structure
// File: crates/hyperswitch_connectors/src/connectors/hipay.rs
// Module: hyperswitch_connectors
// Public submodules:
pub mod transformers;
|
crates/hyperswitch_connectors/src/connectors/hipay.rs
|
hyperswitch_connectors
|
module_structure
| null | null | null | 39
| null | null | null | null | null | 1
| 0
|
// File: crates/router/src/types/api/verify_connector/stripe.rs
// Module: router
use error_stack::ResultExt;
use router_env::env;
use super::VerifyConnector;
use crate::{
connector, core::errors, services, types,
types::api::verify_connector::BoxedConnectorIntegrationInterface,
};
#[async_trait::async_trait]
impl VerifyConnector for connector::Stripe {
async fn handle_payment_error_response<F, ResourceCommonData, Req, Resp>(
connector: BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>,
error_response: types::Response,
) -> errors::RouterResponse<()> {
let error = connector
.get_error_response(error_response, None)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
match (env::which(), error.code.as_str()) {
// In situations where an attempt is made to process a payment using a
// Stripe production key along with a test card (which verify_connector is using),
// Stripe will respond with a "card_declined" error. In production,
// when this scenario occurs we will send back an "Ok" response.
(env::Env::Production, "card_declined") => Ok(services::ApplicationResponse::StatusOk),
_ => Err(errors::ApiErrorResponse::InvalidRequestData {
message: error.reason.unwrap_or(error.message),
}
.into()),
}
}
}
|
crates/router/src/types/api/verify_connector/stripe.rs
|
router
|
full_file
| null | null | null | 299
| null | null | null | null | null | null | null |
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: Some(connector_meta),
network_txn_id: item.response.scheme_id.clone(),
connector_response_reference_id: Some(
item.response.reference.unwrap_or(item.response.id),
),
incremental_authorization_allowed: None,
charges: None,
};
Ok(Self {
status,
response: error_response.map_or_else(|| Ok(payments_response_data), Err),
..item.data
})
}
}
impl TryFrom<PaymentsSyncResponseRouterData<PaymentsResponse>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<PaymentsResponse>,
) -> Result<Self, Self::Error> {
let redirection_data = item
.response
.links
.redirect
.map(|href| RedirectForm::from((href.redirection_url, Method::Get)));
let checkout_meta: CheckoutMeta =
utils::to_connector_meta(item.data.request.connector_meta.clone())?;
let status = get_attempt_status_intent((item.response.status, checkout_meta.psync_flow));
let error_response = if status == AttemptStatus::Failure {
Some(ErrorResponse {
status_code: item.http_code,
code: item
.response
.response_code
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: item
.response
.response_summary
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: item.response.response_summary,
attempt_status: None,
connector_transaction_id: Some(item.response.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
None
};
let mandate_reference = if item.data.request.is_mandate_payment() {
item.response
.source
.as_ref()
.and_then(|src| src.id.clone())
.map(|id| MandateReference {
connector_mandate_id: Some(id),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: Some(item.response.id.clone()),
})
} else {
None
};
let additional_information =
convert_to_additional_payment_method_connector_response(item.response.source.as_ref())
.map(ConnectorResponseData::with_additional_payment_method_data);
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: item.response.scheme_id.clone(),
connector_response_reference_id: Some(
item.response.reference.unwrap_or(item.response.id),
),
incremental_authorization_allowed: None,
charges: None,
};
Ok(Self {
status,
response: error_response.map_or_else(|| Ok(payments_response_data), Err),
connector_response: additional_information,
..item.data
})
}
}
impl TryFrom<PaymentsSyncResponseRouterData<PaymentsResponseEnum>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<PaymentsResponseEnum>,
) -> Result<Self, Self::Error> {
let capture_sync_response_list = match item.response {
PaymentsResponseEnum::PaymentResponse(payments_response) => {
// for webhook consumption flow
utils::construct_captures_response_hashmap(vec![payments_response])?
}
PaymentsResponseEnum::ActionResponse(action_list) => {
// for captures sync
utils::construct_captures_response_hashmap(action_list)?
}
};
Ok(Self {
response: Ok(PaymentsResponseData::MultipleCaptureResponse {
capture_sync_response_list,
}),
..item.data
})
}
}
#[derive(Clone, Default, Debug, Eq, PartialEq, Serialize)]
pub struct PaymentVoidRequest {
reference: String,
}
#[derive(Clone, Default, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct PaymentVoidResponse {
#[serde(skip)]
pub(super) status: u16,
action_id: String,
reference: String,
scheme_id: Option<String>,
}
impl From<&PaymentVoidResponse> for AttemptStatus {
fn from(item: &PaymentVoidResponse) -> Self {
if item.status == 202 {
Self::Voided
} else {
Self::VoidFailed
}
}
}
impl TryFrom<PaymentsCancelResponseRouterData<PaymentVoidResponse>> for PaymentsCancelRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<PaymentVoidResponse>,
) -> Result<Self, Self::Error> {
let response = &item.response;
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.action_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: item.response.scheme_id.clone(),
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
status: response.into(),
..item.data
})
}
}
impl TryFrom<&PaymentsCancelRouterData> for PaymentVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
Ok(Self {
reference: item.request.connector_transaction_id.clone(),
})
}
}
#[derive(Debug, Serialize)]
pub enum CaptureType {
Final,
NonFinal,
}
#[derive(Debug, Serialize)]
pub struct PaymentCaptureRequest {
pub amount: Option<MinorUnit>,
pub capture_type: Option<CaptureType>,
pub processing_channel_id: Secret<String>,
pub reference: Option<String>,
}
impl TryFrom<&CheckoutRouterData<&PaymentsCaptureRouterData>> for PaymentCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CheckoutRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let connector_auth = &item.router_data.connector_auth_type;
let auth_type: CheckoutAuthType = connector_auth.try_into()?;
let processing_channel_id = auth_type.processing_channel_id;
let capture_type = if item.router_data.request.is_multiple_capture() {
CaptureType::NonFinal
} else {
CaptureType::Final
};
let reference = item
.router_data
.request
.multiple_capture_data
.as_ref()
.map(|multiple_capture_data| multiple_capture_data.capture_reference.clone());
Ok(Self {
amount: Some(item.amount.to_owned()),
capture_type: Some(capture_type),
processing_channel_id,
reference, // hyperswitch's reference for this capture
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaymentCaptureResponse {
pub action_id: String,
pub reference: Option<String>,
pub scheme_id: Option<String>,
}
impl TryFrom<PaymentsCaptureResponseRouterData<PaymentCaptureResponse>>
for PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<PaymentCaptureResponse>,
) -> Result<Self, Self::Error> {
let connector_meta = serde_json::json!(CheckoutMeta {
psync_flow: CheckoutPaymentIntent::Capture,
});
let (status, amount_captured) = if item.http_code == 202 {
(
AttemptStatus::Charged,
Some(item.data.request.amount_to_capture),
)
} else {
(AttemptStatus::Pending, None)
};
// if multiple capture request, return capture action_id so that it will be updated in the captures table.
// else return previous connector_transaction_id.
let resource_id = if item.data.request.is_multiple_capture() {
item.response.action_id
} else {
item.data.request.connector_transaction_id.to_owned()
};
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(resource_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(connector_meta),
network_txn_id: item.response.scheme_id.clone(),
connector_response_reference_id: item.response.reference,
incremental_authorization_allowed: None,
charges: None,
}),
status,
amount_captured,
..item.data
})
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RefundRequest {
amount: Option<MinorUnit>,
reference: String,
}
impl<F> TryFrom<&CheckoutRouterData<&RefundsRouterData<F>>> for RefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &CheckoutRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let reference = item.router_data.request.refund_id.clone();
Ok(Self {
amount: Some(item.amount.to_owned()),
reference,
})
}
}
#[allow(dead_code)]
#[derive(Deserialize, Debug, Serialize)]
pub struct RefundResponse {
action_id: String,
reference: String,
}
#[derive(Deserialize)]
pub struct CheckoutRefundResponse {
pub(super) status: u16,
pub(super) response: RefundResponse,
}
impl From<&CheckoutRefundResponse> for enums::RefundStatus {
fn from(item: &CheckoutRefundResponse) -> Self {
if item.status == 202 {
Self::Success
} else {
Self::Failure
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, CheckoutRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, CheckoutRefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(&item.response);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.response.action_id.clone(),
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, CheckoutRefundResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, CheckoutRefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(&item.response);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.response.action_id.clone(),
refund_status,
}),
..item.data
})
}
}
#[derive(Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct CheckoutErrorResponse {
pub request_id: Option<String>,
pub error_type: Option<String>,
pub error_codes: Option<Vec<String>>,
}
#[derive(Deserialize, Debug, PartialEq, Serialize)]
pub enum ActionType {
Authorization,
Void,
Capture,
Refund,
Payout,
Return,
#[serde(rename = "Card Verification")]
CardVerification,
}
#[derive(Deserialize, Debug, Serialize)]
pub struct ActionResponse {
#[serde(rename = "id")]
pub action_id: String,
pub amount: MinorUnit,
#[serde(rename = "type")]
pub action_type: ActionType,
pub approved: Option<bool>,
pub reference: Option<String>,
}
impl From<&ActionResponse> for enums::RefundStatus {
fn from(item: &ActionResponse) -> Self {
match item.approved {
Some(true) => Self::Success,
Some(false) => Self::Failure,
None => Self::Pending,
}
}
}
impl utils::MultipleCaptureSyncResponse for ActionResponse {
fn get_connector_capture_id(&self) -> String {
self.action_id.clone()
}
fn get_capture_attempt_status(&self) -> AttemptStatus {
match self.approved {
Some(true) => AttemptStatus::Charged,
Some(false) => AttemptStatus::Failure,
None => AttemptStatus::Pending,
}
}
fn get_connector_reference_id(&self) -> Option<String> {
self.reference.clone()
}
fn is_capture_response(&self) -> bool {
self.action_type == ActionType::Capture
}
fn get_amount_captured(&self) -> Result<Option<MinorUnit>, error_stack::Report<ParsingError>> {
Ok(Some(self.amount))
}
}
impl utils::MultipleCaptureSyncResponse for Box<PaymentsResponse> {
fn get_connector_capture_id(&self) -> String {
self.action_id.clone().unwrap_or("".into())
}
fn get_capture_attempt_status(&self) -> AttemptStatus {
get_attempt_status_bal((self.status.clone(), self.balances.clone()))
}
fn get_connector_reference_id(&self) -> Option<String> {
self.reference.clone()
}
fn is_capture_response(&self) -> bool {
self.status == CheckoutPaymentStatus::Captured
}
fn get_amount_captured(&self) -> Result<Option<MinorUnit>, error_stack::Report<ParsingError>> {
Ok(self.amount)
}
}
#[derive(Debug, Clone, serde::Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CheckoutRedirectResponseStatus {
Success,
Failure,
}
#[derive(Debug, Clone, serde::Deserialize, Eq, PartialEq)]
pub struct CheckoutRedirectResponse {
pub status: Option<CheckoutRedirectResponseStatus>,
#[serde(rename = "cko-session-id")]
pub cko_session_id: Option<String>,
}
impl TryFrom<RefundsResponseRouterData<Execute, &ActionResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, &ActionResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.action_id.clone(),
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, &ActionResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, &ActionResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.action_id.clone(),
refund_status,
}),
..item.data
})
}
}
impl From<CheckoutRedirectResponseStatus> for AttemptStatus {
fn from(item: CheckoutRedirectResponseStatus) -> Self {
match item {
CheckoutRedirectResponseStatus::Success => Self::AuthenticationSuccessful,
CheckoutRedirectResponseStatus::Failure => Self::Failure,
}
}
}
pub fn is_refund_event(event_code: &CheckoutWebhookEventType) -> bool {
matches!(
event_code,
CheckoutWebhookEventType::PaymentRefunded | CheckoutWebhookEventType::PaymentRefundDeclined
)
}
pub fn is_chargeback_event(event_code: &CheckoutWebhookEventType) -> bool {
matches!(
event_code,
CheckoutWebhookEventType::DisputeReceived
| CheckoutWebhookEventType::DisputeExpired
| CheckoutWebhookEventType::DisputeAccepted
| CheckoutWebhookEventType::DisputeCanceled
| CheckoutWebhookEventType::DisputeEvidenceSubmitted
| CheckoutWebhookEventType::DisputeEvidenceAcknowledgedByScheme
| CheckoutWebhookEventType::DisputeEvidenceRequired
| CheckoutWebhookEventType::DisputeArbitrationLost
| CheckoutWebhookEventType::DisputeArbitrationWon
| CheckoutWebhookEventType::DisputeWon
| CheckoutWebhookEventType::DisputeLost
)
}
#[derive(Debug, Deserialize, strum::Display, Clone)]
#[serde(rename_all = "snake_case")]
pub enum CheckoutWebhookEventType {
AuthenticationStarted,
AuthenticationApproved,
AuthenticationAttempted,
AuthenticationExpired,
AuthenticationFailed,
PaymentApproved,
PaymentCaptured,
PaymentDeclined,
PaymentRefunded,
PaymentRefundDeclined,
PaymentAuthenticationFailed,
PaymentCanceled,
PaymentCaptureDeclined,
PaymentVoided,
DisputeReceived,
DisputeExpired,
DisputeAccepted,
DisputeCanceled,
DisputeEvidenceSubmitted,
DisputeEvidenceAcknowledgedByScheme,
DisputeEvidenceRequired,
DisputeArbitrationLost,
DisputeArbitrationWon,
DisputeWon,
DisputeLost,
#[serde(other)]
Unknown,
}
#[derive(Debug, Deserialize)]
pub struct CheckoutWebhookEventTypeBody {
#[serde(rename = "type")]
pub transaction_type: CheckoutWebhookEventType,
}
#[derive(Debug, Deserialize)]
pub struct CheckoutWebhookData {
pub id: String,
pub payment_id: Option<String>,
pub action_id: Option<String>,
pub reference: Option<String>,
pub amount: MinorUnit,
pub balances: Option<Balances>,
pub response_code: Option<String>,
pub response_summary: Option<String>,
pub currency: String,
pub processed_on: Option<String>,
pub approved: Option<bool>,
}
#[derive(Debug, Deserialize)]
pub struct CheckoutWebhookBody {
#[serde(rename = "type")]
pub transaction_type: CheckoutWebhookEventType,
pub data: CheckoutWebhookData,
#[serde(rename = "_links")]
pub links: Links,
pub source: Option<Source>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CheckoutDisputeWebhookData {
pub id: String,
pub payment_id: Option<String>,
pub action_id: Option<String>,
pub amount: MinorUnit,
pub currency: enums::Currency,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub evidence_required_by: Option<PrimitiveDateTime>,
pub reason_code: Option<String>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub date: Option<PrimitiveDateTime>,
}
#[derive(Debug, Deserialize)]
pub struct CheckoutDisputeWebhookBody {
#[serde(rename = "type")]
pub transaction_type: CheckoutDisputeTransactionType,
pub data: CheckoutDisputeWebhookData,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub created_on: Option<PrimitiveDateTime>,
}
#[derive(Debug, Deserialize, strum::Display, Clone)]
#[serde(rename_all = "snake_case")]
pub enum CheckoutDisputeTransactionType {
DisputeReceived,
DisputeExpired,
DisputeAccepted,
DisputeCanceled,
DisputeEvidenceSubmitted,
DisputeEvidenceAcknowledgedByScheme,
DisputeEvidenceRequired,
DisputeArbitrationLost,
DisputeArbitrationWon,
DisputeWon,
DisputeLost,
}
impl From<CheckoutWebhookEventType> for api_models::webhooks::IncomingWebhookEvent {
fn from(transaction_type: CheckoutWebhookEventType) -> Self {
match transaction_type {
CheckoutWebhookEventType::AuthenticationStarted
| CheckoutWebhookEventType::AuthenticationApproved
| CheckoutWebhookEventType::AuthenticationAttempted => Self::EventNotSupported,
CheckoutWebhookEventType::AuthenticationExpired
| CheckoutWebhookEventType::AuthenticationFailed
| CheckoutWebhookEventType::PaymentAuthenticationFailed => {
Self::PaymentIntentAuthorizationFailure
}
CheckoutWebhookEventType::PaymentApproved => Self::EventNotSupported,
CheckoutWebhookEventType::PaymentCaptured => Self::PaymentIntentSuccess,
CheckoutWebhookEventType::PaymentDeclined => Self::PaymentIntentFailure,
CheckoutWebhookEventType::PaymentRefunded => Self::RefundSuccess,
CheckoutWebhookEventType::PaymentRefundDeclined => Self::RefundFailure,
CheckoutWebhookEventType::PaymentCanceled => Self::PaymentIntentCancelFailure,
CheckoutWebhookEventType::PaymentCaptureDeclined => Self::PaymentIntentCaptureFailure,
CheckoutWebhookEventType::PaymentVoided => Self::PaymentIntentCancelled,
CheckoutWebhookEventType::DisputeReceived
| CheckoutWebhookEventType::DisputeEvidenceRequired => Self::DisputeOpened,
CheckoutWebhookEventType::DisputeExpired => Self::DisputeExpired,
CheckoutWebhookEventType::DisputeAccepted => Self::DisputeAccepted,
CheckoutWebhookEventType::DisputeCanceled => Self::DisputeCancelled,
CheckoutWebhookEventType::DisputeEvidenceSubmitted
| CheckoutWebhookEventType::DisputeEvidenceAcknowledgedByScheme => {
Self::DisputeChallenged
}
CheckoutWebhookEventType::DisputeWon
| CheckoutWebhookEventType::DisputeArbitrationWon => Self::DisputeWon,
CheckoutWebhookEventType::DisputeLost
| CheckoutWebhookEventType::DisputeArbitrationLost => Self::DisputeLost,
CheckoutWebhookEventType::Unknown => Self::EventNotSupported,
}
}
}
impl From<CheckoutDisputeTransactionType> for api_models::enums::DisputeStage {
fn from(code: CheckoutDisputeTransactionType) -> Self {
match code {
CheckoutDisputeTransactionType::DisputeArbitrationLost
| CheckoutDisputeTransactionType::DisputeArbitrationWon => Self::PreArbitration,
CheckoutDisputeTransactionType::DisputeReceived
| CheckoutDisputeTransactionType::DisputeExpired
| CheckoutDisputeTransactionType::DisputeAccepted
| CheckoutDisputeTransactionType::DisputeCanceled
| CheckoutDisputeTransactionType::DisputeEvidenceSubmitted
| CheckoutDisputeTransactionType::DisputeEvidenceAcknowledgedByScheme
| CheckoutDisputeTransactionType::DisputeEvidenceRequired
| CheckoutDisputeTransactionType::DisputeWon
| CheckoutDisputeTransactionType::DisputeLost => Self::Dispute,
}
}
}
#[derive(Debug, Deserialize)]
pub struct CheckoutWebhookObjectResource {
pub data: serde_json::Value,
}
pub fn construct_file_upload_request(
file_upload_router_data: UploadFileRouterData,
) -> CustomResult<reqwest::multipart::Form, errors::ConnectorError> {
let request = file_upload_router_data.request;
let mut multipart = reqwest::multipart::Form::new();
multipart = multipart.text("purpose", "dispute_evidence");
let file_data = reqwest::multipart::Part::bytes(request.file)
.file_name(format!(
"{}.{}",
request.file_key,
request
.file_type
.as_ref()
.split('/')
.next_back()
.unwrap_or_default()
))
.mime_str(request.file_type.as_ref())
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failure in constructing file data")?;
multipart = multipart.part("file", file_data);
Ok(multipart)
}
#[derive(Debug, Deserialize, Serialize)]
pub struct FileUploadResponse {
#[serde(rename = "id")]
pub file_id: String,
}
#[derive(Default, Debug, Serialize)]
pub struct Evidence {
pub proof_of_delivery_or_service_file: Option<String>,
pub invoice_or_receipt_file: Option<String>,
pub invoice_showing_distinct_transactions_file: Option<String>,
pub customer_communication_file: Option<String>,
pub refund_or_cancellation_policy_file: Option<String>,
pub recurring_transaction_agreement_file: Option<String>,
pub additional_evidence_file: Option<String>,
}
impl TryFrom<&webhooks::IncomingWebhookRequestDetails<'_>> for PaymentsResponse {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> Result<Self, Self::Error> {
let details: CheckoutWebhookBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let data = details.data;
let psync_struct = Self {
id: data.payment_id.unwrap_or(data.id),
amount: Some(data.amount),
status: CheckoutPaymentStatus::try_from(details.transaction_type)?,
links: details.links,
balances: data.balances,
reference: data.reference,
response_code: data.response_code,
response_summary: data.response_summary,
action_id: data.action_id,
currency: Some(data.currency),
processed_on: data.processed_on,
approved: data.approved,
source: Some(Source {
id: details.source.clone().and_then(|src| src.id),
avs_check: details.source.clone().and_then(|src| src.avs_check),
cvv_check: details.source.clone().and_then(|src| src.cvv_check),
}),
scheme_id: None,
processing: None,
};
Ok(psync_struct)
}
}
impl TryFrom<&webhooks::IncomingWebhookRequestDetails<'_>> for RefundResponse {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> Result<Self, Self::Error> {
let details: CheckoutWebhookBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let data = details.data;
let refund_struct = Self {
action_id: data
.action_id
.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?,
reference: data
.reference
.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?,
};
Ok(refund_struct)
}
}
impl TryFrom<&SubmitEvidenceRouterData> for Evidence {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SubmitEvidenceRouterData) -> Result<Self, Self::Error> {
let submit_evidence_request_data = item.request.clone();
Ok(Self {
proof_of_delivery_or_service_file: submit_evidence_request_data
.shipping_documentation_provider_file_id,
invoice_or_receipt_file: submit_evidence_request_data.receipt_provider_file_id,
invoice_showing_distinct_transactions_file: submit_evidence_request_data
.invoice_showing_distinct_transactions_provider_file_id,
customer_communication_file: submit_evidence_request_data
.customer_communication_provider_file_id,
refund_or_cancellation_policy_file: submit_evidence_request_data
.refund_policy_provider_file_id,
recurring_transaction_agreement_file: submit_evidence_request_data
.recurring_transaction_agreement_provider_file_id,
additional_evidence_file: submit_evidence_request_data
.uncategorized_file_provider_file_id,
})
}
}
impl From<String> for utils::ErrorCodeAndMessage {
fn from(error: String) -> Self {
Self {
error_code: error.clone(),
error_message: error,
}
}
}
fn convert_to_additional_payment_method_connector_response(
source: Option<&Source>,
) -> Option<AdditionalPaymentMethodConnectorResponse> {
source.map(|code| {
let payment_checks = serde_json::json!({
"avs_result": code.avs_check,
"card_validation_result": code.cvv_check,
});
AdditionalPaymentMethodConnectorResponse::Card {
authentication_data: None,
payment_checks: Some(payment_checks),
card_network: None,
domestic_network: None,
}
})
}
|
crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs#chunk1
|
hyperswitch_connectors
|
chunk
| null | null | null | 6,130
| null | null | null | null | null | null | null |
// Struct: NoonApplePayTokenData
// File: crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct NoonApplePayTokenData
|
crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
NoonApplePayTokenData
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentToken for for Fiservemea
// File: crates/hyperswitch_connectors/src/connectors/fiservemea.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentToken for for Fiservemea
|
crates/hyperswitch_connectors/src/connectors/fiservemea.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 66
| null |
Fiservemea
|
api::PaymentToken for
| 0
| 0
| null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.