hash
stringlengths 40
40
| date
stringdate 2022-11-17 13:04:47
2025-03-21 17:04:41
| author
stringclasses 141
values | commit_message
stringlengths 22
166
| is_merge
bool 1
class | git_diff
stringlengths 238
9.63M
| type
stringclasses 17
values | masked_commit_message
stringlengths 6
143
|
|---|---|---|---|---|---|---|---|
bcb3450445807a12cde70333bf24593ed57091b5
|
2024-07-11 18:08:08
|
Sandeep Kumar
|
fix(analytics): Resolve issues for payment-intent v2 analytics (#5283)
| false
|
diff --git a/crates/api_models/src/analytics/payment_intents.rs b/crates/api_models/src/analytics/payment_intents.rs
index 232c1719047..e7affa94e08 100644
--- a/crates/api_models/src/analytics/payment_intents.rs
+++ b/crates/api_models/src/analytics/payment_intents.rs
@@ -10,6 +10,7 @@ use crate::enums::{Currency, IntentStatus};
pub struct PaymentIntentFilters {
#[serde(default)]
pub status: Vec<IntentStatus>,
+ #[serde(default)]
pub currency: Vec<Currency>,
}
|
fix
|
Resolve issues for payment-intent v2 analytics (#5283)
|
b54a3f9142388a3d870406c54fd1d314c7c7748d
|
2025-02-05 19:12:35
|
sweta-kumari-sharma
|
feat: Add Support for Amazon Pay Redirect and Amazon Pay payment via Stripe (#7056)
| false
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 7556a4e7765..a8abc3fb7d0 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -3118,6 +3118,9 @@
"AliPayRedirection": {
"type": "object"
},
+ "AmazonPayRedirectData": {
+ "type": "object"
+ },
"AmountDetails": {
"type": "object",
"required": [
@@ -14273,6 +14276,7 @@
"ali_pay",
"ali_pay_hk",
"alma",
+ "amazon_pay",
"apple_pay",
"atome",
"bacs",
@@ -20862,6 +20866,17 @@
}
}
},
+ {
+ "type": "object",
+ "required": [
+ "amazon_pay_redirect"
+ ],
+ "properties": {
+ "amazon_pay_redirect": {
+ "$ref": "#/components/schemas/AmazonPayRedirectData"
+ }
+ }
+ },
{
"type": "object",
"required": [
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json
index ea0a95c1d57..5bdaa5940c8 100644
--- a/api-reference/openapi_spec.json
+++ b/api-reference/openapi_spec.json
@@ -5882,6 +5882,9 @@
"AliPayRedirection": {
"type": "object"
},
+ "AmazonPayRedirectData": {
+ "type": "object"
+ },
"AmountFilter": {
"type": "object",
"properties": {
@@ -17247,6 +17250,7 @@
"ali_pay",
"ali_pay_hk",
"alma",
+ "amazon_pay",
"apple_pay",
"atome",
"bacs",
@@ -26182,6 +26186,17 @@
}
}
},
+ {
+ "type": "object",
+ "required": [
+ "amazon_pay_redirect"
+ ],
+ "properties": {
+ "amazon_pay_redirect": {
+ "$ref": "#/components/schemas/AmazonPayRedirectData"
+ }
+ }
+ },
{
"type": "object",
"required": [
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 4a1fa8b408e..ec281197eda 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -2362,6 +2362,7 @@ impl GetPaymentMethodType for WalletData {
match self {
Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay,
Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk,
+ Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay,
Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo,
Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay,
Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay,
@@ -3241,6 +3242,8 @@ pub enum WalletData {
AliPayRedirect(AliPayRedirection),
/// The wallet data for Ali Pay HK redirect
AliPayHkRedirect(AliPayHkRedirection),
+ /// The wallet data for Amazon Pay redirect
+ AmazonPayRedirect(AmazonPayRedirectData),
/// The wallet data for Momo redirect
MomoRedirect(MomoRedirection),
/// The wallet data for KakaoPay redirect
@@ -3324,6 +3327,7 @@ impl GetAddressFromPaymentMethodData for WalletData {
| Self::KakaoPayRedirect(_)
| Self::GoPayRedirect(_)
| Self::GcashRedirect(_)
+ | Self::AmazonPayRedirect(_)
| Self::ApplePay(_)
| Self::ApplePayRedirect(_)
| Self::ApplePayThirdPartySdk(_)
@@ -3481,6 +3485,9 @@ pub struct GooglePayWalletData {
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct ApplePayRedirectData {}
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+pub struct AmazonPayRedirectData {}
+
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct GooglePayRedirectData {}
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index d9d76dbc53e..0234fbea6d5 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -1557,6 +1557,7 @@ pub enum PaymentMethodType {
AliPay,
AliPayHk,
Alma,
+ AmazonPay,
ApplePay,
Atome,
Bacs,
diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs
index 7611ae127ee..d351f5c927e 100644
--- a/crates/common_enums/src/transformers.rs
+++ b/crates/common_enums/src/transformers.rs
@@ -1799,6 +1799,7 @@ impl From<PaymentMethodType> for PaymentMethod {
PaymentMethodType::AliPay => Self::Wallet,
PaymentMethodType::AliPayHk => Self::Wallet,
PaymentMethodType::Alma => Self::PayLater,
+ PaymentMethodType::AmazonPay => Self::Wallet,
PaymentMethodType::ApplePay => Self::Wallet,
PaymentMethodType::Bacs => Self::BankDebit,
PaymentMethodType::BancontactCard => Self::BankRedirect,
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index 190114fee3a..2b04ea8d1c2 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -3139,6 +3139,8 @@ merchant_secret="Source verification key"
payment_method_type = "sepa"
[[stripe.bank_transfer]]
payment_method_type = "multibanco"
+[[stripe.wallet]]
+ payment_method_type = "amazon_pay"
[[stripe.wallet]]
payment_method_type = "apple_pay"
[[stripe.wallet]]
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index f1745587a6e..b7108c63477 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -2290,6 +2290,8 @@ merchant_secret="Source verification key"
payment_method_type = "bacs"
[[stripe.bank_transfer]]
payment_method_type = "sepa"
+[[stripe.wallet]]
+ payment_method_type = "amazon_pay"
[[stripe.wallet]]
payment_method_type = "apple_pay"
[[stripe.wallet]]
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index 2a83d62ee9c..b886e7410a9 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -3081,6 +3081,8 @@ merchant_secret="Source verification key"
payment_method_type = "sepa"
[[stripe.bank_transfer]]
payment_method_type = "multibanco"
+[[stripe.wallet]]
+ payment_method_type = "amazon_pay"
[[stripe.wallet]]
payment_method_type = "apple_pay"
[[stripe.wallet]]
diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs
index 6c96070159b..6fb302641db 100644
--- a/crates/euclid/src/frontend/dir/enums.rs
+++ b/crates/euclid/src/frontend/dir/enums.rs
@@ -71,6 +71,7 @@ pub enum PayLaterType {
#[strum(serialize_all = "snake_case")]
pub enum WalletType {
GooglePay,
+ AmazonPay,
ApplePay,
Paypal,
AliPay,
diff --git a/crates/euclid/src/frontend/dir/lowering.rs b/crates/euclid/src/frontend/dir/lowering.rs
index 07ff2c4364e..04a029bd109 100644
--- a/crates/euclid/src/frontend/dir/lowering.rs
+++ b/crates/euclid/src/frontend/dir/lowering.rs
@@ -38,6 +38,7 @@ impl From<enums::WalletType> for global_enums::PaymentMethodType {
fn from(value: enums::WalletType) -> Self {
match value {
enums::WalletType::GooglePay => Self::GooglePay,
+ enums::WalletType::AmazonPay => Self::AmazonPay,
enums::WalletType::ApplePay => Self::ApplePay,
enums::WalletType::Paypal => Self::Paypal,
enums::WalletType::AliPay => Self::AliPay,
diff --git a/crates/euclid/src/frontend/dir/transformers.rs b/crates/euclid/src/frontend/dir/transformers.rs
index 914a9444918..1a3bb52e0fa 100644
--- a/crates/euclid/src/frontend/dir/transformers.rs
+++ b/crates/euclid/src/frontend/dir/transformers.rs
@@ -19,6 +19,7 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet
global_enums::PaymentMethodType::AfterpayClearpay => {
Ok(dirval!(PayLaterType = AfterpayClearpay))
}
+ global_enums::PaymentMethodType::AmazonPay => Ok(dirval!(WalletType = AmazonPay)),
global_enums::PaymentMethodType::GooglePay => Ok(dirval!(WalletType = GooglePay)),
global_enums::PaymentMethodType::ApplePay => Ok(dirval!(WalletType = ApplePay)),
global_enums::PaymentMethodType::Paypal => Ok(dirval!(WalletType = Paypal)),
diff --git a/crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs b/crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
index 45a7b577a86..8c5adefc613 100644
--- a/crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
@@ -337,6 +337,7 @@ fn get_wallet_details(
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
diff --git a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
index a0868d688eb..11ff53d439c 100644
--- a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
@@ -296,6 +296,7 @@ impl TryFrom<&SetupMandateRouterData> for BankOfAmericaPaymentsRequest {
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
@@ -1045,6 +1046,7 @@ impl TryFrom<&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>>
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
diff --git a/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
index 7970b1b1d42..809902fa2a2 100644
--- a/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
@@ -368,6 +368,7 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for Blues
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
diff --git a/crates/hyperswitch_connectors/src/connectors/boku/transformers.rs b/crates/hyperswitch_connectors/src/connectors/boku/transformers.rs
index da5f775489c..8bc7b3639b7 100644
--- a/crates/hyperswitch_connectors/src/connectors/boku/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/boku/transformers.rs
@@ -180,6 +180,7 @@ fn get_wallet_type(wallet_data: &WalletData) -> Result<String, errors::Connector
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
index b14ffc9c79e..5e18ee921b4 100644
--- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
@@ -253,6 +253,7 @@ impl TryFrom<&SetupMandateRouterData> for CybersourceZeroMandateRequest {
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
@@ -2066,6 +2067,7 @@ impl TryFrom<&CybersourceRouterData<&PaymentsAuthorizeRouterData>> for Cybersour
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
index 115079c7d00..e23cdd548cb 100644
--- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
@@ -508,6 +508,7 @@ impl TryFrom<&FiuuRouterData<&PaymentsAuthorizeRouterData>> for FiuuPaymentReque
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
diff --git a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
index 5d30146293c..36c83859be9 100644
--- a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
@@ -59,6 +59,7 @@ impl TryFrom<&GlobepayRouterData<&types::PaymentsAuthorizeRouterData>> for Globe
WalletData::WeChatPayQr(_) => GlobepayChannel::Wechat,
WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
diff --git a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs
index a60e8bdc79e..54aca37a76a 100644
--- a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs
@@ -492,6 +492,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
@@ -556,6 +557,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
@@ -715,6 +717,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
diff --git a/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
index 8d6dc42926b..21fa1ec3217 100644
--- a/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
@@ -705,6 +705,7 @@ fn get_wallet_details(
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
index c1ef6566e03..112d409d6e2 100644
--- a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
@@ -341,6 +341,7 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym
WalletDataPaymentMethod::AliPayQr(_)
| WalletDataPaymentMethod::AliPayRedirect(_)
| WalletDataPaymentMethod::AliPayHkRedirect(_)
+ | WalletDataPaymentMethod::AmazonPayRedirect(_)
| WalletDataPaymentMethod::MomoRedirect(_)
| WalletDataPaymentMethod::KakaoPayRedirect(_)
| WalletDataPaymentMethod::GoPayRedirect(_)
@@ -1586,6 +1587,7 @@ impl TryFrom<&SetupMandateRouterData> for NovalnetPaymentsRequest {
WalletDataPaymentMethod::AliPayQr(_)
| WalletDataPaymentMethod::AliPayRedirect(_)
| WalletDataPaymentMethod::AliPayHkRedirect(_)
+ | WalletDataPaymentMethod::AmazonPayRedirect(_)
| WalletDataPaymentMethod::MomoRedirect(_)
| WalletDataPaymentMethod::KakaoPayRedirect(_)
| WalletDataPaymentMethod::GoPayRedirect(_)
diff --git a/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs b/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
index 1973e622be1..5c5615aa945 100644
--- a/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
@@ -286,6 +286,7 @@ impl TryFrom<&WalletData> for Shift4PaymentMethod {
fn try_from(wallet_data: &WalletData) -> Result<Self, Self::Error> {
match wallet_data {
WalletData::AliPayRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
| WalletData::ApplePay(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::AliPayQr(_)
diff --git a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs
index ff3999aee64..6c47e5d58d4 100644
--- a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs
@@ -107,6 +107,7 @@ impl TryFrom<(&types::TokenizationRouterData, WalletData)> for SquareTokenReques
| WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
diff --git a/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs b/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
index 1a4d3ce8f9c..5eaf54065d7 100644
--- a/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
@@ -187,6 +187,7 @@ impl TryFrom<&SetupMandateRouterData> for WellsfargoZeroMandateRequest {
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
@@ -1248,6 +1249,7 @@ impl TryFrom<&WellsfargoRouterData<&PaymentsAuthorizeRouterData>> for Wellsfargo
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs
index e4656021a59..47a5d3b2b2b 100644
--- a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs
@@ -156,6 +156,7 @@ fn fetch_payment_instrument(
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
diff --git a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
index cc6795f157a..a9e21f9071c 100644
--- a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
@@ -487,6 +487,7 @@ impl
| WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index c69641ebd11..418c505cf52 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -2296,6 +2296,7 @@ pub enum PaymentMethodDataType {
AliPayQr,
AliPayRedirect,
AliPayHkRedirect,
+ AmazonPayRedirect,
MomoRedirect,
KakaoPayRedirect,
GoPayRedirect,
@@ -2415,6 +2416,7 @@ impl From<PaymentMethodData> for PaymentMethodDataType {
payment_method_data::WalletData::AliPayQr(_) => Self::AliPayQr,
payment_method_data::WalletData::AliPayRedirect(_) => Self::AliPayRedirect,
payment_method_data::WalletData::AliPayHkRedirect(_) => Self::AliPayHkRedirect,
+ payment_method_data::WalletData::AmazonPayRedirect(_) => Self::AmazonPayRedirect,
payment_method_data::WalletData::MomoRedirect(_) => Self::MomoRedirect,
payment_method_data::WalletData::KakaoPayRedirect(_) => Self::KakaoPayRedirect,
payment_method_data::WalletData::GoPayRedirect(_) => Self::GoPayRedirect,
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index dcf46964170..9e83810c9e0 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -1,6 +1,8 @@
use api_models::{
mandates, payment_methods,
- payments::{additional_info as payment_additional_types, ExtendedCardInfo},
+ payments::{
+ additional_info as payment_additional_types, AmazonPayRedirectData, ExtendedCardInfo,
+ },
};
use common_enums::enums as api_enums;
use common_utils::{
@@ -169,6 +171,7 @@ pub enum WalletData {
AliPayQr(Box<AliPayQr>),
AliPayRedirect(AliPayRedirection),
AliPayHkRedirect(AliPayHkRedirection),
+ AmazonPayRedirect(Box<AmazonPayRedirectData>),
MomoRedirect(MomoRedirection),
KakaoPayRedirect(KakaoPayRedirection),
GoPayRedirect(GoPayRedirection),
@@ -729,6 +732,9 @@ impl From<api_models::payments::WalletData> for WalletData {
api_models::payments::WalletData::AliPayHkRedirect(_) => {
Self::AliPayHkRedirect(AliPayHkRedirection {})
}
+ api_models::payments::WalletData::AmazonPayRedirect(_) => {
+ Self::AmazonPayRedirect(Box::new(AmazonPayRedirectData {}))
+ }
api_models::payments::WalletData::MomoRedirect(_) => {
Self::MomoRedirect(MomoRedirection {})
}
@@ -1518,6 +1524,7 @@ impl GetPaymentMethodType for WalletData {
match self {
Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay,
Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk,
+ Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay,
Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo,
Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay,
Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay,
diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs
index a3e1dfc6220..e224078493f 100644
--- a/crates/kgraph_utils/src/mca.rs
+++ b/crates/kgraph_utils/src/mca.rs
@@ -21,6 +21,7 @@ fn get_dir_value_payment_method(
from: api_enums::PaymentMethodType,
) -> Result<dir::DirValue, KgraphError> {
match from {
+ api_enums::PaymentMethodType::AmazonPay => Ok(dirval!(WalletType = AmazonPay)),
api_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)),
api_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)),
api_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)),
diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs
index 89b8c5a34ad..adfe5820866 100644
--- a/crates/kgraph_utils/src/transformers.rs
+++ b/crates/kgraph_utils/src/transformers.rs
@@ -130,6 +130,7 @@ impl IntoDirValue for api_enums::FutureUsage {
impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) {
fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> {
match self.0 {
+ api_enums::PaymentMethodType::AmazonPay => Ok(dirval!(WalletType = AmazonPay)),
api_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)),
api_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)),
api_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)),
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index de358f79332..7102c23d17e 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -479,6 +479,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::AchTransfer,
api_models::payments::MultibancoTransferInstructions,
api_models::payments::DokuBankTransferInstructions,
+ api_models::payments::AmazonPayRedirectData,
api_models::payments::ApplePayRedirectData,
api_models::payments::ApplePayThirdPartySdkData,
api_models::payments::GooglePayRedirectData,
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 1078d8080ca..ac88908fbd2 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -440,6 +440,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::AchTransfer,
api_models::payments::MultibancoTransferInstructions,
api_models::payments::DokuBankTransferInstructions,
+ api_models::payments::AmazonPayRedirectData,
api_models::payments::ApplePayRedirectData,
api_models::payments::ApplePayThirdPartySdkData,
api_models::payments::GooglePayRedirectData,
diff --git a/crates/router/src/configs/defaults/payment_connector_required_fields.rs b/crates/router/src/configs/defaults/payment_connector_required_fields.rs
index 644c213acd8..421f430e74e 100644
--- a/crates/router/src/configs/defaults/payment_connector_required_fields.rs
+++ b/crates/router/src/configs/defaults/payment_connector_required_fields.rs
@@ -9488,6 +9488,21 @@ impl Default for settings::RequiredFields {
]),
},
),
+ (
+ enums::PaymentMethodType::AmazonPay,
+ ConnectorFields {
+ fields: HashMap::from([
+ (
+ enums::Connector::Stripe,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::new(),
+ }
+ ),
+ ]),
+ },
+ ),
(
enums::PaymentMethodType::Cashapp,
ConnectorFields {
diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs
index 3e25799c02e..11d34e55b7b 100644
--- a/crates/router/src/connector/aci/transformers.rs
+++ b/crates/router/src/connector/aci/transformers.rs
@@ -108,6 +108,7 @@ impl TryFrom<(&domain::WalletData, &types::PaymentsAuthorizeRouterData)> for Pay
account_id: None,
})),
domain::WalletData::AliPayHkRedirect(_)
+ | domain::WalletData::AmazonPayRedirect(_)
| domain::WalletData::MomoRedirect(_)
| domain::WalletData::KakaoPayRedirect(_)
| domain::WalletData::GoPayRedirect(_)
diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs
index d6f6fdc8f0f..91e65759573 100644
--- a/crates/router/src/connector/adyen.rs
+++ b/crates/router/src/connector/adyen.rs
@@ -215,7 +215,8 @@ impl ConnectorValidation for Adyen {
)
}
},
- PaymentMethodType::CardRedirect
+ PaymentMethodType::AmazonPay
+ | PaymentMethodType::CardRedirect
| PaymentMethodType::DirectCarrierBilling
| PaymentMethodType::Fps
| PaymentMethodType::DuitNow
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 394652c33e1..adb1a795f70 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -2211,6 +2211,7 @@ impl TryFrom<(&domain::WalletData, &types::PaymentsAuthorizeRouterData)>
domain::WalletData::DanaRedirect { .. } => Ok(AdyenPaymentMethod::Dana),
domain::WalletData::SwishQr(_) => Ok(AdyenPaymentMethod::Swish),
domain::WalletData::AliPayQr(_)
+ | domain::WalletData::AmazonPayRedirect(_)
| domain::WalletData::ApplePayRedirect(_)
| domain::WalletData::ApplePayThirdPartySdk(_)
| domain::WalletData::GooglePayRedirect(_)
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index c430191a1ec..276ea6bf77b 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -1809,6 +1809,7 @@ fn get_wallet_data(
domain::WalletData::AliPayQr(_)
| domain::WalletData::AliPayRedirect(_)
| domain::WalletData::AliPayHkRedirect(_)
+ | domain::WalletData::AmazonPayRedirect(_)
| domain::WalletData::MomoRedirect(_)
| domain::WalletData::KakaoPayRedirect(_)
| domain::WalletData::GoPayRedirect(_)
diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs
index bb38ef74836..321a8cec765 100644
--- a/crates/router/src/connector/checkout/transformers.rs
+++ b/crates/router/src/connector/checkout/transformers.rs
@@ -93,6 +93,7 @@ impl TryFrom<&types::TokenizationRouterData> for TokenRequest {
domain::WalletData::AliPayQr(_)
| domain::WalletData::AliPayRedirect(_)
| domain::WalletData::AliPayHkRedirect(_)
+ | domain::WalletData::AmazonPayRedirect(_)
| domain::WalletData::MomoRedirect(_)
| domain::WalletData::KakaoPayRedirect(_)
| domain::WalletData::GoPayRedirect(_)
@@ -347,6 +348,7 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme
domain::WalletData::AliPayQr(_)
| domain::WalletData::AliPayRedirect(_)
| domain::WalletData::AliPayHkRedirect(_)
+ | domain::WalletData::AmazonPayRedirect(_)
| domain::WalletData::MomoRedirect(_)
| domain::WalletData::KakaoPayRedirect(_)
| domain::WalletData::GoPayRedirect(_)
diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs
index 4e54311a89a..6fbc48a66a0 100644
--- a/crates/router/src/connector/klarna.rs
+++ b/crates/router/src/connector/klarna.rs
@@ -577,6 +577,7 @@ impl
| common_enums::PaymentMethodType::AliPay
| common_enums::PaymentMethodType::AliPayHk
| common_enums::PaymentMethodType::Alma
+ | common_enums::PaymentMethodType::AmazonPay
| common_enums::PaymentMethodType::ApplePay
| common_enums::PaymentMethodType::Atome
| common_enums::PaymentMethodType::Bacs
@@ -693,6 +694,7 @@ impl
| common_enums::PaymentMethodType::AliPay
| common_enums::PaymentMethodType::AliPayHk
| common_enums::PaymentMethodType::Alma
+ | common_enums::PaymentMethodType::AmazonPay
| common_enums::PaymentMethodType::ApplePay
| common_enums::PaymentMethodType::Atome
| common_enums::PaymentMethodType::Bacs
diff --git a/crates/router/src/connector/mifinity/transformers.rs b/crates/router/src/connector/mifinity/transformers.rs
index 1e2c420c767..f913077d1dc 100644
--- a/crates/router/src/connector/mifinity/transformers.rs
+++ b/crates/router/src/connector/mifinity/transformers.rs
@@ -154,6 +154,7 @@ impl TryFrom<&MifinityRouterData<&types::PaymentsAuthorizeRouterData>> for Mifin
domain::WalletData::AliPayQr(_)
| domain::WalletData::AliPayRedirect(_)
| domain::WalletData::AliPayHkRedirect(_)
+ | domain::WalletData::AmazonPayRedirect(_)
| domain::WalletData::MomoRedirect(_)
| domain::WalletData::KakaoPayRedirect(_)
| domain::WalletData::GoPayRedirect(_)
diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs
index 4c33f020017..19f03cb1b2c 100644
--- a/crates/router/src/connector/nmi/transformers.rs
+++ b/crates/router/src/connector/nmi/transformers.rs
@@ -545,6 +545,7 @@ impl
domain::WalletData::AliPayQr(_)
| domain::WalletData::AliPayRedirect(_)
| domain::WalletData::AliPayHkRedirect(_)
+ | domain::WalletData::AmazonPayRedirect(_)
| domain::WalletData::MomoRedirect(_)
| domain::WalletData::KakaoPayRedirect(_)
| domain::WalletData::GoPayRedirect(_)
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs
index b96283247b4..5816aaa9295 100644
--- a/crates/router/src/connector/noon/transformers.rs
+++ b/crates/router/src/connector/noon/transformers.rs
@@ -314,6 +314,7 @@ impl TryFrom<&NoonRouterData<&types::PaymentsAuthorizeRouterData>> for NoonPayme
domain::WalletData::AliPayQr(_)
| domain::WalletData::AliPayRedirect(_)
| domain::WalletData::AliPayHkRedirect(_)
+ | domain::WalletData::AmazonPayRedirect(_)
| domain::WalletData::MomoRedirect(_)
| domain::WalletData::KakaoPayRedirect(_)
| domain::WalletData::GoPayRedirect(_)
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index c98a0647778..eea700f695c 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -902,6 +902,7 @@ where
domain::WalletData::AliPayQr(_)
| domain::WalletData::AliPayRedirect(_)
| domain::WalletData::AliPayHkRedirect(_)
+ | domain::WalletData::AmazonPayRedirect(_)
| domain::WalletData::MomoRedirect(_)
| domain::WalletData::KakaoPayRedirect(_)
| domain::WalletData::GoPayRedirect(_)
diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs
index 7e50f7f40e6..c13730529e2 100644
--- a/crates/router/src/connector/payme/transformers.rs
+++ b/crates/router/src/connector/payme/transformers.rs
@@ -393,6 +393,7 @@ impl TryFrom<&PaymentMethodData> for SalePaymentMethod {
domain::WalletData::AliPayQr(_)
| domain::WalletData::AliPayRedirect(_)
| domain::WalletData::AliPayHkRedirect(_)
+ | domain::WalletData::AmazonPayRedirect(_)
| domain::WalletData::MomoRedirect(_)
| domain::WalletData::KakaoPayRedirect(_)
| domain::WalletData::GoPayRedirect(_)
diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs
index 8f739792a0c..18739851ae8 100644
--- a/crates/router/src/connector/paypal/transformers.rs
+++ b/crates/router/src/connector/paypal/transformers.rs
@@ -1044,6 +1044,7 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP
domain::WalletData::AliPayQr(_)
| domain::WalletData::AliPayRedirect(_)
| domain::WalletData::AliPayHkRedirect(_)
+ | domain::WalletData::AmazonPayRedirect(_)
| domain::WalletData::MomoRedirect(_)
| domain::WalletData::KakaoPayRedirect(_)
| domain::WalletData::GoPayRedirect(_)
@@ -1134,6 +1135,7 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP
| enums::PaymentMethodType::AliPay
| enums::PaymentMethodType::AliPayHk
| enums::PaymentMethodType::Alma
+ | enums::PaymentMethodType::AmazonPay
| enums::PaymentMethodType::ApplePay
| enums::PaymentMethodType::Atome
| enums::PaymentMethodType::Bacs
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 60852779884..363dfb81bcc 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -531,6 +531,7 @@ pub enum StripeWallet {
ApplepayToken(StripeApplePay),
GooglepayToken(GooglePayToken),
ApplepayPayment(ApplepayPayment),
+ AmazonpayPayment(AmazonpayPayment),
WechatpayPayment(WechatpayPayment),
AlipayPayment(AlipayPayment),
Cashapp(CashappPayment),
@@ -577,6 +578,12 @@ pub struct ApplepayPayment {
pub payment_method_types: StripePaymentMethodType,
}
+#[derive(Debug, Eq, PartialEq, Serialize)]
+pub struct AmazonpayPayment {
+ #[serde(rename = "payment_method_data[type]")]
+ pub payment_method_types: StripePaymentMethodType,
+}
+
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct AlipayPayment {
#[serde(rename = "payment_method_data[type]")]
@@ -620,6 +627,8 @@ pub enum StripePaymentMethodType {
Affirm,
AfterpayClearpay,
Alipay,
+ #[serde(rename = "amazon_pay")]
+ AmazonPay,
#[serde(rename = "au_becs_debit")]
Becs,
#[serde(rename = "bacs_debit")]
@@ -667,6 +676,7 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType {
enums::PaymentMethodType::Giropay => Ok(Self::Giropay),
enums::PaymentMethodType::Ideal => Ok(Self::Ideal),
enums::PaymentMethodType::Sofort => Ok(Self::Sofort),
+ enums::PaymentMethodType::AmazonPay => Ok(Self::AmazonPay),
enums::PaymentMethodType::ApplePay => Ok(Self::Card),
enums::PaymentMethodType::Ach => Ok(Self::Ach),
enums::PaymentMethodType::Sepa => Ok(Self::Sepa),
@@ -1048,6 +1058,9 @@ impl ForeignTryFrom<&domain::WalletData> for Option<StripePaymentMethodType> {
domain::WalletData::GooglePay(_) => Ok(Some(StripePaymentMethodType::Card)),
domain::WalletData::WeChatPayQr(_) => Ok(Some(StripePaymentMethodType::Wechatpay)),
domain::WalletData::CashappQr(_) => Ok(Some(StripePaymentMethodType::Cashapp)),
+ domain::WalletData::AmazonPayRedirect(_) => {
+ Ok(Some(StripePaymentMethodType::AmazonPay))
+ }
domain::WalletData::MobilePayRedirect(_) => {
Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("stripe"),
@@ -1466,6 +1479,11 @@ impl TryFrom<(&domain::WalletData, Option<types::PaymentMethodToken>)> for Strip
payment_method_data_type: StripePaymentMethodType::Cashapp,
})))
}
+ domain::WalletData::AmazonPayRedirect(_) => Ok(Self::Wallet(
+ StripeWallet::AmazonpayPayment(AmazonpayPayment {
+ payment_method_types: StripePaymentMethodType::AmazonPay,
+ }),
+ )),
domain::WalletData::GooglePay(gpay_data) => Ok(Self::try_from(gpay_data)?),
domain::WalletData::PaypalRedirect(_) | domain::WalletData::MobilePayRedirect(_) => {
Err(errors::ConnectorError::NotImplemented(
@@ -2301,6 +2319,7 @@ pub enum StripePaymentMethodDetailsResponse {
Klarna,
Affirm,
AfterpayClearpay,
+ AmazonPay,
ApplePay,
#[serde(rename = "us_bank_account")]
Ach,
@@ -2348,6 +2367,7 @@ impl StripePaymentMethodDetailsResponse {
| Self::Klarna
| Self::Affirm
| Self::AfterpayClearpay
+ | Self::AmazonPay
| Self::ApplePay
| Self::Ach
| Self::Sepa
@@ -2664,6 +2684,7 @@ impl<F, T>
| Some(StripePaymentMethodDetailsResponse::Klarna)
| Some(StripePaymentMethodDetailsResponse::Affirm)
| Some(StripePaymentMethodDetailsResponse::AfterpayClearpay)
+ | Some(StripePaymentMethodDetailsResponse::AmazonPay)
| Some(StripePaymentMethodDetailsResponse::ApplePay)
| Some(StripePaymentMethodDetailsResponse::Ach)
| Some(StripePaymentMethodDetailsResponse::Sepa)
@@ -3273,6 +3294,7 @@ pub enum StripePaymentMethodOptions {
Klarna {},
Affirm {},
AfterpayClearpay {},
+ AmazonPay {},
Eps {},
Giropay {},
Ideal {},
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index cbf1867b08b..c4824d65836 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -2744,6 +2744,7 @@ pub enum PaymentMethodDataType {
AliPayQr,
AliPayRedirect,
AliPayHkRedirect,
+ AmazonPayRedirect,
MomoRedirect,
KakaoPayRedirect,
GoPayRedirect,
@@ -2862,6 +2863,7 @@ impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType {
domain::payments::WalletData::AliPayQr(_) => Self::AliPayQr,
domain::payments::WalletData::AliPayRedirect(_) => Self::AliPayRedirect,
domain::payments::WalletData::AliPayHkRedirect(_) => Self::AliPayHkRedirect,
+ domain::payments::WalletData::AmazonPayRedirect(_) => Self::AmazonPayRedirect,
domain::payments::WalletData::MomoRedirect(_) => Self::MomoRedirect,
domain::payments::WalletData::KakaoPayRedirect(_) => Self::KakaoPayRedirect,
domain::payments::WalletData::GoPayRedirect(_) => Self::GoPayRedirect,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index b0df22f3d04..db12a6282c3 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -2740,7 +2740,8 @@ pub fn validate_payment_method_type_against_payment_method(
),
api_enums::PaymentMethod::Wallet => matches!(
payment_method_type,
- api_enums::PaymentMethodType::ApplePay
+ api_enums::PaymentMethodType::AmazonPay
+ | api_enums::PaymentMethodType::ApplePay
| api_enums::PaymentMethodType::GooglePay
| api_enums::PaymentMethodType::Paypal
| api_enums::PaymentMethodType::AliPay
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 2a287a337c9..c8222163b52 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -453,7 +453,8 @@ impl ForeignFrom<api_enums::IntentStatus> for Option<storage_enums::EventType> {
impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod {
fn foreign_from(payment_method_type: api_enums::PaymentMethodType) -> Self {
match payment_method_type {
- api_enums::PaymentMethodType::ApplePay
+ api_enums::PaymentMethodType::AmazonPay
+ | api_enums::PaymentMethodType::ApplePay
| api_enums::PaymentMethodType::GooglePay
| api_enums::PaymentMethodType::Paypal
| api_enums::PaymentMethodType::AliPay
|
feat
|
Add Support for Amazon Pay Redirect and Amazon Pay payment via Stripe (#7056)
|
fbf3c03d418242b1f5f1a15c69029023d0b25b4e
|
2023-10-13 08:10:54
|
Sampras Lopes
|
refactor(storage): update paymentintent object to provide a relation with attempts (#2502)
| false
|
diff --git a/Cargo.lock b/Cargo.lock
index e843210faa0..7a8bbe6fe7b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -69,7 +69,7 @@ dependencies = [
"actix-service",
"actix-utils",
"ahash 0.8.3",
- "base64 0.21.2",
+ "base64 0.21.4",
"bitflags 1.3.2",
"brotli",
"bytes",
@@ -99,19 +99,19 @@ dependencies = [
[[package]]
name = "actix-macros"
-version = "0.2.3"
+version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "465a6172cf69b960917811022d8f29bc0b7fa1398bc4f78b3c466673db1213b6"
+checksum = "e01ed3140b2f8d422c68afa1ed2e85d996ea619c988ac834d255db32138655cb"
dependencies = [
"quote",
- "syn 1.0.109",
+ "syn 2.0.38",
]
[[package]]
name = "actix-multipart"
-version = "0.6.0"
+version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dee489e3c01eae4d1c35b03c4493f71cb40d93f66b14558feb1b1a807671cc4e"
+checksum = "3b960e2aea75f49c8f069108063d12a48d329fc8b60b786dfc7552a9d5918d2d"
dependencies = [
"actix-multipart-derive",
"actix-utils",
@@ -134,15 +134,15 @@ dependencies = [
[[package]]
name = "actix-multipart-derive"
-version = "0.6.0"
+version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2ec592f234db8a253cf80531246a4407c8a70530423eea80688a6c5a44a110e7"
+checksum = "0a0a77f836d869f700e5b47ac7c3c8b9c8bc82e4aec861954c6198abee3ebd4d"
dependencies = [
- "darling 0.14.4",
+ "darling 0.20.3",
"parse-size",
"proc-macro2",
"quote",
- "syn 1.0.109",
+ "syn 2.0.38",
]
[[package]]
@@ -160,9 +160,9 @@ dependencies = [
[[package]]
name = "actix-rt"
-version = "2.8.0"
+version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "15265b6b8e2347670eb363c47fc8c75208b4a4994b27192f345fcbe707804f3e"
+checksum = "28f32d40287d3f402ae0028a9d54bef51af15c8769492826a69d28f81893151d"
dependencies = [
"actix-macros",
"futures-core",
@@ -171,9 +171,9 @@ dependencies = [
[[package]]
name = "actix-server"
-version = "2.2.0"
+version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3e8613a75dd50cc45f473cee3c34d59ed677c0f7b44480ce3b8247d7dc519327"
+checksum = "3eb13e7eef0423ea6eab0e59f6c72e7cb46d33691ad56a726b3cd07ddec2c2d4"
dependencies = [
"actix-rt",
"actix-service",
@@ -181,8 +181,7 @@ dependencies = [
"futures-core",
"futures-util",
"mio",
- "num_cpus",
- "socket2",
+ "socket2 0.5.4",
"tokio",
"tracing",
]
@@ -200,20 +199,23 @@ dependencies = [
[[package]]
name = "actix-tls"
-version = "3.0.3"
+version = "3.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9fde0cf292f7cdc7f070803cb9a0d45c018441321a78b1042ffbbb81ec333297"
+checksum = "72616e7fbec0aa99c6f3164677fa48ff5a60036d0799c98cab894a44f3e0efc3"
dependencies = [
- "actix-codec",
"actix-rt",
"actix-service",
"actix-utils",
"futures-core",
"http",
- "log",
+ "impl-more",
"pin-project-lite",
+ "rustls 0.21.7",
+ "rustls-webpki",
+ "tokio",
"tokio-rustls",
"tokio-util",
+ "tracing",
"webpki-roots",
]
@@ -263,21 +265,21 @@ dependencies = [
"serde_json",
"serde_urlencoded",
"smallvec",
- "socket2",
- "time 0.3.22",
+ "socket2 0.4.9",
+ "time",
"url",
]
[[package]]
name = "actix-web-codegen"
-version = "4.2.0"
+version = "4.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2262160a7ae29e3415554a3f1fc04c764b1540c116aa524683208078b7a75bc9"
+checksum = "eb1f50ebbb30eca122b188319a4398b3f7bb4a8cdf50ecfb73bfc6a3c3ce54f5"
dependencies = [
"actix-router",
"proc-macro2",
"quote",
- "syn 1.0.109",
+ "syn 2.0.38",
]
[[package]]
@@ -291,6 +293,15 @@ dependencies = [
"syn 1.0.109",
]
+[[package]]
+name = "addr2line"
+version = "0.21.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a30b2e23b9e17a9f90641c7ab1549cd9b44f296d3ccbf309d2863cfe398a0cb"
+dependencies = [
+ "gimli",
+]
+
[[package]]
name = "adler"
version = "1.0.2"
@@ -328,9 +339,9 @@ dependencies = [
[[package]]
name = "aho-corasick"
-version = "1.0.2"
+version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "43f6cb1bf222025340178f382c426f13757b2960e89779dfcb319c32542a5a41"
+checksum = "ea5d730647d4fadd988536d06fecce94b7b4f2a7efdae548f1cf4b63205518ab"
dependencies = [
"memchr",
]
@@ -373,9 +384,9 @@ checksum = "41ed9a86bf92ae6580e0a31281f65a1b1d867c0cc68d5346e2ae128dddfa6a7d"
[[package]]
name = "anyhow"
-version = "1.0.71"
+version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9c7d0618f0e0b7e8ff11427422b64564d5fb0be1940354bfe2e0529b18a9d9b8"
+checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
[[package]]
name = "api_models"
@@ -395,7 +406,7 @@ dependencies = [
"serde_with",
"strum 0.24.1",
"thiserror",
- "time 0.3.22",
+ "time",
"url",
"utoipa",
]
@@ -420,9 +431,9 @@ checksum = "6b4930d2cb77ce62f89ee5d5289b4ac049559b1c45539271f5ed4fdc7db34545"
[[package]]
name = "arrayvec"
-version = "0.7.3"
+version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8868f09ff8cea88b079da74ae569d9b8c62a23c68c746240b704ee6f7525c89c"
+checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711"
[[package]]
name = "asn1-rs"
@@ -437,7 +448,7 @@ dependencies = [
"num-traits",
"rusticata-macros",
"thiserror",
- "time 0.3.22",
+ "time",
]
[[package]]
@@ -498,9 +509,9 @@ dependencies = [
[[package]]
name = "async-compression"
-version = "0.4.0"
+version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5b0122885821398cc923ece939e24d1056a2384ee719432397fa9db87230ff11"
+checksum = "bb42b2197bf15ccb092b62c74515dbd8b86d0effd934795f6687c93b6e679a2c"
dependencies = [
"flate2",
"futures-core",
@@ -523,17 +534,17 @@ dependencies = [
"log",
"parking",
"polling",
- "rustix",
+ "rustix 0.37.24",
"slab",
- "socket2",
+ "socket2 0.4.9",
"waker-fn",
]
[[package]]
name = "async-lock"
-version = "2.7.0"
+version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fa24f727524730b077666307f2734b4a1a1c57acb79193127dcc8914d5242dd7"
+checksum = "287272293e9d8c41773cec55e365490fe034813a2f172f502d6ddcf75b2f582b"
dependencies = [
"event-listener",
]
@@ -557,7 +568,7 @@ checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.29",
+ "syn 2.0.38",
]
[[package]]
@@ -568,18 +579,7 @@ checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.29",
-]
-
-[[package]]
-name = "atty"
-version = "0.2.14"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
-dependencies = [
- "hermit-abi 0.1.19",
- "libc",
- "winapi",
+ "syn 2.0.38",
]
[[package]]
@@ -601,7 +601,7 @@ dependencies = [
"actix-tls",
"actix-utils",
"ahash 0.7.6",
- "base64 0.21.2",
+ "base64 0.21.4",
"bytes",
"cfg-if",
"cookie",
@@ -616,7 +616,7 @@ dependencies = [
"percent-encoding",
"pin-project-lite",
"rand 0.8.5",
- "rustls",
+ "rustls 0.20.9",
"serde",
"serde_json",
"serde_urlencoded",
@@ -641,12 +641,12 @@ dependencies = [
"aws-smithy-types",
"aws-types",
"bytes",
- "fastrand",
+ "fastrand 1.9.0",
"hex",
"http",
"hyper",
"ring",
- "time 0.3.22",
+ "time",
"tokio",
"tower",
"tracing",
@@ -661,7 +661,7 @@ checksum = "1fcdb2f7acbc076ff5ad05e7864bdb191ca70a6fd07668dc3a1a8bcd051de5ae"
dependencies = [
"aws-smithy-async",
"aws-smithy-types",
- "fastrand",
+ "fastrand 1.9.0",
"tokio",
"tracing",
"zeroize",
@@ -866,7 +866,7 @@ dependencies = [
"percent-encoding",
"regex",
"sha2",
- "time 0.3.22",
+ "time",
"tracing",
]
@@ -914,14 +914,14 @@ dependencies = [
"aws-smithy-http-tower",
"aws-smithy-types",
"bytes",
- "fastrand",
+ "fastrand 1.9.0",
"http",
"http-body",
"hyper",
"hyper-rustls",
"lazy_static",
"pin-project-lite",
- "rustls",
+ "rustls 0.20.9",
"tokio",
"tower",
"tracing",
@@ -1006,7 +1006,7 @@ dependencies = [
"itoa",
"num-integer",
"ryu",
- "time 0.3.22",
+ "time",
]
[[package]]
@@ -1036,9 +1036,9 @@ dependencies = [
[[package]]
name = "axum"
-version = "0.6.18"
+version = "0.6.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f8175979259124331c1d7bf6586ee7e0da434155e4b2d48ec2c8386281d8df39"
+checksum = "3b829e4e32b91e643de6eafe82b1d90675f5874230191a4ffbc1b336dec4d6bf"
dependencies = [
"async-trait",
"axum-core",
@@ -1079,6 +1079,21 @@ dependencies = [
"tower-service",
]
+[[package]]
+name = "backtrace"
+version = "0.3.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2089b7e3f35b9dd2d0ed921ead4f6d318c27680d4a5bd167b3ee120edb105837"
+dependencies = [
+ "addr2line",
+ "cc",
+ "cfg-if",
+ "libc",
+ "miniz_oxide 0.7.1",
+ "object",
+ "rustc-demangle",
+]
+
[[package]]
name = "base64"
version = "0.13.1"
@@ -1087,9 +1102,9 @@ checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
[[package]]
name = "base64"
-version = "0.21.2"
+version = "0.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d"
+checksum = "9ba43ea6f343b788c8764558649e08df62f86c6ef251fdaeb1ffd010a9ae50a2"
[[package]]
name = "base64-simd"
@@ -1146,9 +1161,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitflags"
-version = "2.3.2"
+version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6dbe3c979c178231552ecba20214a8272df4e09f232a87aef4320cf06539aded"
+checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635"
[[package]]
name = "blake3"
@@ -1184,9 +1199,9 @@ dependencies = [
[[package]]
name = "brotli"
-version = "3.3.4"
+version = "3.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a1a0b1dbcc8ae29329621f8d4f0d835787c1c38bb1401979b49d13b0b305ff68"
+checksum = "516074a47ef4bce09577a3b379392300159ce5b1ba2e501ff1c819950066100f"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
@@ -1195,9 +1210,9 @@ dependencies = [
[[package]]
name = "brotli-decompressor"
-version = "2.3.4"
+version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4b6561fd3f895a11e8f72af2cb7d22e08366bebc2b6b57f7744c4bda27034744"
+checksum = "da74e2b81409b1b743f8f0c62cc6254afefb8b8e50bbfe3735550f7aeefa3448"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
@@ -1215,33 +1230,33 @@ dependencies = [
[[package]]
name = "bumpalo"
-version = "3.13.0"
+version = "3.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a3e2c3daef883ecc1b5d58c15adae93470a91d425f3532ba1695849656af3fc1"
+checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec"
[[package]]
name = "bytecount"
-version = "0.6.3"
+version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2c676a478f63e9fa2dd5368a42f28bba0d6c560b775f38583c8bbaa7fcd67c9c"
+checksum = "ad152d03a2c813c80bb94fedbf3a3f02b28f793e39e7c214c8a0bcc196343de7"
[[package]]
name = "bytemuck"
-version = "1.13.1"
+version = "1.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "17febce684fd15d89027105661fec94afb475cb995fbc59d2865198446ba2eea"
+checksum = "374d28ec25809ee0e23827c2ab573d729e293f281dfe393500e7ad618baa61c6"
[[package]]
name = "byteorder"
-version = "1.4.3"
+version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"
+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "bytes"
-version = "1.4.0"
+version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be"
+checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223"
[[package]]
name = "bytes-utils"
@@ -1264,9 +1279,9 @@ dependencies = [
[[package]]
name = "camino"
-version = "1.1.4"
+version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c530edf18f37068ac2d977409ed5cd50d53d73bc653c7647b48eb78976ac9ae2"
+checksum = "c59e92b5a388f549b863a7bea62612c09f24c8393560709a54558a9abdfb3b9c"
dependencies = [
"serde",
]
@@ -1282,14 +1297,14 @@ dependencies = [
"serde",
"serde_json",
"thiserror",
- "time 0.3.22",
+ "time",
]
[[package]]
name = "cargo-platform"
-version = "0.1.2"
+version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cbdb825da8a5df079a43676dbe042702f1707b1109f713a01420fbb4cc71fa27"
+checksum = "2cfa25e60aea747ec7e1124f238816749faa93759c6ff5b31f1ccdda137f4479"
dependencies = [
"serde",
]
@@ -1323,11 +1338,12 @@ dependencies = [
[[package]]
name = "cc"
-version = "1.0.79"
+version = "1.0.83"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f"
+checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0"
dependencies = [
"jobserver",
+ "libc",
]
[[package]]
@@ -1355,18 +1371,17 @@ checksum = "17cc5e6b5ab06331c33589842070416baa137e8b0eb912b008cfd4a78ada7919"
[[package]]
name = "chrono"
-version = "0.4.26"
+version = "0.4.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ec837a71355b28f6556dbd569b37b3f363091c0bd4b2e735674521b4c5fd9bc5"
+checksum = "7f2c685bad3eb3d45a01354cedb7d5faa66194d1d58ba6e267a8de788f79db38"
dependencies = [
"android-tzdata",
"iana-time-zone",
"js-sys",
"num-traits",
"serde",
- "time 0.1.45",
"wasm-bindgen",
- "winapi",
+ "windows-targets",
]
[[package]]
@@ -1422,7 +1437,7 @@ dependencies = [
"heck",
"proc-macro2",
"quote",
- "syn 2.0.29",
+ "syn 2.0.38",
]
[[package]]
@@ -1447,7 +1462,7 @@ dependencies = [
"serde",
"serde_json",
"strum 0.25.0",
- "time 0.3.22",
+ "time",
"utoipa",
]
@@ -1483,15 +1498,15 @@ dependencies = [
"strum 0.24.1",
"test-case",
"thiserror",
- "time 0.3.22",
+ "time",
"tokio",
]
[[package]]
name = "concurrent-queue"
-version = "2.2.0"
+version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "62ec6771ecfa0762d24683ee5a32ad78487a3d3afdc0fb8cae19d2c5deb50b7c"
+checksum = "f057a694a54f12365049b0958a1685bb52d567f5593b355fbf685838e873d400"
dependencies = [
"crossbeam-utils",
]
@@ -1534,7 +1549,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e859cd57d0710d9e06c381b550c06e76992472a8c6d527aecd2fc673dcc231fb"
dependencies = [
"percent-encoding",
- "time 0.3.22",
+ "time",
"version_check",
]
@@ -1562,9 +1577,9 @@ checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa"
[[package]]
name = "cpufeatures"
-version = "0.2.7"
+version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3e4c1eaa2012c47becbbad2ab175484c2a84d1185b566fb2cc5b8707343dfe58"
+checksum = "a17b76ff3a4162b0b27f354a0c87015ddad39d35f9c0c36607a3bdd175dde1f1"
dependencies = [
"libc",
]
@@ -1577,9 +1592,9 @@ checksum = "338089f42c427b86394a5ee60ff321da23a5c89c9d89514c829687b26359fcff"
[[package]]
name = "crc32c"
-version = "0.6.3"
+version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3dfea2db42e9927a3845fb268a10a72faed6d416065f77873f05e411457c363e"
+checksum = "d8f48d60e5b4d2c53d5c2b1d8a58c849a70ae5e5509b08a48d047e3b65714a74"
dependencies = [
"rustc_version",
]
@@ -1658,12 +1673,12 @@ dependencies = [
[[package]]
name = "darling"
-version = "0.20.1"
+version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0558d22a7b463ed0241e993f76f09f30b126687447751a8638587b864e4b3944"
+checksum = "0209d94da627ab5605dcccf08bb18afa5009cfbef48d8a8b7d7bdbc79be25c5e"
dependencies = [
- "darling_core 0.20.1",
- "darling_macro 0.20.1",
+ "darling_core 0.20.3",
+ "darling_macro 0.20.3",
]
[[package]]
@@ -1682,16 +1697,16 @@ dependencies = [
[[package]]
name = "darling_core"
-version = "0.20.1"
+version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ab8bfa2e259f8ee1ce5e97824a3c55ec4404a0d772ca7fa96bf19f0752a046eb"
+checksum = "177e3443818124b357d8e76f53be906d60937f0d3a90773a664fa63fa253e621"
dependencies = [
"fnv",
"ident_case",
"proc-macro2",
"quote",
"strsim",
- "syn 2.0.29",
+ "syn 2.0.38",
]
[[package]]
@@ -1707,23 +1722,23 @@ dependencies = [
[[package]]
name = "darling_macro"
-version = "0.20.1"
+version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "29a358ff9f12ec09c3e61fef9b5a9902623a695a46a917b07f269bff1445611a"
+checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5"
dependencies = [
- "darling_core 0.20.1",
+ "darling_core 0.20.3",
"quote",
- "syn 2.0.29",
+ "syn 2.0.38",
]
[[package]]
name = "dashmap"
-version = "5.4.0"
+version = "5.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "907076dfda823b0b36d2a1bb5f90c96660a5bbcd7729e10727f07858f22c4edc"
+checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856"
dependencies = [
"cfg-if",
- "hashbrown 0.12.3",
+ "hashbrown 0.14.1",
"lock_api",
"once_cell",
"parking_lot_core",
@@ -1749,7 +1764,7 @@ dependencies = [
"serde_json",
"strum 0.25.0",
"thiserror",
- "time 0.3.22",
+ "time",
]
[[package]]
@@ -1767,9 +1782,9 @@ dependencies = [
[[package]]
name = "deadpool-runtime"
-version = "0.1.2"
+version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "eaa37046cc0f6c3cc6090fbdbf73ef0b8ef4cfcc37f6befc0020f63e8cf121e1"
+checksum = "63dfa964fe2a66f3fde91fc70b267fe193d822c7e603e2a675a49a7f46ad3f49"
[[package]]
name = "deflate"
@@ -1827,30 +1842,30 @@ checksum = "d95203a6a50906215a502507c0f879a0ce7ff205a6111e2db2a5ef8e4bb92e43"
[[package]]
name = "diesel"
-version = "2.1.0"
+version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f7a532c1f99a0f596f6960a60d1e119e91582b24b39e2d83a190e61262c3ef0c"
+checksum = "2268a214a6f118fce1838edba3d1561cf0e78d8de785475957a580a7f8c69d33"
dependencies = [
- "bitflags 2.3.2",
+ "bitflags 2.4.0",
"byteorder",
"diesel_derives",
"itoa",
"pq-sys",
"r2d2",
"serde_json",
- "time 0.3.22",
+ "time",
]
[[package]]
name = "diesel_derives"
-version = "2.1.0"
+version = "2.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "74398b79d81e52e130d991afeed9c86034bb1b7735f46d2f5bf7deb261d80303"
+checksum = "ef8337737574f55a468005a83499da720f20c65586241ffea339db9ecdfd2b44"
dependencies = [
"diesel_table_macro_syntax",
"proc-macro2",
"quote",
- "syn 2.0.29",
+ "syn 2.0.38",
]
[[package]]
@@ -1874,7 +1889,7 @@ dependencies = [
"serde_json",
"strum 0.24.1",
"thiserror",
- "time 0.3.22",
+ "time",
]
[[package]]
@@ -1883,7 +1898,7 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc5557efc453706fed5e4fa85006fe9817c224c3f480a34c7e5959fd700921c5"
dependencies = [
- "syn 2.0.29",
+ "syn 2.0.38",
]
[[package]]
@@ -1940,7 +1955,7 @@ checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.29",
+ "syn 2.0.38",
]
[[package]]
@@ -1975,38 +1990,25 @@ dependencies = [
[[package]]
name = "dyn-clone"
-version = "1.0.13"
+version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bbfc4744c1b8f2a09adc0e55242f60b1af195d88596bd8700be74418c056c555"
+checksum = "23d2f3407d9a573d666de4b5bdf10569d73ca9478087346697dcbae6244bfbcd"
[[package]]
name = "either"
-version = "1.8.1"
+version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91"
+checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07"
[[package]]
name = "encoding_rs"
-version = "0.8.32"
+version = "0.8.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "071a31f4ee85403370b58aca746f01041ede6f0da2730960ad001edc2b71b394"
+checksum = "7268b386296a025e474d5140678f75d6de9493ae55a5d709eeb9dd08149945e1"
dependencies = [
"cfg-if",
]
-[[package]]
-name = "env_logger"
-version = "0.7.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36"
-dependencies = [
- "atty",
- "humantime",
- "log",
- "regex",
- "termcolor",
-]
-
[[package]]
name = "equivalent"
version = "1.0.1"
@@ -2015,13 +2017,13 @@ checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"
[[package]]
name = "errno"
-version = "0.3.1"
+version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4bcfec3a70f97c962c307b2d2c56e358cf1d00b558d74262b5f929ee8cc7e73a"
+checksum = "add4f07d43996f76ef320709726a556a9d4f965d9410d8d0271132d2f8293480"
dependencies = [
"errno-dragonfly",
"libc",
- "windows-sys 0.48.0",
+ "windows-sys",
]
[[package]]
@@ -2069,7 +2071,7 @@ dependencies = [
"aws-sdk-kms",
"aws-sdk-sesv2",
"aws-smithy-client",
- "base64 0.21.2",
+ "base64 0.21.4",
"common_utils",
"dyn-clone",
"error-stack",
@@ -2107,7 +2109,7 @@ dependencies = [
"mime",
"serde",
"serde_json",
- "time 0.3.22",
+ "time",
"tokio",
"url",
"webdriver",
@@ -2122,11 +2124,17 @@ dependencies = [
"instant",
]
+[[package]]
+name = "fastrand"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5"
+
[[package]]
name = "flate2"
-version = "1.0.26"
+version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3b9429470923de8e8cbd4d2dc513535400b4b3fef0319fb5c4e1f520a7bef743"
+checksum = "c6c98ee8095e9d1dcbf2fcc6d95acccb90d1c81db1e44725c6a984b1dbdfb010"
dependencies = [
"crc32fast",
"miniz_oxide 0.7.1",
@@ -2173,9 +2181,9 @@ dependencies = [
[[package]]
name = "fred"
-version = "6.3.0"
+version = "6.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7e02c21b098d77b0e99fe0054ebd3e7c9f81bffb42aa843021415ffa793124a6"
+checksum = "a15cc18b56395b8b15ffcdcea7fe8586e3a3ccb3d9dc3b9408800d9814efb08e"
dependencies = [
"arc-swap",
"arcstr",
@@ -2188,7 +2196,6 @@ dependencies = [
"lazy_static",
"log",
"parking_lot",
- "pretty_env_logger",
"rand 0.8.5",
"redis-protocol",
"semver",
@@ -2203,9 +2210,9 @@ dependencies = [
[[package]]
name = "frunk"
-version = "0.4.1"
+version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a89c703bf50009f383a0873845357cc400a95fc535f836feddfe015d7df6e1e0"
+checksum = "11a351b59e12f97b4176ee78497dff72e4276fb1ceb13e19056aca7fa0206287"
dependencies = [
"frunk_core",
"frunk_derives",
@@ -2214,55 +2221,43 @@ dependencies = [
[[package]]
name = "frunk_core"
-version = "0.4.1"
+version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2a446d01a558301dca28ef43222864a9fa2bd9a2e71370f769d5d5d5ec9f3537"
+checksum = "af2469fab0bd07e64ccf0ad57a1438f63160c69b2e57f04a439653d68eb558d6"
[[package]]
name = "frunk_derives"
-version = "0.4.1"
+version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b83164912bb4c97cfe0772913c7af7387ee2e00cb6d4636fb65a35b3d0c8f173"
+checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e"
dependencies = [
"frunk_proc_macro_helpers",
"quote",
- "syn 1.0.109",
+ "syn 2.0.38",
]
[[package]]
name = "frunk_proc_macro_helpers"
-version = "0.1.1"
+version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "015425591bbeb0f5b8a75593340f1789af428e9f887a4f1e36c0c471f067ef50"
+checksum = "35b54add839292b743aeda6ebedbd8b11e93404f902c56223e51b9ec18a13d2c"
dependencies = [
"frunk_core",
"proc-macro2",
"quote",
- "syn 1.0.109",
+ "syn 2.0.38",
]
[[package]]
name = "frunk_proc_macros"
-version = "0.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ea01524f285deab48affffb342b97f186e657b119c3f1821ac531780e0fbfae0"
-dependencies = [
- "frunk_core",
- "frunk_proc_macros_impl",
- "proc-macro-hack",
-]
-
-[[package]]
-name = "frunk_proc_macros_impl"
-version = "0.1.1"
+version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0a802d974cc18ee7fe1a7868fc9ce31086294fd96ba62f8da64ecb44e92a2653"
+checksum = "71b85a1d4a9a6b300b41c05e8e13ef2feca03e0334127f29eca9506a7fe13a93"
dependencies = [
"frunk_core",
"frunk_proc_macro_helpers",
- "proc-macro-hack",
"quote",
- "syn 1.0.109",
+ "syn 2.0.38",
]
[[package]]
@@ -2319,7 +2314,7 @@ version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49a9d51ce47660b1e808d3c990b4709f2f415d928835a17dfd16991515c46bce"
dependencies = [
- "fastrand",
+ "fastrand 1.9.0",
"futures-core",
"futures-io",
"memchr",
@@ -2336,7 +2331,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.29",
+ "syn 2.0.38",
]
[[package]]
@@ -2427,6 +2422,12 @@ dependencies = [
"weezl",
]
+[[package]]
+name = "gimli"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6fb8d784f27acf97159b40fc4db5ecd8aa23b9ad5ef69cdd136d3bc80665f0c0"
+
[[package]]
name = "git2"
version = "0.17.2"
@@ -2472,9 +2473,9 @@ dependencies = [
[[package]]
name = "h2"
-version = "0.3.19"
+version = "0.3.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d357c7ae988e7d2182f7d7871d0b963962420b0678b0997ce7de72001aeab782"
+checksum = "91fc23aa11be92976ef4729127f1a74adf36d8436f7816b185d18df956790833"
dependencies = [
"bytes",
"fnv",
@@ -2500,9 +2501,9 @@ dependencies = [
[[package]]
name = "hashbrown"
-version = "0.14.0"
+version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a"
+checksum = "7dfda62a12f55daeae5015f81b0baea145391cb4520f86c248fc615d72640d12"
[[package]]
name = "heck"
@@ -2512,27 +2513,9 @@ checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
[[package]]
name = "hermit-abi"
-version = "0.1.19"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"
-dependencies = [
- "libc",
-]
-
-[[package]]
-name = "hermit-abi"
-version = "0.2.6"
+version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7"
-dependencies = [
- "libc",
-]
-
-[[package]]
-name = "hermit-abi"
-version = "0.3.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fed44880c466736ef9a5c5b5facefb5ed0785676d0c02d612db14e54f0d84286"
+checksum = "d77f7ec81a6d05a3abb01ab6eb7590f6083d08449fe5a1c8b1e620283546ccb7"
[[package]]
name = "hex"
@@ -2600,9 +2583,9 @@ checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904"
[[package]]
name = "httpdate"
-version = "1.0.2"
+version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421"
+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "humansize"
@@ -2613,15 +2596,6 @@ dependencies = [
"libm",
]
-[[package]]
-name = "humantime"
-version = "1.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f"
-dependencies = [
- "quick-error",
-]
-
[[package]]
name = "hyper"
version = "0.14.27"
@@ -2639,7 +2613,7 @@ dependencies = [
"httpdate",
"itoa",
"pin-project-lite",
- "socket2",
+ "socket2 0.4.9",
"tokio",
"tower-service",
"tracing",
@@ -2655,7 +2629,7 @@ dependencies = [
"http",
"hyper",
"log",
- "rustls",
+ "rustls 0.20.9",
"rustls-native-certs",
"tokio",
"tokio-rustls",
@@ -2761,6 +2735,12 @@ dependencies = [
"tiff",
]
+[[package]]
+name = "impl-more"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "206ca75c9c03ba3d4ace2460e57b189f39f43de612c2f85836e65c929701bb2d"
+
[[package]]
name = "indexmap"
version = "1.9.3"
@@ -2774,12 +2754,13 @@ dependencies = [
[[package]]
name = "indexmap"
-version = "2.0.0"
+version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d"
+checksum = "8adf3ddd720272c6ea8bf59463c04e0f93d0bbf7c5439b691bca2987e0270897"
dependencies = [
"equivalent",
- "hashbrown 0.14.0",
+ "hashbrown 0.14.1",
+ "serde",
]
[[package]]
@@ -2812,16 +2793,16 @@ version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2"
dependencies = [
- "hermit-abi 0.3.1",
+ "hermit-abi",
"libc",
- "windows-sys 0.48.0",
+ "windows-sys",
]
[[package]]
name = "ipnet"
-version = "2.7.2"
+version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "12b6ee2129af8d4fb011108c73d99a1b83a85977f23b82460c0ae2e25bb4b57f"
+checksum = "28b29a3cd74f0f4598934efe3aeba42bae0eb4680554128851ebbecb02af14e6"
[[package]]
name = "itertools"
@@ -2832,11 +2813,20 @@ dependencies = [
"either",
]
+[[package]]
+name = "itertools"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57"
+dependencies = [
+ "either",
+]
+
[[package]]
name = "itoa"
-version = "1.0.6"
+version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "453ad9f582a441959e5f0d088b02ce04cfe8d51a8eaf077f12ac6d3e94164ca6"
+checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38"
[[package]]
name = "jobserver"
@@ -2854,7 +2844,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33a96c4f2128a6f44ecf7c36df2b03dddf5a07b060a4d5ebc0a81e9821f7c60e"
dependencies = [
"anyhow",
- "base64 0.21.2",
+ "base64 0.21.4",
"flate2",
"once_cell",
"openssl",
@@ -2862,7 +2852,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror",
- "time 0.3.22",
+ "time",
]
[[package]]
@@ -2900,7 +2890,7 @@ version = "8.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6971da4d9c3aa03c3d8f3ff0f4155b534aad021292003895a469716b2a230378"
dependencies = [
- "base64 0.21.2",
+ "base64 0.21.4",
"pem",
"ring",
"serde",
@@ -2922,9 +2912,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
-version = "0.2.146"
+version = "0.2.148"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f92be4933c13fd498862a9e02a3055f8a8d9c039ce33db97306fd5a6caa7f29b"
+checksum = "9cdc71e17332e86d2e1d38c1f99edcb6288ee11b815fb1a4b049eaa2114d369b"
[[package]]
name = "libgit2-sys"
@@ -2940,15 +2930,15 @@ dependencies = [
[[package]]
name = "libm"
-version = "0.2.7"
+version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f7012b1bbb0719e1097c47611d3898568c546d597c2e74d66f6087edd5233ff4"
+checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058"
[[package]]
name = "libmimalloc-sys"
-version = "0.1.33"
+version = "0.1.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f4ac0e912c8ef1b735e92369695618dc5b1819f5a7bf3f167301a3ba1cea515e"
+checksum = "3979b5c37ece694f1f5e51e7ecc871fdb0f517ed04ee45f88d15d6d553cb9664"
dependencies = [
"cc",
"libc",
@@ -2956,9 +2946,9 @@ dependencies = [
[[package]]
name = "libz-sys"
-version = "1.1.9"
+version = "1.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "56ee889ecc9568871456d42f603d6a0ce59ff328d291063a45cbdf0036baf6db"
+checksum = "d97137b25e321a73eef1418d1d5d2eda4d77e12813f8e6dead84bc52c5870a7b"
dependencies = [
"cc",
"libc",
@@ -2978,6 +2968,12 @@ version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519"
+[[package]]
+name = "linux-raw-sys"
+version = "0.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3852614a3bd9ca9804678ba6be5e3b8ce76dfc902cae004e3e0c44051b6e88db"
+
[[package]]
name = "literally"
version = "0.1.3"
@@ -2986,13 +2982,12 @@ checksum = "f0d2be3f5a0d4d5c983d1f8ecc2a87676a0875a14feb9eebf0675f7c3e2f3c35"
[[package]]
name = "local-channel"
-version = "0.1.3"
+version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7f303ec0e94c6c54447f84f3b0ef7af769858a9c4ef56ef2a986d3dcd4c3fc9c"
+checksum = "e0a493488de5f18c8ffcba89eebb8532ffc562dc400490eb65b84893fae0b178"
dependencies = [
"futures-core",
"futures-sink",
- "futures-util",
"local-waker",
]
@@ -3014,9 +3009,9 @@ dependencies = [
[[package]]
name = "log"
-version = "0.4.19"
+version = "0.4.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b06a4cde4c0f271a446782e3eff8de789548ce57dbc8eca9292c27f4a42004b4"
+checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"
[[package]]
name = "lru-cache"
@@ -3063,14 +3058,14 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558"
dependencies = [
- "regex-automata",
+ "regex-automata 0.1.10",
]
[[package]]
name = "matchit"
-version = "0.7.0"
+version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b87248edafb776e59e6ee64a79086f65890d3510f2c656c000bf2a7e8a0aea40"
+checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94"
[[package]]
name = "maud"
@@ -3098,10 +3093,11 @@ dependencies = [
[[package]]
name = "md-5"
-version = "0.10.5"
+version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6365506850d44bff6e2fbcb5176cf63650e48bd45ef2fe2665ae1570e0f4b9ca"
+checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
dependencies = [
+ "cfg-if",
"digest 0.10.7",
]
@@ -3113,9 +3109,9 @@ checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771"
[[package]]
name = "memchr"
-version = "2.5.0"
+version = "2.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
+checksum = "f665ee40bc4a3c5590afb1e9677db74a508659dfd71e126420da8274909a0167"
[[package]]
name = "memoffset"
@@ -3128,9 +3124,9 @@ dependencies = [
[[package]]
name = "mimalloc"
-version = "0.1.37"
+version = "0.1.39"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4e2894987a3459f3ffb755608bd82188f8ed00d0ae077f1edea29c068d639d98"
+checksum = "fa01922b5ea280a911e323e4d2fd24b7fe5cc4042e0d2cda3c40775cdc4bdc9c"
dependencies = [
"libmimalloc-sys",
]
@@ -3194,7 +3190,7 @@ dependencies = [
"libc",
"log",
"wasi 0.11.0+wasi-snapshot-preview1",
- "windows-sys 0.48.0",
+ "windows-sys",
]
[[package]]
@@ -3271,9 +3267,9 @@ dependencies = [
[[package]]
name = "num-bigint"
-version = "0.4.3"
+version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f93ab6289c7b344a8a9f60f88d80aa20032336fe78da341afc91c8a2341fc75f"
+checksum = "608e7659b5c3d7cba262d894801b9ec9d00de989e8a82bd4bef91d08da45cdc0"
dependencies = [
"autocfg",
"num-integer",
@@ -3314,9 +3310,9 @@ dependencies = [
[[package]]
name = "num-traits"
-version = "0.2.15"
+version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd"
+checksum = "f30b0abd723be7e2ffca1272140fac1a2f084c77ec3e123c192b66af1ee9e6c2"
dependencies = [
"autocfg",
"libm",
@@ -3324,14 +3320,23 @@ dependencies = [
[[package]]
name = "num_cpus"
-version = "1.15.0"
+version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b"
+checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43"
dependencies = [
- "hermit-abi 0.2.6",
+ "hermit-abi",
"libc",
]
+[[package]]
+name = "object"
+version = "0.32.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9cf5f9dd3933bd50a9e1f149ec995f39ae2c496d31fd772c1fd45ebc27e902b0"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "oid-registry"
version = "0.6.1"
@@ -3361,11 +3366,11 @@ checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5"
[[package]]
name = "openssl"
-version = "0.10.55"
+version = "0.10.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "345df152bc43501c5eb9e4654ff05f794effb78d4efe3d53abc158baddc0703d"
+checksum = "bac25ee399abb46215765b1cb35bc0212377e58a061560d8b29b024fd0430e7c"
dependencies = [
- "bitflags 1.3.2",
+ "bitflags 2.4.0",
"cfg-if",
"foreign-types",
"libc",
@@ -3382,7 +3387,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.29",
+ "syn 2.0.38",
]
[[package]]
@@ -3393,9 +3398,9 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"
[[package]]
name = "openssl-sys"
-version = "0.9.90"
+version = "0.9.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "374533b0e45f3a7ced10fcaeccca020e66656bc03dac384f852e4e5a7a8104a6"
+checksum = "db4d56a4c0478783083cfafcc42493dd4a981d41669da64b4572a2a089b51b1d"
dependencies = [
"cc",
"libc",
@@ -3506,9 +3511,9 @@ checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"
[[package]]
name = "parking"
-version = "2.1.0"
+version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "14f2252c834a40ed9bb5422029649578e63aa341ac401f74e719dd1afda8394e"
+checksum = "e52c774a4c39359c1d1c52e43f73dd91a75a614652c825408eec30c95a9b2067"
[[package]]
name = "parking_lot"
@@ -3550,9 +3555,9 @@ dependencies = [
[[package]]
name = "paste"
-version = "1.0.12"
+version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9f746c4065a8fa3fe23974dd82f15431cc8d40779821001404d10d2e79ca7d79"
+checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c"
[[package]]
name = "pathdiff"
@@ -3577,19 +3582,20 @@ checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94"
[[package]]
name = "pest"
-version = "2.6.0"
+version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e68e84bfb01f0507134eac1e9b410a12ba379d064eab48c50ba4ce329a527b70"
+checksum = "c022f1e7b65d6a24c0dbbd5fb344c66881bc01f3e5ae74a1c8100f2f985d98a4"
dependencies = [
+ "memchr",
"thiserror",
"ucd-trie",
]
[[package]]
name = "pest_derive"
-version = "2.6.0"
+version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6b79d4c71c865a25a4322296122e3924d30bc8ee0834c8bfc8b95f7f054afbfb"
+checksum = "35513f630d46400a977c4cb58f78e1bfbe01434316e60c37d27b9ad6139c66d8"
dependencies = [
"pest",
"pest_generator",
@@ -3597,22 +3603,22 @@ dependencies = [
[[package]]
name = "pest_generator"
-version = "2.6.0"
+version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6c435bf1076437b851ebc8edc3a18442796b30f1728ffea6262d59bbe28b077e"
+checksum = "bc9fc1b9e7057baba189b5c626e2d6f40681ae5b6eb064dc7c7834101ec8123a"
dependencies = [
"pest",
"pest_meta",
"proc-macro2",
"quote",
- "syn 2.0.29",
+ "syn 2.0.38",
]
[[package]]
name = "pest_meta"
-version = "2.6.0"
+version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "745a452f8eb71e39ffd8ee32b3c5f51d03845f99786fa9b68db6ff509c505411"
+checksum = "1df74e9e7ec4053ceb980e7c0c8bd3594e977fde1af91daba9c928e8e8c6708d"
dependencies = [
"once_cell",
"pest",
@@ -3666,7 +3672,7 @@ dependencies = [
"bincode",
"either",
"fnv",
- "itertools",
+ "itertools 0.11.0",
"lazy_static",
"nom",
"quick-xml",
@@ -3680,29 +3686,29 @@ dependencies = [
[[package]]
name = "pin-project"
-version = "1.1.0"
+version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c95a7476719eab1e366eaf73d0260af3021184f18177925b07f54b30089ceead"
+checksum = "fda4ed1c6c173e3fc7a83629421152e01d7b1f9b7f65fb301e490e8cfc656422"
dependencies = [
"pin-project-internal",
]
[[package]]
name = "pin-project-internal"
-version = "1.1.0"
+version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "39407670928234ebc5e6e580247dd567ad73a3578460c5990f9503df207e8f07"
+checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.29",
+ "syn 2.0.38",
]
[[package]]
name = "pin-project-lite"
-version = "0.2.9"
+version = "0.2.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116"
+checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58"
[[package]]
name = "pin-utils"
@@ -3741,7 +3747,7 @@ dependencies = [
"libc",
"log",
"pin-project-lite",
- "windows-sys 0.48.0",
+ "windows-sys",
]
[[package]]
@@ -3759,16 +3765,6 @@ dependencies = [
"vcpkg",
]
-[[package]]
-name = "pretty_env_logger"
-version = "0.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "926d36b9553851b8b0005f1275891b392ee4d2d833852c417ed025477350fb9d"
-dependencies = [
- "env_logger",
- "log",
-]
-
[[package]]
name = "proc-macro-error"
version = "1.0.4"
@@ -3793,36 +3789,30 @@ dependencies = [
"version_check",
]
-[[package]]
-name = "proc-macro-hack"
-version = "0.5.20+deprecated"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068"
-
[[package]]
name = "proc-macro2"
-version = "1.0.66"
+version = "1.0.68"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "18fb31db3f9bddb2ea821cde30a9f70117e3f119938b5ee630b7403aa6e2ead9"
+checksum = "5b1106fec09662ec6dd98ccac0f81cef56984d0b49f75c92d8cbad76e20c005c"
dependencies = [
"unicode-ident",
]
[[package]]
name = "proptest"
-version = "1.2.0"
+version = "1.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4e35c06b98bf36aba164cc17cb25f7e232f5c4aeea73baa14b8a9f0d92dbfa65"
+checksum = "7c003ac8c77cb07bb74f5f198bce836a689bcd5a42574612bf14d17bfd08c20e"
dependencies = [
"bit-set",
- "bitflags 1.3.2",
- "byteorder",
+ "bit-vec",
+ "bitflags 2.4.0",
"lazy_static",
"num-traits",
"rand 0.8.5",
"rand_chacha 0.3.1",
"rand_xorshift",
- "regex-syntax 0.6.29",
+ "regex-syntax 0.7.5",
"rusty-fork",
"tempfile",
"unarray",
@@ -3845,7 +3835,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5d2d8d10f3c6ded6da8b05b5fb3b8a5082514344d56c9f871412d29b4e075b4"
dependencies = [
"anyhow",
- "itertools",
+ "itertools 0.10.5",
"proc-macro2",
"quote",
"syn 1.0.109",
@@ -4015,9 +4005,9 @@ dependencies = [
[[package]]
name = "rayon"
-version = "1.7.0"
+version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1d2df5196e37bcc87abebc0053e20787d73847bb33134a69841207dd0a47f03b"
+checksum = "9c27db03db7734835b3f53954b534c91069375ce6ccaa2e065441e07d9b6cdb1"
dependencies = [
"either",
"rayon-core",
@@ -4025,14 +4015,12 @@ dependencies = [
[[package]]
name = "rayon-core"
-version = "1.11.0"
+version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4b8f95bd6966f5c87776639160a66bd8ab9895d9d4ab01ddba9fc60661aebe8d"
+checksum = "5ce3fb6ad83f861aac485e76e1985cd109d9a3713802152be56c3b1f0e0658ed"
dependencies = [
- "crossbeam-channel",
"crossbeam-deque",
"crossbeam-utils",
- "num_cpus",
]
[[package]]
@@ -4094,13 +4082,14 @@ dependencies = [
[[package]]
name = "regex"
-version = "1.8.4"
+version = "1.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d0ab3ca65655bb1e41f2a8c8cd662eb4fb035e67c3f78da1d61dffe89d07300f"
+checksum = "ebee201405406dbf528b8b672104ae6d6d63e6d118cb10e4d51abbc7b58044ff"
dependencies = [
"aho-corasick",
"memchr",
- "regex-syntax 0.7.2",
+ "regex-automata 0.3.9",
+ "regex-syntax 0.7.5",
]
[[package]]
@@ -4112,6 +4101,17 @@ dependencies = [
"regex-syntax 0.6.29",
]
+[[package]]
+name = "regex-automata"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59b23e92ee4318893fa3fe3e6fb365258efbfe6ac6ab30f090cdcbb7aa37efa9"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax 0.7.5",
+]
+
[[package]]
name = "regex-cache"
version = "0.2.1"
@@ -4132,18 +4132,18 @@ checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1"
[[package]]
name = "regex-syntax"
-version = "0.7.2"
+version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "436b050e76ed2903236f032a59761c1eb99e1b0aead2c257922771dab1fc8c78"
+checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da"
[[package]]
name = "reqwest"
-version = "0.11.18"
+version = "0.11.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cde824a14b7c14f85caff81225f411faacc04a2013f41670f41443742b1c1c55"
+checksum = "046cd98826c46c2ac8ddecae268eb5c2e58628688a5fc7a2643704a73faba95b"
dependencies = [
"async-compression",
- "base64 0.21.2",
+ "base64 0.21.4",
"bytes",
"encoding_rs",
"futures-core",
@@ -4165,6 +4165,7 @@ dependencies = [
"serde",
"serde_json",
"serde_urlencoded",
+ "system-configuration",
"tokio",
"tokio-native-tls",
"tokio-util",
@@ -4224,7 +4225,7 @@ dependencies = [
"awc",
"aws-config",
"aws-sdk-s3",
- "base64 0.21.2",
+ "base64 0.21.4",
"bb8",
"blake3",
"bytes",
@@ -4284,7 +4285,7 @@ dependencies = [
"test_utils",
"thirtyfour",
"thiserror",
- "time 0.3.22",
+ "time",
"tokio",
"toml 0.7.4",
"url",
@@ -4301,7 +4302,7 @@ version = "0.1.0"
dependencies = [
"darling 0.14.4",
"diesel",
- "indexmap 2.0.0",
+ "indexmap 2.0.2",
"proc-macro2",
"quote",
"serde",
@@ -4326,7 +4327,7 @@ dependencies = [
"serde_json",
"serde_path_to_error",
"strum 0.24.1",
- "time 0.3.22",
+ "time",
"tokio",
"tracing",
"tracing-actix-web",
@@ -4339,18 +4340,18 @@ dependencies = [
[[package]]
name = "roxmltree"
-version = "0.18.0"
+version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d8f595a457b6b8c6cda66a48503e92ee8d19342f905948f29c383200ec9eb1d8"
+checksum = "862340e351ce1b271a378ec53f304a5558f7db87f3769dc655a8f6ecbb68b302"
dependencies = [
"xmlparser",
]
[[package]]
name = "rust-embed"
-version = "6.7.0"
+version = "6.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b73e721f488c353141288f223b599b4ae9303ecf3e62923f40a492f0634a4dc3"
+checksum = "a36224c3276f8c4ebc8c20f158eca7ca4359c8db89991c4925132aaaf6702661"
dependencies = [
"rust-embed-impl",
"rust-embed-utils",
@@ -4359,23 +4360,23 @@ dependencies = [
[[package]]
name = "rust-embed-impl"
-version = "6.6.0"
+version = "6.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e22ce362f5561923889196595504317a4372b84210e6e335da529a65ea5452b5"
+checksum = "49b94b81e5b2c284684141a2fb9e2a31be90638caf040bf9afbc5a0416afe1ac"
dependencies = [
"proc-macro2",
"quote",
"rust-embed-utils",
"shellexpand",
- "syn 2.0.29",
+ "syn 2.0.38",
"walkdir",
]
[[package]]
name = "rust-embed-utils"
-version = "7.5.0"
+version = "7.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "512b0ab6853f7e14e3c8754acb43d6f748bb9ced66aa5915a6553ac8213f7731"
+checksum = "9d38ff6bf570dc3bb7100fce9f7b60c33fa71d80e88da3f2580df4ff2bdded74"
dependencies = [
"sha2",
"walkdir",
@@ -4391,6 +4392,12 @@ dependencies = [
"ordered-multimap",
]
+[[package]]
+name = "rustc-demangle"
+version = "0.1.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76"
+
[[package]]
name = "rustc-hash"
version = "1.1.0"
@@ -4417,23 +4424,36 @@ dependencies = [
[[package]]
name = "rustix"
-version = "0.37.20"
+version = "0.37.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b96e891d04aa506a6d1f318d2771bcb1c7dfda84e126660ace067c9b474bb2c0"
+checksum = "4279d76516df406a8bd37e7dff53fd37d1a093f997a3c34a5c21658c126db06d"
dependencies = [
"bitflags 1.3.2",
"errno",
"io-lifetimes",
"libc",
- "linux-raw-sys",
- "windows-sys 0.48.0",
+ "linux-raw-sys 0.3.8",
+ "windows-sys",
+]
+
+[[package]]
+name = "rustix"
+version = "0.38.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f25469e9ae0f3d0047ca8b93fc56843f38e6774f0914a107ff8b41be8be8e0b7"
+dependencies = [
+ "bitflags 2.4.0",
+ "errno",
+ "libc",
+ "linux-raw-sys 0.4.8",
+ "windows-sys",
]
[[package]]
name = "rustls"
-version = "0.20.8"
+version = "0.20.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fff78fc74d175294f4e83b28343315ffcfb114b156f0185e9741cb5570f50e2f"
+checksum = "1b80e3dec595989ea8510028f30c408a4630db12c9cbb8de34203b89d6577e99"
dependencies = [
"log",
"ring",
@@ -4441,6 +4461,18 @@ dependencies = [
"webpki",
]
+[[package]]
+name = "rustls"
+version = "0.21.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd8d6c9f025a446bc4d18ad9632e69aec8f287aa84499ee335599fabd20c3fd8"
+dependencies = [
+ "log",
+ "ring",
+ "rustls-webpki",
+ "sct",
+]
+
[[package]]
name = "rustls-native-certs"
version = "0.6.3"
@@ -4455,18 +4487,28 @@ dependencies = [
[[package]]
name = "rustls-pemfile"
-version = "1.0.2"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2d3987094b1d07b653b7dfdc3f70ce9a1da9c51ac18c1b06b662e4f9a0e9f4b2"
+dependencies = [
+ "base64 0.21.4",
+]
+
+[[package]]
+name = "rustls-webpki"
+version = "0.101.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d194b56d58803a43635bdc398cd17e383d6f71f9182b9a192c127ca42494a59b"
+checksum = "3c7d5dece342910d9ba34d259310cae3e0154b873b35408b787b59bce53d34fe"
dependencies = [
- "base64 0.21.2",
+ "ring",
+ "untrusted",
]
[[package]]
name = "rustversion"
-version = "1.0.12"
+version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4f3208ce4d8448b3f3e7d168a73f5e0c43a61e32930de3bceeccedb388b6bf06"
+checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4"
[[package]]
name = "rusty-fork"
@@ -4482,9 +4524,9 @@ dependencies = [
[[package]]
name = "ryu"
-version = "1.0.13"
+version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f91339c0467de62360649f8d3e185ca8de4224ff281f66000de5eb2a77a79041"
+checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741"
[[package]]
name = "same-file"
@@ -4497,11 +4539,11 @@ dependencies = [
[[package]]
name = "schannel"
-version = "0.1.21"
+version = "0.1.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "713cfb06c7059f3588fb8044c0fad1d09e3c01d225e25b9220dbfdcf16dbb1b3"
+checksum = "0c3733bf4cf7ea0880754e19cb5a462007c4a8c1914bff372ccc95b464f1df88"
dependencies = [
- "windows-sys 0.42.0",
+ "windows-sys",
]
[[package]]
@@ -4534,7 +4576,7 @@ dependencies = [
"storage_impl",
"strum 0.24.1",
"thiserror",
- "time 0.3.22",
+ "time",
"tokio",
"uuid",
]
@@ -4547,9 +4589,9 @@ checksum = "1d51f5df5af43ab3f1360b429fa5e0152ac5ce8c0bd6485cae490332e96846a8"
[[package]]
name = "scopeguard"
-version = "1.1.0"
+version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "sct"
@@ -4563,9 +4605,9 @@ dependencies = [
[[package]]
name = "security-framework"
-version = "2.9.1"
+version = "2.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1fc758eb7bffce5b308734e9b0c1468893cae9ff70ebf13e7090be8dcbcc83a8"
+checksum = "05b64fb303737d99b81884b2c63433e9ae28abebe5eb5045dcdd175dc2ecf4de"
dependencies = [
"bitflags 1.3.2",
"core-foundation",
@@ -4576,9 +4618,9 @@ dependencies = [
[[package]]
name = "security-framework-sys"
-version = "2.9.0"
+version = "2.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f51d0c0d83bec45f16480d0ce0058397a69e48fcdc52d1dc8855fb68acbd31a7"
+checksum = "e932934257d3b408ed8f30db49d85ea163bfe74961f017f405b025af298f0c7a"
dependencies = [
"core-foundation-sys",
"libc",
@@ -4586,9 +4628,9 @@ dependencies = [
[[package]]
name = "semver"
-version = "1.0.17"
+version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed"
+checksum = "ad977052201c6de01a8ef2aa3378c4bd23217a056337d1d6da40468d267a4fb0"
dependencies = [
"serde",
]
@@ -4610,7 +4652,7 @@ checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.29",
+ "syn 2.0.38",
]
[[package]]
@@ -4619,7 +4661,7 @@ version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b420ce6e3d8bd882e9b243c6eed35dbc9a6110c9769e74b584e0d68d1f20c65"
dependencies = [
- "indexmap 2.0.0",
+ "indexmap 2.0.2",
"itoa",
"ryu",
"serde",
@@ -4627,18 +4669,19 @@ dependencies = [
[[package]]
name = "serde_path_to_error"
-version = "0.1.11"
+version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f7f05c1d5476066defcdfacce1f52fc3cae3af1d3089727100c02ae92e5abbe0"
+checksum = "4beec8bce849d58d06238cb50db2e1c417cfeafa4c63f692b15c82b7c80f8335"
dependencies = [
+ "itoa",
"serde",
]
[[package]]
name = "serde_plain"
-version = "1.0.1"
+version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d6018081315db179d0ce57b1fe4b62a12a0028c9cf9bbef868c9cf477b3c34ae"
+checksum = "9ce1fc6db65a611022b23a0dec6975d63fb80a302cb3388835ff02c097258d50"
dependencies = [
"serde",
]
@@ -4667,20 +4710,20 @@ dependencies = [
[[package]]
name = "serde_repr"
-version = "0.1.12"
+version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bcec881020c684085e55a25f7fd888954d56609ef363479dc5a1305eb0d40cab"
+checksum = "8725e1dfadb3a50f7e5ce0b1a540466f6ed3fe7a0fca2ac2b8b831d31316bd00"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.29",
+ "syn 2.0.38",
]
[[package]]
name = "serde_spanned"
-version = "0.6.2"
+version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "93107647184f6027e3b7dcb2e11034cf95ffa1e3a682c67951963ac69c1c007d"
+checksum = "96426c9936fd7a0124915f9185ea1d20aa9445cc9821142f0a73bc9207a2e186"
dependencies = [
"serde",
]
@@ -4699,30 +4742,31 @@ dependencies = [
[[package]]
name = "serde_with"
-version = "3.0.0"
+version = "3.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9f02d8aa6e3c385bf084924f660ce2a3a6bd333ba55b35e8590b321f35d88513"
+checksum = "1ca3b16a3d82c4088f343b7480a93550b3eabe1a358569c2dfe38bbcead07237"
dependencies = [
- "base64 0.21.2",
+ "base64 0.21.4",
"chrono",
"hex",
"indexmap 1.9.3",
+ "indexmap 2.0.2",
"serde",
"serde_json",
"serde_with_macros",
- "time 0.3.22",
+ "time",
]
[[package]]
name = "serde_with_macros"
-version = "3.0.0"
+version = "3.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "edc7d5d3932fb12ce722ee5e64dd38c504efba37567f0c402f6ca728c3b8b070"
+checksum = "2e6be15c453eb305019bfa438b1593c731f36a289a7853f7707ee29e870b3b3c"
dependencies = [
- "darling 0.20.1",
+ "darling 0.20.3",
"proc-macro2",
"quote",
- "syn 2.0.29",
+ "syn 2.0.38",
]
[[package]]
@@ -4747,7 +4791,7 @@ checksum = "91d129178576168c589c9ec973feedf7d3126c01ac2bf08795109aa35b69fb8f"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.29",
+ "syn 2.0.38",
]
[[package]]
@@ -4776,9 +4820,9 @@ dependencies = [
[[package]]
name = "sha1"
-version = "0.10.5"
+version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3"
+checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
dependencies = [
"cfg-if",
"cpufeatures",
@@ -4787,9 +4831,9 @@ dependencies = [
[[package]]
name = "sha2"
-version = "0.10.6"
+version = "0.10.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0"
+checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8"
dependencies = [
"cfg-if",
"cpufeatures",
@@ -4798,9 +4842,9 @@ dependencies = [
[[package]]
name = "sharded-slab"
-version = "0.1.4"
+version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "900fba806f70c630b0a382d0d825e17a0f19fcd059a2ade1ff237bcddf446b31"
+checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
dependencies = [
"lazy_static",
]
@@ -4816,9 +4860,9 @@ dependencies = [
[[package]]
name = "signal-hook"
-version = "0.3.15"
+version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "732768f1176d21d09e076c23a93123d40bba92d50c4058da34d45c8de8e682b9"
+checksum = "8621587d4798caf8eb44879d42e56b9a93ea5dcd315a6487c357130095b62801"
dependencies = [
"libc",
"signal-hook-registry",
@@ -4854,7 +4898,7 @@ dependencies = [
"num-bigint",
"num-traits",
"thiserror",
- "time 0.3.22",
+ "time",
]
[[package]]
@@ -4880,9 +4924,9 @@ dependencies = [
[[package]]
name = "slab"
-version = "0.4.8"
+version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6528351c9bc8ab22353f9d776db39a20288e8d6c37ef8cfe3317cf875eecfc2d"
+checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67"
dependencies = [
"autocfg",
]
@@ -4898,9 +4942,9 @@ dependencies = [
[[package]]
name = "smallvec"
-version = "1.10.0"
+version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0"
+checksum = "942b4a808e05215192e39f4ab80813e599068285906cc91aa64f923db842bd5a"
[[package]]
name = "socket2"
@@ -4912,6 +4956,16 @@ dependencies = [
"winapi",
]
+[[package]]
+name = "socket2"
+version = "0.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4031e820eb552adee9295814c0ced9e5cf38ddf1e8b7d566d6de8e2538ea989e"
+dependencies = [
+ "libc",
+ "windows-sys",
+]
+
[[package]]
name = "spin"
version = "0.5.2"
@@ -5009,7 +5063,7 @@ dependencies = [
"proc-macro2",
"quote",
"rustversion",
- "syn 2.0.29",
+ "syn 2.0.38",
]
[[package]]
@@ -5031,9 +5085,9 @@ dependencies = [
[[package]]
name = "syn"
-version = "2.0.29"
+version = "2.0.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c324c494eba9d92503e6f1ef2e6df781e78f6a7705a0202d9801b198807d518a"
+checksum = "e96b79aaa137db8f61e26363a0c9b47d8b4ec75da28b7d1d614c2303e232408b"
dependencies = [
"proc-macro2",
"quote",
@@ -5058,6 +5112,27 @@ dependencies = [
"unicode-xid",
]
+[[package]]
+name = "system-configuration"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba3a3adc5c275d719af8cb4272ea1c4a6d668a777f37e115f6d11ddbc1c8e0e7"
+dependencies = [
+ "bitflags 1.3.2",
+ "core-foundation",
+ "system-configuration-sys",
+]
+
+[[package]]
+name = "system-configuration-sys"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a75fb188eb626b924683e3b95e3a48e63551fcfb51949de2f06a9d91dbee93c9"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
[[package]]
name = "tagptr"
version = "0.2.0"
@@ -5066,16 +5141,15 @@ checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417"
[[package]]
name = "tempfile"
-version = "3.6.0"
+version = "3.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "31c0432476357e58790aaa47a8efb0c5138f137343f3b5f23bd36a27e3b0a6d6"
+checksum = "cb94d2f3cc536af71caac6b6fcebf65860b347e7ce0cc9ebe8f70d3e521054ef"
dependencies = [
- "autocfg",
"cfg-if",
- "fastrand",
+ "fastrand 2.0.1",
"redox_syscall 0.3.5",
- "rustix",
- "windows-sys 0.48.0",
+ "rustix 0.38.17",
+ "windows-sys",
]
[[package]]
@@ -5100,15 +5174,6 @@ dependencies = [
"unic-segment",
]
-[[package]]
-name = "termcolor"
-version = "1.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6"
-dependencies = [
- "winapi-util",
-]
-
[[package]]
name = "test-case"
version = "3.2.1"
@@ -5128,7 +5193,7 @@ dependencies = [
"proc-macro-error",
"proc-macro2",
"quote",
- "syn 2.0.29",
+ "syn 2.0.38",
]
[[package]]
@@ -5140,7 +5205,7 @@ dependencies = [
"proc-macro-error",
"proc-macro2",
"quote",
- "syn 2.0.29",
+ "syn 2.0.38",
"test-case-core",
]
@@ -5153,7 +5218,7 @@ dependencies = [
"api_models",
"async-trait",
"awc",
- "base64 0.21.2",
+ "base64 0.21.4",
"clap",
"derive_deref",
"masking",
@@ -5165,7 +5230,7 @@ dependencies = [
"serde_urlencoded",
"serial_test",
"thirtyfour",
- "time 0.3.22",
+ "time",
"tokio",
"toml 0.7.4",
"uuid",
@@ -5211,22 +5276,22 @@ dependencies = [
[[package]]
name = "thiserror"
-version = "1.0.40"
+version = "1.0.49"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "978c9a314bd8dc99be594bc3c175faaa9794be04a5a5e153caba6915336cebac"
+checksum = "1177e8c6d7ede7afde3585fd2513e611227efd6481bd78d2e82ba1ce16557ed4"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
-version = "1.0.40"
+version = "1.0.49"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f"
+checksum = "10712f02019e9288794769fba95cd6847df9874d49d871d062172f9dd41bc4cc"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.29",
+ "syn 2.0.38",
]
[[package]]
@@ -5250,17 +5315,6 @@ dependencies = [
"weezl",
]
-[[package]]
-name = "time"
-version = "0.1.45"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a"
-dependencies = [
- "libc",
- "wasi 0.10.0+wasi-snapshot-preview1",
- "winapi",
-]
-
[[package]]
name = "time"
version = "0.3.22"
@@ -5305,11 +5359,11 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
-version = "1.28.2"
+version = "1.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "94d7b1cfd2aa4011f2de74c2c4c63665e27a71006b0a192dcd2710272e73dfa2"
+checksum = "17ed6077ed6cd6c74735e21f37eb16dc3935f96878b1fe961074089cc80893f9"
dependencies = [
- "autocfg",
+ "backtrace",
"bytes",
"libc",
"mio",
@@ -5317,9 +5371,9 @@ dependencies = [
"parking_lot",
"pin-project-lite",
"signal-hook-registry",
- "socket2",
+ "socket2 0.5.4",
"tokio-macros",
- "windows-sys 0.48.0",
+ "windows-sys",
]
[[package]]
@@ -5340,7 +5394,7 @@ checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.29",
+ "syn 2.0.38",
]
[[package]]
@@ -5359,7 +5413,7 @@ version = "0.23.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c43ee83903113e03984cb9e5cebe6c04a5116269e900e3ddba8f068a62adda59"
dependencies = [
- "rustls",
+ "rustls 0.20.9",
"tokio",
"webpki",
]
@@ -5377,9 +5431,9 @@ dependencies = [
[[package]]
name = "tokio-util"
-version = "0.7.8"
+version = "0.7.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "806fe8c2c87eccc8b3267cbae29ed3ab2d0bd37fca70ab622e46aaa9375ddb7d"
+checksum = "1d68074620f57a0b21594d9735eb2e98ab38b17f80d3fcb189fca266771ca60d"
dependencies = [
"bytes",
"futures-core",
@@ -5412,9 +5466,9 @@ dependencies = [
[[package]]
name = "toml_datetime"
-version = "0.6.2"
+version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5a76a9312f5ba4c2dec6b9161fdf25d87ad8a09256ccea5a556fef03c706a10f"
+checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b"
dependencies = [
"serde",
]
@@ -5511,9 +5565,9 @@ dependencies = [
[[package]]
name = "tracing-actix-web"
-version = "0.7.5"
+version = "0.7.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ce52ffaf2d544e317d3bef63f49a6a22022866505fa4840a4339b1756834a2a9"
+checksum = "94982c2ad939d5d0bfd71c2f9b7ed273c72348485c72bb87bb4db6bd69df10cb"
dependencies = [
"actix-web",
"opentelemetry",
@@ -5530,7 +5584,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09d48f71a791638519505cefafe162606f706c25592e4bde4d97600c0195312e"
dependencies = [
"crossbeam-channel",
- "time 0.3.22",
+ "time",
"tracing-subscriber",
]
@@ -5623,9 +5677,9 @@ dependencies = [
[[package]]
name = "triomphe"
-version = "0.1.8"
+version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f1ee9bd9239c339d714d657fac840c6d2a4f9c45f4f9ec7b0975113458be78db"
+checksum = "0eee8098afad3fb0c54a9007aab6804558410503ad676d4633f9c2559a00ac0f"
[[package]]
name = "try-lock"
@@ -5635,15 +5689,15 @@ checksum = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed"
[[package]]
name = "typenum"
-version = "1.16.0"
+version = "1.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba"
+checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825"
[[package]]
name = "ucd-trie"
-version = "0.1.5"
+version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9e79c4d996edb816c91e4308506774452e55e95c3c9de07b6729e17e15a5ef81"
+checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9"
[[package]]
name = "unarray"
@@ -5703,9 +5757,9 @@ dependencies = [
[[package]]
name = "unicase"
-version = "2.6.0"
+version = "2.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6"
+checksum = "f7d2d4dafb69621809a81864c9c1b864479e1235c0dd4e199924b9742439ed89"
dependencies = [
"version_check",
]
@@ -5718,9 +5772,9 @@ checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460"
[[package]]
name = "unicode-ident"
-version = "1.0.9"
+version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0"
+checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
[[package]]
name = "unicode-normalization"
@@ -5757,9 +5811,9 @@ checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a"
[[package]]
name = "url"
-version = "2.4.0"
+version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "50bff7831e19200a85b17131d085c25d7811bc4e186efdaf54bbd132994a88cb"
+checksum = "143b538f18257fac9cad154828a57c6bf5157e1aa604d4816b5995bf6de87ae5"
dependencies = [
"form_urlencoded",
"idna",
@@ -5769,9 +5823,9 @@ dependencies = [
[[package]]
name = "urlencoding"
-version = "2.1.2"
+version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e8db7427f936968176eaa7cdf81b7f98b980b18495ec28f1b5791ac3bfe3eea9"
+checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
[[package]]
name = "urlparse"
@@ -5781,11 +5835,11 @@ checksum = "110352d4e9076c67839003c7788d8604e24dcded13e0b375af3efaa8cf468517"
[[package]]
name = "utoipa"
-version = "3.3.0"
+version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "68ae74ef183fae36d650f063ae7bde1cacbe1cd7e72b617cbe1e985551878b98"
+checksum = "d82b1bc5417102a73e8464c686eef947bdfb99fcdfc0a4f228e81afa9526470a"
dependencies = [
- "indexmap 1.9.3",
+ "indexmap 2.0.2",
"serde",
"serde_json",
"utoipa-gen",
@@ -5793,21 +5847,21 @@ dependencies = [
[[package]]
name = "utoipa-gen"
-version = "3.3.0"
+version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7ea8ac818da7e746a63285594cce8a96f5e00ee31994e655bd827569cb8b137b"
+checksum = "05d96dcd6fc96f3df9b3280ef480770af1b7c5d14bc55192baa9b067976d920c"
dependencies = [
"proc-macro-error",
"proc-macro2",
"quote",
- "syn 2.0.29",
+ "syn 2.0.38",
]
[[package]]
name = "utoipa-swagger-ui"
-version = "3.1.3"
+version = "3.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "062bba5a3568e126ac72049a63254f4cb1da2eb713db0c1ab2a4c76be191db8c"
+checksum = "84614caa239fb25b2bb373a52859ffd94605ceb256eeb1d63436325cf81e3653"
dependencies = [
"actix-web",
"mime_guess",
@@ -5821,9 +5875,9 @@ dependencies = [
[[package]]
name = "uuid"
-version = "1.3.4"
+version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0fa2982af2eec27de306107c027578ff7f423d65f7250e40ce0fea8f45248b81"
+checksum = "79daa5ed5740825c40b389c5e50312b9c86df53fccd33f281df655642b43869d"
dependencies = [
"getrandom 0.2.10",
"serde",
@@ -5851,7 +5905,7 @@ dependencies = [
"git2",
"rustc_version",
"rustversion",
- "time 0.3.22",
+ "time",
]
[[package]]
@@ -5877,15 +5931,15 @@ dependencies = [
[[package]]
name = "waker-fn"
-version = "1.1.0"
+version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9d5b2c62b4012a3e1eca5a7e077d13b3bf498c4073e33ccd58626607748ceeca"
+checksum = "f3c4517f54858c779bbcbf228f4fca63d121bf85fbecb2dc578cdf4a39395690"
[[package]]
name = "walkdir"
-version = "2.3.3"
+version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "36df944cda56c7d8d8b7496af378e6b16de9284591917d307c9b4d313c44e698"
+checksum = "d71d857dc86794ca4c280d616f7da00d2dbfd8cd788846559a6813e6aa4b54ee"
dependencies = [
"same-file",
"winapi-util",
@@ -5906,12 +5960,6 @@ version = "0.9.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519"
-[[package]]
-name = "wasi"
-version = "0.10.0+wasi-snapshot-preview1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f"
-
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
@@ -5939,7 +5987,7 @@ dependencies = [
"once_cell",
"proc-macro2",
"quote",
- "syn 2.0.29",
+ "syn 2.0.38",
"wasm-bindgen-shared",
]
@@ -5973,7 +6021,7 @@ checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.29",
+ "syn 2.0.38",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
@@ -6008,7 +6056,7 @@ dependencies = [
"serde",
"serde_derive",
"serde_json",
- "time 0.3.22",
+ "time",
"unicode-segmentation",
"url",
]
@@ -6056,9 +6104,9 @@ checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
-version = "0.1.5"
+version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"
+checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596"
dependencies = [
"winapi",
]
@@ -6078,21 +6126,6 @@ dependencies = [
"windows-targets",
]
-[[package]]
-name = "windows-sys"
-version = "0.42.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7"
-dependencies = [
- "windows_aarch64_gnullvm 0.42.2",
- "windows_aarch64_msvc 0.42.2",
- "windows_i686_gnu 0.42.2",
- "windows_i686_msvc 0.42.2",
- "windows_x86_64_gnu 0.42.2",
- "windows_x86_64_gnullvm 0.42.2",
- "windows_x86_64_msvc 0.42.2",
-]
-
[[package]]
name = "windows-sys"
version = "0.48.0"
@@ -6104,119 +6137,78 @@ dependencies = [
[[package]]
name = "windows-targets"
-version = "0.48.0"
+version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5"
+checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
dependencies = [
- "windows_aarch64_gnullvm 0.48.0",
- "windows_aarch64_msvc 0.48.0",
- "windows_i686_gnu 0.48.0",
- "windows_i686_msvc 0.48.0",
- "windows_x86_64_gnu 0.48.0",
- "windows_x86_64_gnullvm 0.48.0",
- "windows_x86_64_msvc 0.48.0",
+ "windows_aarch64_gnullvm",
+ "windows_aarch64_msvc",
+ "windows_i686_gnu",
+ "windows_i686_msvc",
+ "windows_x86_64_gnu",
+ "windows_x86_64_gnullvm",
+ "windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
-version = "0.42.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
-
-[[package]]
-name = "windows_aarch64_gnullvm"
-version = "0.48.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc"
-
-[[package]]
-name = "windows_aarch64_msvc"
-version = "0.42.2"
+version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
+checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
[[package]]
name = "windows_aarch64_msvc"
-version = "0.48.0"
+version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3"
+checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
[[package]]
name = "windows_i686_gnu"
-version = "0.42.2"
+version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
-
-[[package]]
-name = "windows_i686_gnu"
-version = "0.48.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241"
+checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
[[package]]
name = "windows_i686_msvc"
-version = "0.42.2"
+version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
-
-[[package]]
-name = "windows_i686_msvc"
-version = "0.48.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00"
-
-[[package]]
-name = "windows_x86_64_gnu"
-version = "0.42.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
+checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
[[package]]
name = "windows_x86_64_gnu"
-version = "0.48.0"
+version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1"
+checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
[[package]]
name = "windows_x86_64_gnullvm"
-version = "0.42.2"
+version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
-
-[[package]]
-name = "windows_x86_64_gnullvm"
-version = "0.48.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953"
+checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
[[package]]
name = "windows_x86_64_msvc"
-version = "0.42.2"
+version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
-
-[[package]]
-name = "windows_x86_64_msvc"
-version = "0.48.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a"
+checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
[[package]]
name = "winnow"
-version = "0.4.7"
+version = "0.4.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ca0ace3845f0d96209f0375e6d367e3eb87eb65d27d445bdc9f1843a26f39448"
+checksum = "656953b22bcbfb1ec8179d60734981d1904494ecc91f8a3f0ee5c7389bb8eb4b"
dependencies = [
"memchr",
]
[[package]]
name = "winreg"
-version = "0.10.1"
+version = "0.50.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d"
+checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1"
dependencies = [
- "winapi",
+ "cfg-if",
+ "windows-sys",
]
[[package]]
@@ -6227,7 +6219,7 @@ checksum = "c6f71803d3a1c80377a06221e0530be02035d5b3e854af56c6ece7ac20ac441d"
dependencies = [
"assert-json-diff",
"async-trait",
- "base64 0.21.2",
+ "base64 0.21.4",
"deadpool",
"futures",
"futures-timer",
@@ -6255,14 +6247,14 @@ dependencies = [
"oid-registry",
"rusticata-macros",
"thiserror",
- "time 0.3.22",
+ "time",
]
[[package]]
name = "xmlparser"
-version = "0.13.5"
+version = "0.13.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4d25c75bf9ea12c4040a97f829154768bbbce366287e2dc044af160cd79a13fd"
+checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4"
[[package]]
name = "yaml-rust"
@@ -6293,18 +6285,18 @@ dependencies = [
[[package]]
name = "zstd"
-version = "0.12.3+zstd.1.5.2"
+version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "76eea132fb024e0e13fd9c2f5d5d595d8a967aa72382ac2f9d39fcc95afd0806"
+checksum = "1a27595e173641171fc74a1232b7b1c7a7cb6e18222c11e9dfb9888fa424c53c"
dependencies = [
"zstd-safe",
]
[[package]]
name = "zstd-safe"
-version = "6.0.5+zstd.1.5.4"
+version = "6.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d56d9e60b4b1758206c238a10165fbcae3ca37b01744e394c463463f6529d23b"
+checksum = "ee98ffd0b48ee95e6c5168188e44a54550b1564d9d530ee21d5f0eaed1069581"
dependencies = [
"libc",
"zstd-sys",
diff --git a/crates/data_models/src/lib.rs b/crates/data_models/src/lib.rs
index a4376be88fd..f1e659ee9ec 100644
--- a/crates/data_models/src/lib.rs
+++ b/crates/data_models/src/lib.rs
@@ -23,3 +23,28 @@ pub enum MerchantStorageScheme {
PostgresOnly,
RedisKv,
}
+
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub enum RemoteStorageObject<T: ForeignIDRef> {
+ ForeignID(String),
+ Object(T),
+}
+
+impl<T: ForeignIDRef> From<T> for RemoteStorageObject<T> {
+ fn from(value: T) -> Self {
+ Self::Object(value)
+ }
+}
+
+pub trait ForeignIDRef {
+ fn foreign_id(&self) -> String;
+}
+
+impl<T: ForeignIDRef> RemoteStorageObject<T> {
+ pub fn get_id(&self) -> String {
+ match self {
+ Self::ForeignID(id) => id.clone(),
+ Self::Object(i) => i.foreign_id(),
+ }
+ }
+}
diff --git a/crates/data_models/src/payments.rs b/crates/data_models/src/payments.rs
index 5e8e1033013..5cdd167a8d3 100644
--- a/crates/data_models/src/payments.rs
+++ b/crates/data_models/src/payments.rs
@@ -1,2 +1,50 @@
+use common_utils::pii;
+use time::PrimitiveDateTime;
+
pub mod payment_attempt;
pub mod payment_intent;
+
+use common_enums as storage_enums;
+
+use self::payment_attempt::PaymentAttempt;
+use crate::RemoteStorageObject;
+
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct PaymentIntent {
+ pub id: i32,
+ pub payment_id: String,
+ pub merchant_id: String,
+ pub status: storage_enums::IntentStatus,
+ pub amount: i64,
+ pub currency: Option<storage_enums::Currency>,
+ pub amount_captured: Option<i64>,
+ pub customer_id: Option<String>,
+ pub description: Option<String>,
+ pub return_url: Option<String>,
+ pub metadata: Option<pii::SecretSerdeValue>,
+ pub connector_id: Option<String>,
+ pub shipping_address_id: Option<String>,
+ pub billing_address_id: Option<String>,
+ pub statement_descriptor_name: Option<String>,
+ pub statement_descriptor_suffix: Option<String>,
+ pub created_at: PrimitiveDateTime,
+ pub modified_at: PrimitiveDateTime,
+ pub last_synced: Option<PrimitiveDateTime>,
+ pub setup_future_usage: Option<storage_enums::FutureUsage>,
+ pub off_session: Option<bool>,
+ pub client_secret: Option<String>,
+ pub active_attempt: RemoteStorageObject<PaymentAttempt>,
+ pub business_country: Option<storage_enums::CountryAlpha2>,
+ pub business_label: Option<String>,
+ pub order_details: Option<Vec<pii::SecretSerdeValue>>,
+ pub allowed_payment_method_types: Option<serde_json::Value>,
+ pub connector_metadata: Option<serde_json::Value>,
+ pub feature_metadata: Option<serde_json::Value>,
+ pub attempt_count: i16,
+ pub profile_id: Option<String>,
+ pub payment_link_id: Option<String>,
+ // Denotes the action(approve or reject) taken by merchant in case of manual review.
+ // Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment
+ pub merchant_decision: Option<String>,
+ pub payment_confirm_source: Option<storage_enums::PaymentSource>,
+}
diff --git a/crates/data_models/src/payments/payment_attempt.rs b/crates/data_models/src/payments/payment_attempt.rs
index 29a83a30997..f711ae66381 100644
--- a/crates/data_models/src/payments/payment_attempt.rs
+++ b/crates/data_models/src/payments/payment_attempt.rs
@@ -3,8 +3,8 @@ use common_enums as storage_enums;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
-use super::payment_intent::PaymentIntent;
-use crate::{errors, mandates::MandateDataType, MerchantStorageScheme};
+use super::PaymentIntent;
+use crate::{errors, mandates::MandateDataType, ForeignIDRef, MerchantStorageScheme};
#[async_trait::async_trait]
pub trait PaymentAttemptInterface {
@@ -314,3 +314,9 @@ pub enum PaymentAttemptUpdate {
surcharge_metadata: Option<serde_json::Value>,
},
}
+
+impl ForeignIDRef for PaymentAttempt {
+ fn foreign_id(&self) -> String {
+ self.attempt_id.clone()
+ }
+}
diff --git a/crates/data_models/src/payments/payment_intent.rs b/crates/data_models/src/payments/payment_intent.rs
index 3d8f52d0006..57507aa6a3b 100644
--- a/crates/data_models/src/payments/payment_intent.rs
+++ b/crates/data_models/src/payments/payment_intent.rs
@@ -6,7 +6,8 @@ use common_utils::{
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
-use crate::{errors, MerchantStorageScheme};
+use super::{payment_attempt::PaymentAttempt, PaymentIntent};
+use crate::{errors, MerchantStorageScheme, RemoteStorageObject};
#[async_trait::async_trait]
pub trait PaymentIntentInterface {
async fn update_payment_intent(
@@ -29,6 +30,12 @@ pub trait PaymentIntentInterface {
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, errors::StorageError>;
+ async fn get_active_payment_attempt(
+ &self,
+ payment: &mut PaymentIntent,
+ storage_scheme: MerchantStorageScheme,
+ ) -> error_stack::Result<PaymentAttempt, errors::StorageError>;
+
#[cfg(feature = "olap")]
async fn filter_payment_intent_by_constraints(
&self,
@@ -51,10 +58,7 @@ pub trait PaymentIntentInterface {
merchant_id: &str,
constraints: &PaymentIntentFetchConstraints,
storage_scheme: MerchantStorageScheme,
- ) -> error_stack::Result<
- Vec<(PaymentIntent, super::payment_attempt::PaymentAttempt)>,
- errors::StorageError,
- >;
+ ) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, errors::StorageError>;
#[cfg(feature = "olap")]
async fn get_filtered_active_attempt_ids_for_total_count(
@@ -65,50 +69,7 @@ pub trait PaymentIntentInterface {
) -> error_stack::Result<Vec<String>, errors::StorageError>;
}
-#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
-pub struct PaymentIntent {
- pub id: i32,
- pub payment_id: String,
- pub merchant_id: String,
- pub status: storage_enums::IntentStatus,
- pub amount: i64,
- pub currency: Option<storage_enums::Currency>,
- pub amount_captured: Option<i64>,
- pub customer_id: Option<String>,
- pub description: Option<String>,
- pub return_url: Option<String>,
- pub metadata: Option<pii::SecretSerdeValue>,
- pub connector_id: Option<String>,
- pub shipping_address_id: Option<String>,
- pub billing_address_id: Option<String>,
- pub statement_descriptor_name: Option<String>,
- pub statement_descriptor_suffix: Option<String>,
- #[serde(with = "common_utils::custom_serde::iso8601")]
- pub created_at: PrimitiveDateTime,
- #[serde(with = "common_utils::custom_serde::iso8601")]
- pub modified_at: PrimitiveDateTime,
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
- pub last_synced: Option<PrimitiveDateTime>,
- pub setup_future_usage: Option<storage_enums::FutureUsage>,
- pub off_session: Option<bool>,
- pub client_secret: Option<String>,
- pub active_attempt_id: String,
- pub business_country: Option<storage_enums::CountryAlpha2>,
- pub business_label: Option<String>,
- pub order_details: Option<Vec<pii::SecretSerdeValue>>,
- pub allowed_payment_method_types: Option<serde_json::Value>,
- pub connector_metadata: Option<serde_json::Value>,
- pub feature_metadata: Option<serde_json::Value>,
- pub attempt_count: i16,
- pub profile_id: Option<String>,
- // Denotes the action(approve or reject) taken by merchant in case of manual review.
- // Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment
- pub merchant_decision: Option<String>,
- pub payment_link_id: Option<String>,
- pub payment_confirm_source: Option<storage_enums::PaymentSource>,
-}
-
-#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
+#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PaymentIntentNew {
pub payment_id: String,
pub merchant_id: String,
@@ -125,16 +86,13 @@ pub struct PaymentIntentNew {
pub billing_address_id: Option<String>,
pub statement_descriptor_name: Option<String>,
pub statement_descriptor_suffix: Option<String>,
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub created_at: Option<PrimitiveDateTime>,
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub modified_at: Option<PrimitiveDateTime>,
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub off_session: Option<bool>,
pub client_secret: Option<String>,
- pub active_attempt_id: String,
+ pub active_attempt: RemoteStorageObject<PaymentAttempt>,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
pub order_details: Option<Vec<pii::SecretSerdeValue>>,
diff --git a/crates/diesel_models/src/kv.rs b/crates/diesel_models/src/kv.rs
index ed886c783f9..f1145a4b6e1 100644
--- a/crates/diesel_models/src/kv.rs
+++ b/crates/diesel_models/src/kv.rs
@@ -6,9 +6,10 @@ use crate::{
connector_response::{ConnectorResponse, ConnectorResponseNew, ConnectorResponseUpdate},
errors,
payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate},
- payment_intent::{PaymentIntent, PaymentIntentNew, PaymentIntentUpdate},
+ payment_intent::{PaymentIntentNew, PaymentIntentUpdate},
refund::{Refund, RefundNew, RefundUpdate},
reverse_lookup::ReverseLookupNew,
+ PaymentIntent,
};
#[derive(Debug, Serialize, Deserialize)]
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index 1669cd7e779..82cfc05eaff 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -165,7 +165,6 @@ pub enum PaymentIntentUpdate {
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = payment_intent)]
-
pub struct PaymentIntentUpdateInternal {
pub amount: Option<i64>,
pub currency: Option<storage_enums::Currency>,
diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs
index 8e2fc729dbf..4737233e304 100644
--- a/crates/diesel_models/src/query/payment_attempt.rs
+++ b/crates/diesel_models/src/query/payment_attempt.rs
@@ -15,10 +15,9 @@ use crate::{
payment_attempt::{
PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate, PaymentAttemptUpdateInternal,
},
- payment_intent::PaymentIntent,
query::generics::db_metrics,
schema::payment_attempt::dsl,
- PgPooledConn, StorageResult,
+ PaymentIntent, PgPooledConn, StorageResult,
};
impl PaymentAttemptNew {
diff --git a/crates/drainer/src/lib.rs b/crates/drainer/src/lib.rs
index 632fb4a0c14..7dcbc2c518c 100644
--- a/crates/drainer/src/lib.rs
+++ b/crates/drainer/src/lib.rs
@@ -122,7 +122,8 @@ async fn drainer_handler(
active_tasks.fetch_add(1, atomic::Ordering::Release);
let stream_name = utils::get_drainer_stream_name(store.clone(), stream_index);
- let drainer_result = drainer(store.clone(), max_read_count, stream_name.as_str()).await;
+ let drainer_result =
+ Box::pin(drainer(store.clone(), max_read_count, stream_name.as_str())).await;
if let Err(error) = drainer_result {
logger::error!(?error)
diff --git a/crates/router/src/connector/trustpay.rs b/crates/router/src/connector/trustpay.rs
index b631a9611c1..d0597412170 100644
--- a/crates/router/src/connector/trustpay.rs
+++ b/crates/router/src/connector/trustpay.rs
@@ -115,7 +115,7 @@ impl ConnectorCommon for Trustpay {
match response {
Ok(response_data) => {
- let error_list = response_data.errors.clone().unwrap_or(vec![]);
+ let error_list = response_data.errors.clone().unwrap_or_default();
let option_error_code_message = get_error_code_error_message_based_on_priority(
self.clone(),
error_list.into_iter().map(|errors| errors.into()).collect(),
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 850daeba75f..422c3fa1988 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -7,7 +7,7 @@ pub use api_models::{
payouts as payout_types,
};
pub use common_utils::request::RequestBody;
-use data_models::payments::{payment_attempt::PaymentAttempt, payment_intent::PaymentIntent};
+use data_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
use diesel_models::enums;
use crate::{
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index c775dbc6ecd..2161ab69222 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -859,7 +859,7 @@ pub async fn list_payment_methods(
db.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&pi.payment_id,
&pi.merchant_id,
- &pi.active_attempt_id,
+ &pi.active_attempt.get_id(),
merchant_account.storage_scheme,
)
.await
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 39c709687d8..20712a64397 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1619,7 +1619,7 @@ pub async fn list_payments(
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&pi.payment_id,
merchant_id,
- &pi.active_attempt_id,
+ &pi.active_attempt.get_id(),
// since OLAP doesn't have KV. Force to get the data from PSQL.
storage_enums::MerchantStorageScheme::PostgresOnly,
)
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index c513ed02ae0..7a6b0f3a8d8 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -7,7 +7,7 @@ use common_utils::{
};
use data_models::{
mandates::MandateData,
- payments::{payment_attempt::PaymentAttempt, payment_intent::PaymentIntent},
+ payments::{payment_attempt::PaymentAttempt, PaymentIntent},
};
use diesel_models::enums;
// TODO : Evaluate all the helper functions ()
@@ -2392,7 +2392,7 @@ mod tests {
setup_future_usage: None,
off_session: None,
client_secret: Some("1".to_string()),
- active_attempt_id: "nopes".to_string(),
+ active_attempt: data_models::RemoteStorageObject::ForeignID("nopes".to_string()),
business_country: None,
business_label: None,
order_details: None,
@@ -2440,7 +2440,7 @@ mod tests {
setup_future_usage: None,
off_session: None,
client_secret: Some("1".to_string()),
- active_attempt_id: "nopes".to_string(),
+ active_attempt: data_models::RemoteStorageObject::ForeignID("nopes".to_string()),
business_country: None,
business_label: None,
order_details: None,
@@ -2488,7 +2488,7 @@ mod tests {
setup_future_usage: None,
off_session: None,
client_secret: None,
- active_attempt_id: "nopes".to_string(),
+ active_attempt: data_models::RemoteStorageObject::ForeignID("nopes".to_string()),
business_country: None,
business_label: None,
order_details: None,
@@ -2930,7 +2930,7 @@ impl AttemptType {
&request.payment_method_data,
Some(true),
),
- active_attempt_id: new_payment_attempt.attempt_id.to_owned(),
+ active_attempt_id: new_payment_attempt.attempt_id.clone(),
attempt_count: new_attempt_count,
},
storage_scheme,
diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs
index 95995c46bfb..5b7b475988f 100644
--- a/crates/router/src/core/payments/operations/payment_approve.rs
+++ b/crates/router/src/core/payments/operations/payment_approve.rs
@@ -100,7 +100,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
field_name: "browser_info",
})?;
- let attempt_id = payment_intent.active_attempt_id.clone();
+ let attempt_id = payment_intent.active_attempt.get_id().clone();
payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs
index cd221c0be70..9159153aeef 100644
--- a/crates/router/src/core/payments/operations/payment_cancel.rs
+++ b/crates/router/src/core/payments/operations/payment_cancel.rs
@@ -76,7 +76,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
payment_intent.payment_id.as_str(),
merchant_id,
- payment_intent.active_attempt_id.as_str(),
+ payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
)
.await
diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs
index 0d5dd5c7741..63869781ba9 100644
--- a/crates/router/src/core/payments/operations/payment_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_capture.rs
@@ -66,7 +66,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
payment_intent.payment_id.as_str(),
merchant_id,
- payment_intent.active_attempt_id.as_str(),
+ payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
)
.await
diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
index 25143df386a..0e357f08734 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -103,7 +103,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
merchant_id,
- &payment_intent.active_attempt_id,
+ &payment_intent.active_attempt.get_id(),
storage_scheme,
)
.await
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 86304cbf175..9ee079fbd0e 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -105,11 +105,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
// Stage 2
+ let attempt_id = payment_intent.active_attempt.get_id();
let payment_attempt_fut = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
payment_intent.payment_id.as_str(),
merchant_id,
- payment_intent.active_attempt_id.as_str(),
+ attempt_id.as_str(),
storage_scheme,
)
.map(|x| x.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound));
@@ -163,11 +164,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
| api_models::enums::IntentStatus::RequiresConfirmation => {
let attempt_type = helpers::AttemptType::SameOld;
+ let attempt_id = payment_intent.active_attempt.get_id();
let connector_response_fut = attempt_type.get_connector_response(
db,
&payment_intent.payment_id,
&payment_intent.merchant_id,
- &payment_intent.active_attempt_id,
+ attempt_id.as_str(),
storage_scheme,
);
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index aec9a13f038..e073b15d4d7 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -3,7 +3,7 @@ use std::marker::PhantomData;
use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
use common_utils::ext_traits::{AsyncExt, Encode, ValueExt};
-use data_models::mandates::MandateData;
+use data_models::{mandates::MandateData, payments::payment_attempt::PaymentAttempt};
use diesel_models::ephemeral_key;
use error_stack::{self, ResultExt};
use router_derive::PaymentOperation;
@@ -364,7 +364,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
async fn add_task_to_process_tracker<'a>(
&'a self,
_state: &'a AppState,
- _payment_attempt: &storage::PaymentAttempt,
+ _payment_attempt: &PaymentAttempt,
_requeue: bool,
_schedule_time: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
@@ -701,7 +701,7 @@ impl PaymentCreate {
metadata: request.metadata.clone(),
business_country: request.business_country,
business_label: request.business_label.clone(),
- active_attempt_id,
+ active_attempt: data_models::RemoteStorageObject::ForeignID(active_attempt_id),
order_details,
amount_captured: None,
customer_id: None,
@@ -719,7 +719,7 @@ impl PaymentCreate {
#[instrument(skip_all)]
pub fn make_connector_response(
- payment_attempt: &storage::PaymentAttempt,
+ payment_attempt: &PaymentAttempt,
) -> storage::ConnectorResponseNew {
storage::ConnectorResponseNew {
payment_id: payment_attempt.payment_id.clone(),
diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs
index 77e0a7dce2b..48bac48aacf 100644
--- a/crates/router/src/core/payments/operations/payment_method_validate.rs
+++ b/crates/router/src/core/payments/operations/payment_method_validate.rs
@@ -121,7 +121,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
&payment_id,
merchant_id,
request,
- payment_attempt.attempt_id.to_owned(),
+ payment_attempt.attempt_id.clone(),
),
storage_scheme,
)
@@ -375,9 +375,27 @@ impl PaymentMethodValidate {
client_secret: Some(client_secret),
setup_future_usage: request.setup_future_usage,
off_session: request.off_session,
- active_attempt_id,
+ active_attempt: data_models::RemoteStorageObject::ForeignID(active_attempt_id),
attempt_count: 1,
- ..Default::default()
+ amount_captured: Default::default(),
+ customer_id: Default::default(),
+ description: Default::default(),
+ return_url: Default::default(),
+ metadata: Default::default(),
+ shipping_address_id: Default::default(),
+ billing_address_id: Default::default(),
+ statement_descriptor_name: Default::default(),
+ statement_descriptor_suffix: Default::default(),
+ business_country: Default::default(),
+ business_label: Default::default(),
+ order_details: Default::default(),
+ allowed_payment_method_types: Default::default(),
+ connector_metadata: Default::default(),
+ feature_metadata: Default::default(),
+ profile_id: Default::default(),
+ merchant_decision: Default::default(),
+ payment_confirm_source: Default::default(),
+ payment_link_id: Default::default(),
}
}
}
diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs
index 938ce92af29..08731f5aa34 100644
--- a/crates/router/src/core/payments/operations/payment_reject.rs
+++ b/crates/router/src/core/payments/operations/payment_reject.rs
@@ -69,7 +69,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
"reject",
)?;
- let attempt_id = payment_intent.active_attempt_id.clone();
+ let attempt_id = payment_intent.active_attempt.get_id().clone();
let payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
payment_intent.payment_id.as_str(),
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 1decf13b37e..b9f78cb81ed 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -87,7 +87,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
payment_intent.payment_id.as_str(),
merchant_id,
- payment_intent.active_attempt_id.as_str(),
+ payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
)
.await
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index c3462079cb0..227e7e2f90d 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -86,7 +86,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
payment_intent.payment_id.as_str(),
merchant_id,
- payment_intent.active_attempt_id.as_str(),
+ payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
)
.await
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index ed642d3c468..d20830d9bc6 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -466,7 +466,7 @@ pub async fn get_payment_intent_payment_attempt(
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
pi.payment_id.as_str(),
merchant_id,
- pi.active_attempt_id.as_str(),
+ pi.active_attempt.get_id().as_str(),
storage_scheme,
)
.await?;
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 12c065c53eb..257793ce782 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -124,7 +124,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
payment_intent.payment_id.as_str(),
merchant_id,
- payment_intent.active_attempt_id.as_str(),
+ payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
)
.await
diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs
index 623a5f94989..92ead76e913 100644
--- a/crates/router/src/types/storage.rs
+++ b/crates/router/src/types/storage.rs
@@ -32,7 +32,8 @@ pub mod refund;
pub use data_models::payments::{
payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate},
- payment_intent::{PaymentIntent, PaymentIntentNew, PaymentIntentUpdate},
+ payment_intent::{PaymentIntentNew, PaymentIntentUpdate},
+ PaymentIntent,
};
pub use self::{
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 2e376b0c218..8686729ea2b 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -463,9 +463,8 @@ impl ForeignFrom<storage::Config> for api_types::Config {
impl<'a> ForeignFrom<&'a api_types::ConfigUpdate> for storage::ConfigUpdate {
fn foreign_from(config: &api_types::ConfigUpdate) -> Self {
- let config_update = config;
Self::Update {
- config: Some(config_update.value.clone()),
+ config: Some(config.value.clone()),
}
}
}
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index bf2f5943fc2..fa92cd11199 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -15,7 +15,7 @@ pub use common_utils::{
fp_utils::when,
validation::validate_email,
};
-use data_models::payments::payment_intent::PaymentIntent;
+use data_models::payments::PaymentIntent;
use error_stack::{IntoReport, ResultExt};
use image::Luma;
use nanoid::nanoid;
diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs
index ca043ac587b..8674f761568 100644
--- a/crates/storage_impl/src/mock_db.rs
+++ b/crates/storage_impl/src/mock_db.rs
@@ -2,7 +2,7 @@ use std::sync::Arc;
use data_models::{
errors::StorageError,
- payments::{payment_attempt::PaymentAttempt, payment_intent::PaymentIntent},
+ payments::{payment_attempt::PaymentAttempt, PaymentIntent},
};
use diesel_models::{self as store};
use error_stack::ResultExt;
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index e74de71c852..21343bd31e8 100644
--- a/crates/storage_impl/src/mock_db/payment_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs
@@ -26,7 +26,7 @@ impl PaymentAttemptInterface for MockDb {
async fn get_filters_for_payments(
&self,
- _pi: &[data_models::payments::payment_intent::PaymentIntent],
+ _pi: &[data_models::payments::PaymentIntent],
_merchant_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<data_models::payments::payment_attempt::PaymentListFilters, StorageError>
diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs
index 2dc720b9f5d..692847e14e9 100644
--- a/crates/storage_impl/src/mock_db/payment_intent.rs
+++ b/crates/storage_impl/src/mock_db/payment_intent.rs
@@ -1,8 +1,10 @@
use common_utils::errors::CustomResult;
use data_models::{
errors::StorageError,
- payments::payment_intent::{
- PaymentIntent, PaymentIntentInterface, PaymentIntentNew, PaymentIntentUpdate,
+ payments::{
+ payment_attempt::PaymentAttempt,
+ payment_intent::{PaymentIntentInterface, PaymentIntentNew, PaymentIntentUpdate},
+ PaymentIntent,
},
MerchantStorageScheme,
};
@@ -48,13 +50,7 @@ impl PaymentIntentInterface for MockDb {
_merchant_id: &str,
_constraints: &data_models::payments::payment_intent::PaymentIntentFetchConstraints,
_storage_scheme: MerchantStorageScheme,
- ) -> error_stack::Result<
- Vec<(
- PaymentIntent,
- data_models::payments::payment_attempt::PaymentAttempt,
- )>,
- StorageError,
- > {
+ ) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
@@ -97,7 +93,7 @@ impl PaymentIntentInterface for MockDb {
client_secret: new.client_secret,
business_country: new.business_country,
business_label: new.business_label,
- active_attempt_id: new.active_attempt_id.to_owned(),
+ active_attempt: new.active_attempt,
order_details: new.order_details,
allowed_payment_method_types: new.allowed_payment_method_types,
connector_metadata: new.connector_metadata,
@@ -147,4 +143,24 @@ impl PaymentIntentInterface for MockDb {
.cloned()
.unwrap())
}
+
+ async fn get_active_payment_attempt(
+ &self,
+ payment: &mut PaymentIntent,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> error_stack::Result<PaymentAttempt, StorageError> {
+ match payment.active_attempt.clone() {
+ data_models::RemoteStorageObject::ForeignID(id) => {
+ let attempts = self.payment_attempts.lock().await;
+ let attempt = attempts
+ .iter()
+ .find(|pa| pa.attempt_id == id && pa.merchant_id == payment.merchant_id)
+ .ok_or(StorageError::ValueNotFound("Attempt not found".to_string()))?;
+
+ payment.active_attempt = attempt.clone().into();
+ Ok(attempt.clone())
+ }
+ data_models::RemoteStorageObject::Object(pa) => Ok(pa.clone()),
+ }
+ }
}
diff --git a/crates/storage_impl/src/payments.rs b/crates/storage_impl/src/payments.rs
index f4196e1eb23..b7d14c8fd63 100644
--- a/crates/storage_impl/src/payments.rs
+++ b/crates/storage_impl/src/payments.rs
@@ -1,7 +1,7 @@
pub mod payment_attempt;
pub mod payment_intent;
-use diesel_models::{payment_attempt::PaymentAttempt, payment_intent::PaymentIntent};
+use diesel_models::{payment_attempt::PaymentAttempt, PaymentIntent};
use crate::redis::kv_store::KvStorePartition;
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index b9b850a0aaa..2b84b8d7441 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -8,7 +8,7 @@ use data_models::{
PaymentAttempt, PaymentAttemptInterface, PaymentAttemptNew, PaymentAttemptUpdate,
PaymentListFilters,
},
- payment_intent::PaymentIntent,
+ PaymentIntent,
},
MerchantStorageScheme,
};
@@ -168,7 +168,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
.iter()
.cloned()
.map(|pi| pi.to_storage_model())
- .collect::<Vec<diesel_models::payment_intent::PaymentIntent>>();
+ .collect::<Vec<diesel_models::PaymentIntent>>();
DieselPaymentAttempt::get_filters_for_payments(&conn, intents.as_slice(), merchant_id)
.await
.map_err(|er| {
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index c4718b34258..07a732229d5 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -2,22 +2,21 @@
use async_bb8_diesel::AsyncRunQueryDsl;
use common_utils::{date_time, ext_traits::Encode};
#[cfg(feature = "olap")]
-use data_models::payments::{
- payment_attempt::PaymentAttempt, payment_intent::PaymentIntentFetchConstraints,
-};
+use data_models::payments::payment_intent::PaymentIntentFetchConstraints;
use data_models::{
errors::StorageError,
- payments::payment_intent::{
- PaymentIntent, PaymentIntentInterface, PaymentIntentNew, PaymentIntentUpdate,
+ payments::{
+ payment_attempt::PaymentAttempt,
+ payment_intent::{PaymentIntentInterface, PaymentIntentNew, PaymentIntentUpdate},
+ PaymentIntent,
},
- MerchantStorageScheme,
+ MerchantStorageScheme, RemoteStorageObject,
};
#[cfg(feature = "olap")]
use diesel::{associations::HasTable, ExpressionMethods, JoinOnDsl, QueryDsl};
-#[cfg(feature = "olap")]
-use diesel_models::query::generics::db_metrics;
use diesel_models::{
kv,
+ payment_attempt::PaymentAttempt as DieselPaymentAttempt,
payment_intent::{
PaymentIntent as DieselPaymentIntent, PaymentIntentNew as DieselPaymentIntentNew,
PaymentIntentUpdate as DieselPaymentIntentUpdate,
@@ -25,7 +24,7 @@ use diesel_models::{
};
#[cfg(feature = "olap")]
use diesel_models::{
- payment_attempt::PaymentAttempt as DieselPaymentAttempt,
+ query::generics::db_metrics,
schema::{payment_attempt::dsl as pa_dsl, payment_intent::dsl as pi_dsl},
};
use error_stack::{IntoReport, ResultExt};
@@ -35,6 +34,7 @@ use router_env::logger;
use router_env::{instrument, tracing};
use crate::{
+ diesel_error_to_data_error,
redis::kv_store::{kv_wrapper, KvOperation, PartitionKey},
utils::{pg_connection_read, pg_connection_write},
DataModelExt, DatabaseStore, KVRouterStore,
@@ -82,7 +82,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
client_secret: new.client_secret.clone(),
business_country: new.business_country,
business_label: new.business_label.clone(),
- active_attempt_id: new.active_attempt_id.to_owned(),
+ active_attempt: new.active_attempt.clone(),
order_details: new.order_details.clone(),
allowed_payment_method_types: new.allowed_payment_method_types.clone(),
connector_metadata: new.connector_metadata.clone(),
@@ -93,10 +93,11 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
payment_link_id: new.payment_link_id.clone(),
payment_confirm_source: new.payment_confirm_source,
};
+ let diesel_intent = created_intent.clone().to_storage_model();
- match kv_wrapper::<PaymentIntent, _, _>(
+ match kv_wrapper::<DieselPaymentIntent, _, _>(
self,
- KvOperation::HSetNx(&field, &created_intent),
+ KvOperation::HSetNx(&field, &diesel_intent),
&key,
)
.await
@@ -149,15 +150,16 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
let field = format!("pi_{}", this.payment_id);
let updated_intent = payment_intent.clone().apply_changeset(this.clone());
+ let diesel_intent = payment_intent.to_storage_model();
// Check for database presence as well Maybe use a read replica here ?
let redis_value =
- Encode::<PaymentIntent>::encode_to_string_of_json(&updated_intent)
+ Encode::<DieselPaymentIntent>::encode_to_string_of_json(&diesel_intent)
.change_context(StorageError::SerializationFailed)?;
kv_wrapper::<(), _, _>(
self,
- KvOperation::<PaymentIntent>::Hset((&field, redis_value)),
+ KvOperation::<DieselPaymentIntent>::Hset((&field, redis_value)),
&key,
)
.await
@@ -170,7 +172,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
updatable: kv::Updateable::PaymentIntentUpdate(
kv::PaymentIntentUpdateMems {
orig: this.to_storage_model(),
- update_data: payment_intent.to_storage_model(),
+ update_data: diesel_intent,
},
),
},
@@ -198,13 +200,13 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let database_call = || async {
- self.router_store
- .find_payment_intent_by_payment_id_merchant_id(
- payment_id,
- merchant_id,
- storage_scheme,
- )
+ let conn = pg_connection_read(self).await?;
+ DieselPaymentIntent::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id)
.await
+ .map_err(|er| {
+ let new_err = diesel_error_to_data_error(er.current_context());
+ er.change_context(new_err)
+ })
};
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
@@ -214,9 +216,9 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
let field = format!("pi_{payment_id}");
crate::utils::try_redis_get_else_try_database_get(
async {
- kv_wrapper::<PaymentIntent, _, _>(
+ kv_wrapper::<DieselPaymentIntent, _, _>(
self,
- KvOperation::<PaymentIntent>::HGet(&field),
+ KvOperation::<DieselPaymentIntent>::HGet(&field),
&key,
)
.await?
@@ -227,6 +229,34 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
.await
}
}
+ .map(PaymentIntent::from_storage_model)
+ }
+
+ async fn get_active_payment_attempt(
+ &self,
+ payment: &mut PaymentIntent,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> error_stack::Result<PaymentAttempt, StorageError> {
+ match payment.active_attempt.clone() {
+ data_models::RemoteStorageObject::ForeignID(attempt_id) => {
+ let conn = pg_connection_read(self).await?;
+
+ let pa = DieselPaymentAttempt::find_by_merchant_id_attempt_id(
+ &conn,
+ payment.merchant_id.as_str(),
+ attempt_id.as_str(),
+ )
+ .await
+ .map_err(|er| {
+ let new_err = diesel_error_to_data_error(er.current_context());
+ er.change_context(new_err)
+ })
+ .map(PaymentAttempt::from_storage_model)?;
+ payment.active_attempt = data_models::RemoteStorageObject::Object(pa.clone());
+ Ok(pa)
+ }
+ data_models::RemoteStorageObject::Object(pa) => Ok(pa.clone()),
+ }
}
#[cfg(feature = "olap")]
@@ -298,7 +328,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
.insert(&conn)
.await
.map_err(|er| {
- let new_err = crate::diesel_error_to_data_error(er.current_context());
+ let new_err = diesel_error_to_data_error(er.current_context());
er.change_context(new_err)
})
.map(PaymentIntent::from_storage_model)
@@ -315,7 +345,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
.update(&conn, payment_intent.to_storage_model())
.await
.map_err(|er| {
- let new_err = crate::diesel_error_to_data_error(er.current_context());
+ let new_err = diesel_error_to_data_error(er.current_context());
er.change_context(new_err)
})
.map(PaymentIntent::from_storage_model)
@@ -333,11 +363,38 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
.await
.map(PaymentIntent::from_storage_model)
.map_err(|er| {
- let new_err = crate::diesel_error_to_data_error(er.current_context());
+ let new_err = diesel_error_to_data_error(er.current_context());
er.change_context(new_err)
})
}
+ async fn get_active_payment_attempt(
+ &self,
+ payment: &mut PaymentIntent,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> error_stack::Result<PaymentAttempt, StorageError> {
+ match &payment.active_attempt {
+ data_models::RemoteStorageObject::ForeignID(attempt_id) => {
+ let conn = pg_connection_read(self).await?;
+
+ let pa = DieselPaymentAttempt::find_by_merchant_id_attempt_id(
+ &conn,
+ payment.merchant_id.as_str(),
+ attempt_id.as_str(),
+ )
+ .await
+ .map_err(|er| {
+ let new_err = diesel_error_to_data_error(er.current_context());
+ er.change_context(new_err)
+ })
+ .map(PaymentAttempt::from_storage_model)?;
+ payment.active_attempt = data_models::RemoteStorageObject::Object(pa.clone());
+ Ok(pa)
+ }
+ data_models::RemoteStorageObject::Object(pa) => Ok(pa.clone()),
+ }
+ }
+
#[cfg(feature = "olap")]
async fn filter_payment_intent_by_constraints(
&self,
@@ -688,7 +745,7 @@ impl DataModelExt for PaymentIntentNew {
setup_future_usage: self.setup_future_usage,
off_session: self.off_session,
client_secret: self.client_secret,
- active_attempt_id: self.active_attempt_id,
+ active_attempt_id: self.active_attempt.get_id(),
business_country: self.business_country,
business_label: self.business_label,
order_details: self.order_details,
@@ -726,7 +783,7 @@ impl DataModelExt for PaymentIntentNew {
setup_future_usage: storage_model.setup_future_usage,
off_session: storage_model.off_session,
client_secret: storage_model.client_secret,
- active_attempt_id: storage_model.active_attempt_id,
+ active_attempt: RemoteStorageObject::ForeignID(storage_model.active_attempt_id),
business_country: storage_model.business_country,
business_label: storage_model.business_label,
order_details: storage_model.order_details,
@@ -769,9 +826,9 @@ impl DataModelExt for PaymentIntent {
setup_future_usage: self.setup_future_usage,
off_session: self.off_session,
client_secret: self.client_secret,
+ active_attempt_id: self.active_attempt.get_id(),
business_country: self.business_country,
business_label: self.business_label,
- active_attempt_id: self.active_attempt_id,
order_details: self.order_details,
allowed_payment_method_types: self.allowed_payment_method_types,
connector_metadata: self.connector_metadata,
@@ -808,7 +865,7 @@ impl DataModelExt for PaymentIntent {
setup_future_usage: storage_model.setup_future_usage,
off_session: storage_model.off_session,
client_secret: storage_model.client_secret,
- active_attempt_id: storage_model.active_attempt_id,
+ active_attempt: RemoteStorageObject::ForeignID(storage_model.active_attempt_id),
business_country: storage_model.business_country,
business_label: storage_model.business_label,
order_details: storage_model.order_details,
@@ -928,104 +985,8 @@ impl DataModelExt for PaymentIntentUpdate {
}
}
- fn from_storage_model(storage_model: Self::StorageModel) -> Self {
- match storage_model {
- DieselPaymentIntentUpdate::ResponseUpdate {
- status,
- amount_captured,
- return_url,
- } => Self::ResponseUpdate {
- status,
- amount_captured,
- return_url,
- },
- DieselPaymentIntentUpdate::MetadataUpdate { metadata } => {
- Self::MetadataUpdate { metadata }
- }
- DieselPaymentIntentUpdate::ReturnUrlUpdate {
- return_url,
- status,
- customer_id,
- shipping_address_id,
- billing_address_id,
- } => Self::ReturnUrlUpdate {
- return_url,
- status,
- customer_id,
- shipping_address_id,
- billing_address_id,
- },
- DieselPaymentIntentUpdate::MerchantStatusUpdate {
- status,
- shipping_address_id,
- billing_address_id,
- } => Self::MerchantStatusUpdate {
- status,
- shipping_address_id,
- billing_address_id,
- },
- DieselPaymentIntentUpdate::PGStatusUpdate { status } => Self::PGStatusUpdate { status },
- DieselPaymentIntentUpdate::Update {
- amount,
- currency,
- setup_future_usage,
- status,
- customer_id,
- shipping_address_id,
- billing_address_id,
- return_url,
- business_country,
- business_label,
- description,
- statement_descriptor_name,
- statement_descriptor_suffix,
- order_details,
- metadata,
- payment_confirm_source,
- } => Self::Update {
- amount,
- currency,
- setup_future_usage,
- status,
- customer_id,
- shipping_address_id,
- billing_address_id,
- return_url,
- business_country,
- business_label,
- description,
- statement_descriptor_name,
- statement_descriptor_suffix,
- order_details,
- metadata,
- payment_confirm_source,
- },
- DieselPaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate {
- active_attempt_id,
- attempt_count,
- } => Self::PaymentAttemptAndAttemptCountUpdate {
- active_attempt_id,
- attempt_count,
- },
- DieselPaymentIntentUpdate::StatusAndAttemptUpdate {
- status,
- active_attempt_id,
- attempt_count,
- } => Self::StatusAndAttemptUpdate {
- status,
- active_attempt_id,
- attempt_count,
- },
- DieselPaymentIntentUpdate::ApproveUpdate { merchant_decision } => {
- Self::ApproveUpdate { merchant_decision }
- }
- DieselPaymentIntentUpdate::RejectUpdate {
- status,
- merchant_decision,
- } => Self::RejectUpdate {
- status,
- merchant_decision,
- },
- }
+ #[allow(clippy::todo)]
+ fn from_storage_model(_storage_model: Self::StorageModel) -> Self {
+ todo!("Reverse map should no longer be needed")
}
}
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 526c8204d67..971a573b8e4 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -6164,7 +6164,7 @@
"description": "Will be used to expire client secret after certain amount of time to be supplied in seconds\n(900) for 15 mins",
"example": 900,
"nullable": true,
- "minimum": 0.0
+ "minimum": 0
},
"organization_id": {
"type": "string",
@@ -6468,7 +6468,7 @@
"format": "int32",
"description": "Will be used to expire client secret after certain amount of time to be supplied in seconds\n(900) for 15 mins",
"nullable": true,
- "minimum": 0.0
+ "minimum": 0
},
"default_profile": {
"type": "string",
@@ -6483,8 +6483,7 @@
"description": "Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc.\"",
"required": [
"connector_type",
- "connector_name",
- "connector_label"
+ "connector_name"
],
"properties": {
"connector_type": {
@@ -6493,10 +6492,6 @@
"connector_name": {
"$ref": "#/components/schemas/Connector"
},
- "connector_label": {
- "type": "string",
- "example": "stripe_US_travel"
- },
"merchant_connector_id": {
"type": "string",
"description": "Unique ID of the connector",
@@ -6709,11 +6704,6 @@
"description": "Name of the Connector",
"example": "stripe"
},
- "connector_label": {
- "type": "string",
- "example": "stripe_US_travel",
- "nullable": true
- },
"merchant_connector_id": {
"type": "string",
"description": "Unique ID of the connector",
@@ -7236,13 +7226,13 @@
"type": "integer",
"format": "int64",
"description": "Timestamp at which session is requested",
- "minimum": 0.0
+ "minimum": 0
},
"expires_at": {
"type": "integer",
"format": "int64",
"description": "Timestamp at which session expires",
- "minimum": 0.0
+ "minimum": 0
},
"merchant_session_identifier": {
"type": "string",
@@ -7276,7 +7266,7 @@
"type": "integer",
"format": "int32",
"description": "The number of retries to get the session response",
- "minimum": 0.0
+ "minimum": 0
},
"psp_id": {
"type": "string",
@@ -7330,7 +7320,7 @@
"format": "int32",
"description": "The quantity of the product to be purchased",
"example": 1,
- "minimum": 0.0
+ "minimum": 0
}
}
},
@@ -7353,7 +7343,7 @@
"format": "int32",
"description": "The quantity of the product to be purchased",
"example": 1,
- "minimum": 0.0
+ "minimum": 0
},
"amount": {
"type": "integer",
@@ -7683,6 +7673,7 @@
"$ref": "#/components/schemas/AuthenticationType"
}
],
+ "default": "three_ds",
"nullable": true
},
"cancellation_reason": {
@@ -7867,8 +7858,8 @@
"format": "int32",
"description": "limit on the number of objects to return",
"default": 10,
- "maximum": 100.0,
- "minimum": 0.0
+ "maximum": 100,
+ "minimum": 0
},
"created": {
"type": "string",
@@ -7917,7 +7908,7 @@
"size": {
"type": "integer",
"description": "The number of payments included in the list",
- "minimum": 0.0
+ "minimum": 0
},
"data": {
"type": "array",
@@ -8520,14 +8511,7 @@
},
"PaymentsCaptureRequest": {
"type": "object",
- "required": [
- "payment_id"
- ],
"properties": {
- "payment_id": {
- "type": "string",
- "description": "The unique identifier for the payment"
- },
"merchant_id": {
"type": "string",
"description": "The unique identifier for the merchant",
@@ -8592,7 +8576,7 @@
"description": "The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,",
"example": 6540,
"nullable": true,
- "minimum": 0.0
+ "minimum": 0
},
"routing": {
"allOf": [
@@ -8726,6 +8710,7 @@
"$ref": "#/components/schemas/AuthenticationType"
}
],
+ "default": "three_ds",
"nullable": true
},
"payment_method_data": {
@@ -8947,7 +8932,7 @@
"description": "The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,",
"example": 6540,
"nullable": true,
- "minimum": 0.0
+ "minimum": 0
},
"routing": {
"allOf": [
@@ -9081,6 +9066,7 @@
"$ref": "#/components/schemas/AuthenticationType"
}
],
+ "default": "three_ds",
"nullable": true
},
"payment_method_data": {
@@ -9304,7 +9290,12 @@
"maxLength": 255
},
"status": {
- "$ref": "#/components/schemas/IntentStatus"
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/IntentStatus"
+ }
+ ],
+ "default": "requires_confirmation"
},
"amount": {
"type": "integer",
@@ -9318,7 +9309,7 @@
"description": "The maximum amount that could be captured from the payment",
"example": 6540,
"nullable": true,
- "minimum": 100.0
+ "minimum": 100
},
"amount_received": {
"type": "integer",
@@ -9326,7 +9317,7 @@
"description": "The amount which is already captured from the payment",
"example": 6540,
"nullable": true,
- "minimum": 100.0
+ "minimum": 100
},
"connector": {
"type": "string",
@@ -9514,6 +9505,7 @@
"$ref": "#/components/schemas/AuthenticationType"
}
],
+ "default": "three_ds",
"nullable": true
},
"statement_descriptor_name": {
@@ -10463,7 +10455,7 @@
"count": {
"type": "integer",
"description": "The number of refunds included in the list",
- "minimum": 0.0
+ "minimum": 0
},
"total_count": {
"type": "integer",
@@ -10513,7 +10505,7 @@
"description": "Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, this will default to the full payment amount",
"example": 6540,
"nullable": true,
- "minimum": 100.0
+ "minimum": 100
},
"reason": {
"type": "string",
@@ -10528,6 +10520,7 @@
"$ref": "#/components/schemas/RefundType"
}
],
+ "default": "Instant",
"nullable": true
},
"metadata": {
|
refactor
|
update paymentintent object to provide a relation with attempts (#2502)
|
d5e9866b522bad3e62f6f6c0d7993f5dcc2939af
|
2024-01-25 15:11:10
|
Sakil Mostak
|
feat(core): Add outgoing webhook for manual `partial_capture` events (#3388)
| false
|
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index aaa145099e4..68909d1127c 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -51,7 +51,7 @@ use crate::{
types::{encrypt_optional, AsyncLift},
},
storage,
- transformers::{ForeignTryFrom, ForeignTryInto},
+ transformers::ForeignFrom,
},
};
@@ -681,23 +681,6 @@ pub fn add_apple_pay_payment_status_metrics(
}
}
-impl ForeignTryFrom<enums::IntentStatus> for enums::EventType {
- type Error = errors::ValidationError;
-
- fn foreign_try_from(value: enums::IntentStatus) -> Result<Self, Self::Error> {
- match value {
- enums::IntentStatus::Succeeded => Ok(Self::PaymentSucceeded),
- enums::IntentStatus::Failed => Ok(Self::PaymentFailed),
- enums::IntentStatus::Processing => Ok(Self::PaymentProcessing),
- enums::IntentStatus::RequiresMerchantAction
- | enums::IntentStatus::RequiresCustomerAction => Ok(Self::ActionRequired),
- _ => Err(errors::ValidationError::IncorrectValueProvided {
- field_name: "intent_status",
- }),
- }
- }
-}
-
pub async fn trigger_payments_webhook<F, Req, Op>(
merchant_account: domain::MerchantAccount,
business_profile: diesel_models::business_profile::BusinessProfile,
@@ -726,7 +709,9 @@ where
if matches!(
status,
- enums::IntentStatus::Succeeded | enums::IntentStatus::Failed
+ enums::IntentStatus::Succeeded
+ | enums::IntentStatus::Failed
+ | enums::IntentStatus::PartiallyCaptured
) {
let payments_response = crate::core::payments::transformers::payments_to_payments_response(
req,
@@ -742,11 +727,7 @@ where
None,
)?;
- let event_type: enums::EventType = status
- .foreign_try_into()
- .into_report()
- .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
- .attach_printable("payment event type mapping failed")?;
+ let event_type = ForeignFrom::foreign_from(status);
if let services::ApplicationResponse::JsonWithHeaders((payments_response_json, _)) =
payments_response
@@ -755,27 +736,34 @@ where
// This spawns this futures in a background thread, the exception inside this future won't affect
// the current thread and the lifecycle of spawn thread is not handled by runtime.
// So when server shutdown won't wait for this thread's completion.
- tokio::spawn(
- async move {
- Box::pin(
- webhooks_core::create_event_and_trigger_appropriate_outgoing_webhook(
- m_state,
- merchant_account,
- business_profile,
- event_type,
- diesel_models::enums::EventClass::Payments,
- None,
- payment_id,
- diesel_models::enums::EventObjectType::PaymentDetails,
- webhooks::OutgoingWebhookContent::PaymentDetails(
- payments_response_json,
+
+ if let Some(event_type) = event_type {
+ tokio::spawn(
+ async move {
+ Box::pin(
+ webhooks_core::create_event_and_trigger_appropriate_outgoing_webhook(
+ m_state,
+ merchant_account,
+ business_profile,
+ event_type,
+ diesel_models::enums::EventClass::Payments,
+ None,
+ payment_id,
+ diesel_models::enums::EventObjectType::PaymentDetails,
+ webhooks::OutgoingWebhookContent::PaymentDetails(
+ payments_response_json,
+ ),
),
- ),
- )
- .await
- }
- .in_current_span(),
- );
+ )
+ .await
+ }
+ .in_current_span(),
+ );
+ } else {
+ logger::warn!(
+ "Outgoing webhook not sent because of missing event type status mapping"
+ );
+ }
}
}
|
feat
|
Add outgoing webhook for manual `partial_capture` events (#3388)
|
ecaf70099671950287e9a6b7d30ffd02c0c5f51e
|
2024-10-24 19:30:17
|
Jeeva Ramachandran
|
chore: Add samsung pay payment method support for cybersource (#6424)
| false
|
diff --git a/crates/connector_configs/src/common_config.rs b/crates/connector_configs/src/common_config.rs
index d0becb80468..26c9d33f405 100644
--- a/crates/connector_configs/src/common_config.rs
+++ b/crates/connector_configs/src/common_config.rs
@@ -206,7 +206,7 @@ pub enum InputType {
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, serde::Serialize, Clone)]
#[serde(rename_all = "snake_case")]
-pub struct MetaDataInupt {
+pub struct InputData {
pub name: String,
pub label: String,
pub placeholder: String,
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index 7916efc1a84..923edd386de 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -10,7 +10,7 @@ use serde::Deserialize;
#[cfg(any(feature = "sandbox", feature = "development", feature = "production"))]
use toml;
-use crate::common_config::{CardProvider, MetaDataInupt, Provider, ZenApplePay};
+use crate::common_config::{CardProvider, InputData, Provider, ZenApplePay};
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Classic {
@@ -83,38 +83,44 @@ pub enum KlarnaEndpoint {
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, serde::Serialize, Clone)]
pub struct ConfigMerchantAdditionalDetails {
- pub open_banking_recipient_data: Option<MetaDataInupt>,
- pub account_data: Option<MetaDataInupt>,
- pub iban: Option<Vec<MetaDataInupt>>,
- pub bacs: Option<Vec<MetaDataInupt>>,
- pub connector_recipient_id: Option<MetaDataInupt>,
- pub wallet_id: Option<MetaDataInupt>,
+ pub open_banking_recipient_data: Option<InputData>,
+ pub account_data: Option<InputData>,
+ pub iban: Option<Vec<InputData>>,
+ pub bacs: Option<Vec<InputData>>,
+ pub connector_recipient_id: Option<InputData>,
+ pub wallet_id: Option<InputData>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, serde::Serialize, Clone)]
pub struct ConfigMetadata {
- pub merchant_config_currency: Option<MetaDataInupt>,
- pub merchant_account_id: Option<MetaDataInupt>,
- pub account_name: Option<MetaDataInupt>,
- pub terminal_id: Option<MetaDataInupt>,
- pub google_pay: Option<Vec<MetaDataInupt>>,
- pub apple_pay: Option<Vec<MetaDataInupt>>,
- pub merchant_id: Option<MetaDataInupt>,
- pub endpoint_prefix: Option<MetaDataInupt>,
- pub mcc: Option<MetaDataInupt>,
- pub merchant_country_code: Option<MetaDataInupt>,
- pub merchant_name: Option<MetaDataInupt>,
- pub acquirer_bin: Option<MetaDataInupt>,
- pub acquirer_merchant_id: Option<MetaDataInupt>,
- pub acquirer_country_code: Option<MetaDataInupt>,
- pub three_ds_requestor_name: Option<MetaDataInupt>,
- pub three_ds_requestor_id: Option<MetaDataInupt>,
- pub pull_mechanism_for_external_3ds_enabled: Option<MetaDataInupt>,
- pub klarna_region: Option<MetaDataInupt>,
- pub source_balance_account: Option<MetaDataInupt>,
- pub brand_id: Option<MetaDataInupt>,
- pub destination_account_number: Option<MetaDataInupt>,
+ pub merchant_config_currency: Option<InputData>,
+ pub merchant_account_id: Option<InputData>,
+ pub account_name: Option<InputData>,
+ pub terminal_id: Option<InputData>,
+ pub google_pay: Option<Vec<InputData>>,
+ pub apple_pay: Option<Vec<InputData>>,
+ pub merchant_id: Option<InputData>,
+ pub endpoint_prefix: Option<InputData>,
+ pub mcc: Option<InputData>,
+ pub merchant_country_code: Option<InputData>,
+ pub merchant_name: Option<InputData>,
+ pub acquirer_bin: Option<InputData>,
+ pub acquirer_merchant_id: Option<InputData>,
+ pub acquirer_country_code: Option<InputData>,
+ pub three_ds_requestor_name: Option<InputData>,
+ pub three_ds_requestor_id: Option<InputData>,
+ pub pull_mechanism_for_external_3ds_enabled: Option<InputData>,
+ pub klarna_region: Option<InputData>,
+ pub source_balance_account: Option<InputData>,
+ pub brand_id: Option<InputData>,
+ pub destination_account_number: Option<InputData>,
+}
+
+#[serde_with::skip_serializing_none]
+#[derive(Debug, Deserialize, serde::Serialize, Clone)]
+pub struct ConnectorWalletDetailsConfig {
+ pub samsung_pay: Option<Vec<InputData>>,
}
#[serde_with::skip_serializing_none]
@@ -123,6 +129,7 @@ pub struct ConnectorTomlConfig {
pub connector_auth: Option<ConnectorAuthType>,
pub connector_webhook_details: Option<api_models::admin::MerchantConnectorWebhookDetails>,
pub metadata: Option<Box<ConfigMetadata>>,
+ pub connector_wallets_details: Option<Box<ConnectorWalletDetailsConfig>>,
pub additional_merchant_data: Option<Box<ConfigMerchantAdditionalDetails>>,
pub credit: Option<Vec<CardProvider>>,
pub debit: Option<Vec<CardProvider>>,
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index ba6d3cb2b43..c903c189b5b 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -1215,6 +1215,8 @@ merchant_secret="Source verification key"
payment_method_type = "google_pay"
[[cybersource.wallet]]
payment_method_type = "paze"
+[[cybersource.wallet]]
+ payment_method_type = "samsung_pay"
[cybersource.connector_auth.SignatureKey]
api_key="Key"
key1="Merchant ID"
@@ -1296,6 +1298,33 @@ placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[cybersource.connector_wallets_details.samsung_pay]]
+name="service_id"
+label="Samsung Pay Service Id"
+placeholder="Enter Samsung Pay Service Id"
+required=true
+type="Text"
+[[cybersource.connector_wallets_details.samsung_pay]]
+name="merchant_display_name"
+label="Display Name"
+placeholder="Enter Display Name"
+required=true
+type="Text"
+[[cybersource.connector_wallets_details.samsung_pay]]
+name="merchant_business_country"
+label="Merchant Business Country"
+placeholder="Enter Merchant Business Country"
+required=true
+type="Select"
+options=[]
+[[cybersource.connector_wallets_details.samsung_pay]]
+name="allowed_brands"
+label="Allowed Brands"
+placeholder="Enter Allowed Brands"
+required=true
+type="MultiSelect"
+options=["visa","masterCard","amex","discover"]
+
[cybersource.metadata.acquirer_bin]
name="acquirer_bin"
label="Acquirer Bin"
|
chore
|
Add samsung pay payment method support for cybersource (#6424)
|
774a0322aa4b36d87b122e47cd893383e262de12
|
2024-02-13 20:04:45
|
Pritish Budhiraja
|
feat(users): add some checks for prod-intent send to biz email (#3631)
| false
|
diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs
index 82f95564768..7318f9973f1 100644
--- a/crates/router/src/core/user/dashboard_metadata.rs
+++ b/crates/router/src/core/user/dashboard_metadata.rs
@@ -4,10 +4,10 @@ use diesel_models::{
};
use error_stack::ResultExt;
#[cfg(feature = "email")]
+use masking::ExposeInterface;
+#[cfg(feature = "email")]
use router_env::logger;
-#[cfg(feature = "email")]
-use crate::services::email::types as email_types;
use crate::{
core::errors::{UserErrors, UserResponse, UserResult},
routes::AppState,
@@ -15,6 +15,8 @@ use crate::{
types::domain::{user::dashboard_metadata as types, MerchantKeyStore},
utils::user::dashboard_metadata as utils,
};
+#[cfg(feature = "email")]
+use crate::{services::email::types as email_types, types::domain};
pub async fn set_metadata(
state: AppState,
@@ -446,8 +448,8 @@ async fn insert_metadata(
metadata = utils::update_user_scoped_metadata(
state,
user.user_id.clone(),
- user.merchant_id,
- user.org_id,
+ user.merchant_id.clone(),
+ user.org_id.clone(),
metadata_key,
data.clone(),
)
@@ -457,7 +459,13 @@ async fn insert_metadata(
#[cfg(feature = "email")]
{
- if utils::is_prod_email_required(&data) {
+ let user_data = user.get_user(state).await?;
+ let user_email = domain::UserEmail::from_pii_email(user_data.email.clone())
+ .change_context(UserErrors::InternalServerError)?
+ .get_secret()
+ .expose();
+
+ if utils::is_prod_email_required(&data, user_email) {
let email_contents = email_types::BizEmailProd::new(state, data)?;
let send_email_result = state
.email_client
diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rs
index ac3d918a34f..58841580244 100644
--- a/crates/router/src/utils/user/dashboard_metadata.rs
+++ b/crates/router/src/utils/user/dashboard_metadata.rs
@@ -279,9 +279,15 @@ pub fn parse_string_to_enums(query: String) -> UserResult<GetMultipleMetaDataPay
})
}
-pub fn is_prod_email_required(data: &ProdIntent) -> bool {
- !(data
- .poc_email
+fn not_contains_string(value: &Option<String>, value_to_be_checked: &str) -> bool {
+ value
.as_ref()
- .map_or(true, |mail| mail.contains("juspay")))
+ .map_or(false, |mail| !mail.contains(value_to_be_checked))
+}
+
+pub fn is_prod_email_required(data: &ProdIntent, user_email: String) -> bool {
+ not_contains_string(&data.poc_email, "juspay")
+ && not_contains_string(&data.business_website, "juspay")
+ && not_contains_string(&data.business_website, "hyperswitch")
+ && not_contains_string(&Some(user_email), "juspay")
}
|
feat
|
add some checks for prod-intent send to biz email (#3631)
|
fa44c1f6023110b833ee03f2011255c89d46f1bb
|
2023-04-17 23:58:18
|
Arjun Karthik
|
fix(stripe): remove cancel reason validation for stripe (#876)
| false
|
diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs
index 9b070bbe66b..be3f92d18b0 100644
--- a/crates/router/src/connector/stripe.rs
+++ b/crates/router/src/connector/stripe.rs
@@ -555,9 +555,7 @@ impl
req: &types::PaymentsCancelRouterData,
) -> CustomResult<Option<String>, errors::ConnectorError> {
let stripe_req = utils::Encode::<stripe::CancelRequest>::convert_and_url_encode(req)
- .change_context(errors::ConnectorError::RequestEncodingFailedWithReason(
- "Invalid cancellation reason".to_string(),
- ))?;
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Some(stripe_req))
}
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 1440fe6a1d1..d5e00464fc4 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -1,12 +1,9 @@
-use std::str::FromStr;
-
use api_models::{self, enums as api_enums, payments};
use base64::Engine;
use common_utils::{fp_utils, pii::Email};
use error_stack::{IntoReport, ResultExt};
use masking::ExposeInterface;
use serde::{Deserialize, Serialize};
-use strum::EnumString;
use url::Url;
use uuid::Uuid;
@@ -1208,39 +1205,20 @@ pub struct StripeRedirectResponse {
pub source_type: Option<Secret<String>>,
}
-#[derive(Debug, Serialize, Clone, Copy)]
+#[derive(Debug, Serialize)]
pub struct CancelRequest {
- cancellation_reason: Option<CancellationReason>,
+ cancellation_reason: Option<String>,
}
impl TryFrom<&types::PaymentsCancelRouterData> for CancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
- let cancellation_reason = match &item.request.cancellation_reason {
- Some(c) => Some(
- CancellationReason::from_str(c)
- .into_report()
- .change_context(errors::ConnectorError::RequestEncodingFailed)?,
- ),
- None => None,
- };
-
Ok(Self {
- cancellation_reason,
+ cancellation_reason: item.request.cancellation_reason.clone(),
})
}
}
-#[derive(Debug, Serialize, Deserialize, Copy, Clone, EnumString)]
-#[serde(rename_all = "snake_case")]
-#[strum(serialize_all = "snake_case")]
-pub enum CancellationReason {
- Duplicate,
- Fraudulent,
- RequestedByCustomer,
- Abandoned,
-}
-
#[derive(Deserialize, Debug, Clone, Eq, PartialEq)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
|
fix
|
remove cancel reason validation for stripe (#876)
|
85c7629061ebbe5c9e0393f138af9b8876c3643d
|
2023-04-22 13:54:16
|
Prasunna Soppa
|
fix(connector): fix adyen unit test (#957)
| false
|
diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs
index f9d60e23e28..0c8ad34cf51 100644
--- a/crates/router/tests/connectors/adyen.rs
+++ b/crates/router/tests/connectors/adyen.rs
@@ -417,7 +417,8 @@ async fn should_fail_payment_for_invalid_exp_month() {
)
.await
.unwrap();
- assert_eq!(response.response.unwrap_err().message, "Refused",);
+ let errors = vec!["The provided Expiry Date is not valid.: Expiry month should be between 1 and 12 inclusive: 20","Refused"];
+ assert!(errors.contains(&response.response.unwrap_err().message.as_str()))
}
// Creates a payment with incorrect expiry year.
|
fix
|
fix adyen unit test (#957)
|
1fc941056fb8759435f41bba004a602c176eb802
|
2024-12-23 14:41:42
|
chikke srujan
|
fix(connector): [Cybersource] fix the required fields for wallet mandate payments (#6911)
| false
|
diff --git a/crates/router/src/configs/defaults/payment_connector_required_fields.rs b/crates/router/src/configs/defaults/payment_connector_required_fields.rs
index 0954ac51c7d..9e42aec4a51 100644
--- a/crates/router/src/configs/defaults/payment_connector_required_fields.rs
+++ b/crates/router/src/configs/defaults/payment_connector_required_fields.rs
@@ -8142,7 +8142,8 @@ impl Default for settings::RequiredFields {
enums::Connector::Bankofamerica,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::from(
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
[
(
"email".to_string(),
@@ -8222,14 +8223,14 @@ impl Default for settings::RequiredFields {
)
]
),
- common: HashMap::new(),
}
),
(
enums::Connector::Cybersource,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::from(
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
[
(
"billing.email".to_string(),
@@ -8309,7 +8310,6 @@ impl Default for settings::RequiredFields {
)
]
),
- common: HashMap::new(),
}
),
(
@@ -8524,7 +8524,8 @@ impl Default for settings::RequiredFields {
enums::Connector::Bankofamerica,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::from(
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
[
(
"email".to_string(),
@@ -8604,7 +8605,6 @@ impl Default for settings::RequiredFields {
)
]
),
- common: HashMap::new(),
}
),
(
@@ -8789,7 +8789,8 @@ impl Default for settings::RequiredFields {
enums::Connector::Cybersource,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::from(
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
[
(
"billing.email".to_string(),
@@ -8869,7 +8870,6 @@ impl Default for settings::RequiredFields {
)
]
),
- common: HashMap::new(),
}
),
(
|
fix
|
[Cybersource] fix the required fields for wallet mandate payments (#6911)
|
1929f56e2ab65fc8570eb492ebc4f254bd5092d0
|
2024-09-12 18:56:17
|
Sai Harsha Vardhan
|
fix(router): add payment_method check in `get_mandate_type` (#5828)
| false
|
diff --git a/crates/router/src/core/mandate/helpers.rs b/crates/router/src/core/mandate/helpers.rs
index 96f00a0d20e..52afa6e0e5e 100644
--- a/crates/router/src/core/mandate/helpers.rs
+++ b/crates/router/src/core/mandate/helpers.rs
@@ -51,6 +51,7 @@ pub fn get_mandate_type(
setup_future_usage: Option<enums::FutureUsage>,
customer_acceptance: Option<api_payments::CustomerAcceptance>,
token: Option<String>,
+ payment_method: Option<enums::PaymentMethod>,
) -> CustomResult<Option<api::MandateTransactionType>, errors::ValidationError> {
match (
mandate_data.clone(),
@@ -58,25 +59,28 @@ pub fn get_mandate_type(
setup_future_usage,
customer_acceptance.or(mandate_data.and_then(|m_data| m_data.customer_acceptance)),
token,
+ payment_method,
) {
- (Some(_), Some(_), Some(enums::FutureUsage::OffSession), Some(_), Some(_)) => {
+ (Some(_), Some(_), Some(enums::FutureUsage::OffSession), Some(_), Some(_), _) => {
Err(errors::ValidationError::InvalidValue {
message: "Expected one out of recurring_details and mandate_data but got both"
.to_string(),
}
.into())
}
- (_, _, Some(enums::FutureUsage::OffSession), Some(_), Some(_))
- | (_, _, Some(enums::FutureUsage::OffSession), Some(_), _)
- | (Some(_), _, Some(enums::FutureUsage::OffSession), _, _) => {
+ (_, _, Some(enums::FutureUsage::OffSession), Some(_), Some(_), _)
+ | (_, _, Some(enums::FutureUsage::OffSession), Some(_), _, _)
+ | (Some(_), _, Some(enums::FutureUsage::OffSession), _, _, _) => {
Ok(Some(api::MandateTransactionType::NewMandateTransaction))
}
- (_, _, Some(enums::FutureUsage::OffSession), _, Some(_))
- | (_, Some(_), _, _, _)
- | (_, _, Some(enums::FutureUsage::OffSession), _, _) => Ok(Some(
- api::MandateTransactionType::RecurringMandateTransaction,
- )),
+ (_, _, Some(enums::FutureUsage::OffSession), _, Some(_), _)
+ | (_, Some(_), _, _, _, _)
+ | (_, _, Some(enums::FutureUsage::OffSession), _, _, Some(enums::PaymentMethod::Wallet)) => {
+ Ok(Some(
+ api::MandateTransactionType::RecurringMandateTransaction,
+ ))
+ }
_ => Ok(None),
}
diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
index 0f9459b5523..00eb0a3bc3e 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -111,6 +111,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co
payment_intent.setup_future_usage,
request.customer_acceptance.clone(),
request.payment_token.clone(),
+ payment_attempt.payment_method,
)
.change_context(errors::ApiErrorResponse::MandateValidationFailed {
reason: "Expected one out of recurring_details and mandate_data but got both".into(),
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index df2f8746e11..c4abe7ff869 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -524,6 +524,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
payment_intent.setup_future_usage,
request.customer_acceptance.clone(),
request.payment_token.clone(),
+ payment_attempt.payment_method.or(request.payment_method),
)
.change_context(errors::ApiErrorResponse::MandateValidationFailed {
reason: "Expected one out of recurring_details and mandate_data but got both".into(),
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index f590f797817..88489f4a03b 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -150,6 +150,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
request.setup_future_usage,
request.customer_acceptance.clone(),
request.payment_token.clone(),
+ request.payment_method,
)
.change_context(errors::ApiErrorResponse::MandateValidationFailed {
reason: "Expected one out of recurring_details and mandate_data but got both".into(),
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 6928b8f6f78..3b243e86132 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -136,6 +136,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
payment_intent.setup_future_usage,
request.customer_acceptance.clone(),
request.payment_token.clone(),
+ payment_attempt.payment_method.or(request.payment_method),
)
.change_context(errors::ApiErrorResponse::MandateValidationFailed {
reason: "Expected one out of recurring_details and mandate_data but got both".into(),
|
fix
|
add payment_method check in `get_mandate_type` (#5828)
|
966369b6f2c205b59524c23ad3b21ebab547631f
|
2023-11-09 20:39:12
|
Abhishek Marrivagu
|
refactor(core): remove connector response table and use payment_attempt instead (#2644)
| false
|
diff --git a/crates/data_models/src/payments/payment_attempt.rs b/crates/data_models/src/payments/payment_attempt.rs
index 734de8fe4a5..cdd41ea9db2 100644
--- a/crates/data_models/src/payments/payment_attempt.rs
+++ b/crates/data_models/src/payments/payment_attempt.rs
@@ -286,6 +286,8 @@ pub enum PaymentAttemptUpdate {
connector_response_reference_id: Option<String>,
amount_capturable: Option<i64>,
updated_by: String,
+ authentication_data: Option<serde_json::Value>,
+ encoded_data: Option<String>,
},
UnresolvedResponseUpdate {
status: storage_enums::AttemptStatus,
diff --git a/crates/diesel_models/src/connector_response.rs b/crates/diesel_models/src/connector_response.rs
deleted file mode 100644
index 863ce28ee0a..00000000000
--- a/crates/diesel_models/src/connector_response.rs
+++ /dev/null
@@ -1,122 +0,0 @@
-use diesel::{AsChangeset, Identifiable, Insertable, Queryable};
-use serde::{Deserialize, Serialize};
-use time::PrimitiveDateTime;
-
-use crate::schema::connector_response;
-
-#[derive(Clone, Debug, Deserialize, Serialize, Insertable, router_derive::DebugAsDisplay)]
-#[diesel(table_name = connector_response)]
-#[serde(deny_unknown_fields)]
-pub struct ConnectorResponseNew {
- pub payment_id: String,
- pub merchant_id: String,
- pub attempt_id: String,
- #[serde(with = "common_utils::custom_serde::iso8601")]
- pub created_at: PrimitiveDateTime,
- #[serde(with = "common_utils::custom_serde::iso8601")]
- pub modified_at: PrimitiveDateTime,
- pub connector_name: Option<String>,
- pub connector_transaction_id: Option<String>,
- pub authentication_data: Option<serde_json::Value>,
- pub encoded_data: Option<String>,
- pub updated_by: String,
-}
-
-#[derive(Clone, Debug, Deserialize, Serialize, Identifiable, Queryable)]
-#[diesel(table_name = connector_response)]
-pub struct ConnectorResponse {
- pub id: i32,
- pub payment_id: String,
- pub merchant_id: String,
- pub attempt_id: String,
- #[serde(with = "common_utils::custom_serde::iso8601")]
- pub created_at: PrimitiveDateTime,
- #[serde(with = "common_utils::custom_serde::iso8601")]
- pub modified_at: PrimitiveDateTime,
- pub connector_name: Option<String>,
- pub connector_transaction_id: Option<String>,
- pub authentication_data: Option<serde_json::Value>,
- pub encoded_data: Option<String>,
- pub updated_by: String,
-}
-
-#[derive(Clone, Default, Debug, Deserialize, AsChangeset, Serialize)]
-#[diesel(table_name = connector_response)]
-pub struct ConnectorResponseUpdateInternal {
- pub connector_transaction_id: Option<String>,
- pub authentication_data: Option<serde_json::Value>,
- pub modified_at: Option<PrimitiveDateTime>,
- pub encoded_data: Option<String>,
- pub connector_name: Option<String>,
- pub updated_by: String,
-}
-
-#[derive(Clone, Debug, Serialize, Deserialize)]
-pub enum ConnectorResponseUpdate {
- ResponseUpdate {
- connector_transaction_id: Option<String>,
- authentication_data: Option<serde_json::Value>,
- encoded_data: Option<String>,
- connector_name: Option<String>,
- updated_by: String,
- },
- ErrorUpdate {
- connector_name: Option<String>,
- updated_by: String,
- },
-}
-
-impl ConnectorResponseUpdate {
- pub fn apply_changeset(self, source: ConnectorResponse) -> ConnectorResponse {
- let connector_response_update: ConnectorResponseUpdateInternal = self.into();
- ConnectorResponse {
- modified_at: connector_response_update
- .modified_at
- .unwrap_or_else(common_utils::date_time::now),
- connector_name: connector_response_update
- .connector_name
- .or(source.connector_name),
- connector_transaction_id: source
- .connector_transaction_id
- .or(connector_response_update.connector_transaction_id),
- authentication_data: connector_response_update
- .authentication_data
- .or(source.authentication_data),
- encoded_data: connector_response_update
- .encoded_data
- .or(source.encoded_data),
- updated_by: connector_response_update.updated_by,
- ..source
- }
- }
-}
-
-impl From<ConnectorResponseUpdate> for ConnectorResponseUpdateInternal {
- fn from(connector_response_update: ConnectorResponseUpdate) -> Self {
- match connector_response_update {
- ConnectorResponseUpdate::ResponseUpdate {
- connector_transaction_id,
- authentication_data,
- encoded_data,
- connector_name,
- updated_by,
- } => Self {
- connector_transaction_id,
- authentication_data,
- encoded_data,
- modified_at: Some(common_utils::date_time::now()),
- connector_name,
- updated_by,
- },
- ConnectorResponseUpdate::ErrorUpdate {
- connector_name,
- updated_by,
- } => Self {
- connector_name,
- modified_at: Some(common_utils::date_time::now()),
- updated_by,
- ..Self::default()
- },
- }
- }
-}
diff --git a/crates/diesel_models/src/kv.rs b/crates/diesel_models/src/kv.rs
index 81fa7a88ee3..f56ef830418 100644
--- a/crates/diesel_models/src/kv.rs
+++ b/crates/diesel_models/src/kv.rs
@@ -3,7 +3,6 @@ use serde::{Deserialize, Serialize};
use crate::{
address::{Address, AddressNew, AddressUpdateInternal},
- connector_response::{ConnectorResponse, ConnectorResponseNew, ConnectorResponseUpdate},
errors,
payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate},
payment_intent::{PaymentIntentNew, PaymentIntentUpdate},
@@ -51,7 +50,6 @@ pub enum Insertable {
PaymentIntent(PaymentIntentNew),
PaymentAttempt(PaymentAttemptNew),
Refund(RefundNew),
- ConnectorResponse(ConnectorResponseNew),
Address(Box<AddressNew>),
ReverseLookUp(ReverseLookupNew),
}
@@ -62,16 +60,9 @@ pub enum Updateable {
PaymentIntentUpdate(PaymentIntentUpdateMems),
PaymentAttemptUpdate(PaymentAttemptUpdateMems),
RefundUpdate(RefundUpdateMems),
- ConnectorResponseUpdate(ConnectorResponseUpdateMems),
AddressUpdate(Box<AddressUpdateMems>),
}
-#[derive(Debug, Serialize, Deserialize)]
-pub struct ConnectorResponseUpdateMems {
- pub orig: ConnectorResponse,
- pub update_data: ConnectorResponseUpdate,
-}
-
#[derive(Debug, Serialize, Deserialize)]
pub struct AddressUpdateMems {
pub orig: Address,
diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs
index 08d74fb8fd3..46a6965b3a7 100644
--- a/crates/diesel_models/src/lib.rs
+++ b/crates/diesel_models/src/lib.rs
@@ -4,7 +4,7 @@ pub mod business_profile;
pub mod capture;
pub mod cards_info;
pub mod configs;
-pub mod connector_response;
+
pub mod customers;
pub mod dispute;
pub mod encryption;
@@ -44,10 +44,10 @@ use diesel_impl::{DieselArray, OptionalDieselArray};
pub type StorageResult<T> = error_stack::Result<T, errors::DatabaseError>;
pub type PgPooledConn = async_bb8_diesel::Connection<diesel::PgConnection>;
pub use self::{
- address::*, api_keys::*, cards_info::*, configs::*, connector_response::*, customers::*,
- dispute::*, ephemeral_key::*, events::*, file::*, locker_mock_up::*, mandate::*,
- merchant_account::*, merchant_connector_account::*, payment_attempt::*, payment_intent::*,
- payment_method::*, process_tracker::*, refund::*, reverse_lookup::*,
+ address::*, api_keys::*, cards_info::*, configs::*, customers::*, dispute::*, ephemeral_key::*,
+ events::*, file::*, locker_mock_up::*, mandate::*, merchant_account::*,
+ merchant_connector_account::*, payment_attempt::*, payment_intent::*, payment_method::*,
+ process_tracker::*, refund::*, reverse_lookup::*,
};
/// The types and implementations provided by this module are required for the schema generated by
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index 05808610611..ce388fea10e 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -203,6 +203,8 @@ pub enum PaymentAttemptUpdate {
connector_response_reference_id: Option<String>,
amount_capturable: Option<i64>,
updated_by: String,
+ authentication_data: Option<serde_json::Value>,
+ encoded_data: Option<String>,
},
UnresolvedResponseUpdate {
status: storage_enums::AttemptStatus,
@@ -478,6 +480,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
connector_response_reference_id,
amount_capturable,
updated_by,
+ authentication_data,
+ encoded_data,
} => Self {
status: Some(status),
connector,
@@ -494,6 +498,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
connector_response_reference_id,
amount_capturable,
updated_by,
+ authentication_data,
+ encoded_data,
..Default::default()
},
PaymentAttemptUpdate::ErrorUpdate {
diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs
index ac3eeba4435..f315327702a 100644
--- a/crates/diesel_models/src/query.rs
+++ b/crates/diesel_models/src/query.rs
@@ -4,7 +4,7 @@ pub mod business_profile;
mod capture;
pub mod cards_info;
pub mod configs;
-pub mod connector_response;
+
pub mod customers;
pub mod dispute;
pub mod events;
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 9933bf90a59..6c9cea035b3 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -157,31 +157,6 @@ diesel::table! {
}
}
-diesel::table! {
- use diesel::sql_types::*;
- use crate::enums::diesel_exports::*;
-
- connector_response (id) {
- id -> Int4,
- #[max_length = 64]
- payment_id -> Varchar,
- #[max_length = 64]
- merchant_id -> Varchar,
- #[max_length = 64]
- attempt_id -> Varchar,
- created_at -> Timestamp,
- modified_at -> Timestamp,
- #[max_length = 64]
- connector_name -> Nullable<Varchar>,
- #[max_length = 128]
- connector_transaction_id -> Nullable<Varchar>,
- authentication_data -> Nullable<Json>,
- encoded_data -> Nullable<Text>,
- #[max_length = 32]
- updated_by -> Varchar,
- }
-}
-
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
@@ -932,7 +907,6 @@ diesel::allow_tables_to_appear_in_same_query!(
captures,
cards_info,
configs,
- connector_response,
customers,
dispute,
events,
diff --git a/crates/drainer/src/lib.rs b/crates/drainer/src/lib.rs
index 19abe9ba3aa..7ccfd600d66 100644
--- a/crates/drainer/src/lib.rs
+++ b/crates/drainer/src/lib.rs
@@ -206,7 +206,6 @@ async fn drainer(
let payment_attempt = "payment_attempt";
let refund = "refund";
let reverse_lookup = "reverse_lookup";
- let connector_response = "connector_response";
let address = "address";
match db_op {
// TODO: Handle errors
@@ -230,13 +229,6 @@ async fn drainer(
kv::Insertable::Refund(a) => {
macro_util::handle_resp!(a.insert(&conn).await, insert_op, refund)
}
- kv::Insertable::ConnectorResponse(a) => {
- macro_util::handle_resp!(
- a.insert(&conn).await,
- insert_op,
- connector_response
- )
- }
kv::Insertable::Address(addr) => {
macro_util::handle_resp!(addr.insert(&conn).await, insert_op, address)
}
@@ -283,11 +275,6 @@ async fn drainer(
refund
)
}
- kv::Updateable::ConnectorResponseUpdate(a) => macro_util::handle_resp!(
- a.orig.update(&conn, a.update_data).await,
- update_op,
- connector_response
- ),
kv::Updateable::AddressUpdate(a) => macro_util::handle_resp!(
a.orig.update(&conn, a.update_data).await,
update_op,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 98ab158e793..a114b20380b 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1578,7 +1578,6 @@ where
pub payment_intent: storage::PaymentIntent,
pub payment_attempt: storage::PaymentAttempt,
pub multiple_capture_data: Option<types::MultipleCaptureData>,
- pub connector_response: storage::ConnectorResponse,
pub amount: api::Amount,
pub mandate_id: Option<api_models::payments::MandateIds>,
pub mandate_connector: Option<MandateConnectorDetails>,
@@ -1671,10 +1670,7 @@ pub fn should_call_connector<Op: Debug, F: Clone>(
!matches!(
payment_data.payment_intent.status,
storage_enums::IntentStatus::Failed | storage_enums::IntentStatus::Succeeded
- ) && payment_data
- .connector_response
- .authentication_data
- .is_none()
+ ) && payment_data.payment_attempt.authentication_data.is_none()
}
"PaymentStatus" => {
matches!(
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index fd9fd7361da..4ee2fd4b94d 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -2998,60 +2998,6 @@ impl AttemptType {
}
}
}
-
- #[instrument(skip_all)]
- pub async fn get_or_insert_connector_response(
- &self,
- payment_attempt: &PaymentAttempt,
- db: &dyn StorageInterface,
- storage_scheme: storage::enums::MerchantStorageScheme,
- ) -> RouterResult<storage::ConnectorResponse> {
- match self {
- Self::New => db
- .insert_connector_response(
- payments::PaymentCreate::make_connector_response(payment_attempt),
- storage_scheme,
- )
- .await
- .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment {
- payment_id: payment_attempt.payment_id.clone(),
- }),
- Self::SameOld => db
- .find_connector_response_by_payment_id_merchant_id_attempt_id(
- &payment_attempt.payment_id,
- &payment_attempt.merchant_id,
- &payment_attempt.attempt_id,
- storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound),
- }
- }
-
- #[instrument(skip_all)]
- pub async fn get_connector_response(
- &self,
- db: &dyn StorageInterface,
- payment_id: &str,
- merchant_id: &str,
- attempt_id: &str,
- storage_scheme: storage_enums::MerchantStorageScheme,
- ) -> RouterResult<storage::ConnectorResponse> {
- match self {
- Self::New => Err(errors::ApiErrorResponse::InternalServerError)
- .into_report()
- .attach_printable("Precondition failed, the attempt type should not be `New`"),
- Self::SameOld => db
- .find_connector_response_by_payment_id_merchant_id_attempt_id(
- payment_id,
- merchant_id,
- attempt_id,
- storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound),
- }
- }
}
#[inline(always)]
diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs
index 4cd1bae04de..d5d0d2d0176 100644
--- a/crates/router/src/core/payments/operations/payment_approve.rs
+++ b/crates/router/src/core/payments/operations/payment_approve.rs
@@ -161,16 +161,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
)
.await?;
- let connector_response = db
- .find_connector_response_by_payment_id_merchant_id_attempt_id(
- &payment_attempt.payment_id,
- &payment_attempt.merchant_id,
- &payment_attempt.attempt_id,
- storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
-
let redirect_response = request
.feature_metadata
.as_ref()
@@ -224,7 +214,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
payment_intent,
payment_attempt,
currency,
- connector_response,
amount,
email: request.email.clone(),
mandate_id: None,
diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs
index 43fdc440e64..f734afef782 100644
--- a/crates/router/src/core/payments/operations/payment_cancel.rs
+++ b/crates/router/src/core/payments/operations/payment_cancel.rs
@@ -106,15 +106,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
)
.await?;
- let connector_response = db
- .find_connector_response_by_payment_id_merchant_id_attempt_id(
- &payment_attempt.payment_id,
- &payment_attempt.merchant_id,
- &payment_attempt.attempt_id,
- storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let currency = payment_attempt.currency.get_required_value("currency")?;
let amount = payment_attempt.amount.into();
@@ -161,7 +152,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
refunds: vec![],
disputes: vec![],
attempts: None,
- connector_response,
+
sessions_token: vec![],
card_cvc: None,
creds_identifier,
diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs
index 1cfcbce5532..6e794b1ba61 100644
--- a/crates/router/src/core/payments/operations/payment_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_capture.rs
@@ -3,7 +3,6 @@ use std::marker::PhantomData;
use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
use common_utils::ext_traits::AsyncExt;
-use diesel_models::connector_response::ConnectorResponse;
use error_stack::ResultExt;
use router_env::{instrument, tracing};
@@ -20,7 +19,7 @@ use crate::{
types::{
api::{self, PaymentIdTypeExt},
domain,
- storage::{self, enums, payment_attempt::PaymentAttemptExt, ConnectorResponseExt},
+ storage::{self, enums, payment_attempt::PaymentAttemptExt},
},
utils::OptionExt,
};
@@ -89,9 +88,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
helpers::validate_capture_method(capture_method)?;
- let (multiple_capture_data, connector_response) = if capture_method
- == enums::CaptureMethod::ManualMultiple
- {
+ let multiple_capture_data = if capture_method == enums::CaptureMethod::ManualMultiple {
let amount_to_capture = request
.amount_to_capture
.get_required_value("amount_to_capture")?;
@@ -121,37 +118,13 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.to_not_found_response(errors::ApiErrorResponse::DuplicatePayment {
payment_id: payment_id.clone(),
})?;
- let new_connector_response = db
- .insert_connector_response(
- ConnectorResponse::make_new_connector_response(
- capture.payment_id.clone(),
- capture.merchant_id.clone(),
- capture.capture_id.clone(),
- Some(capture.connector.clone()),
- storage_scheme.to_string(),
- ),
- storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::DuplicatePayment { payment_id })?;
- (
- Some(MultipleCaptureData::new_for_create(
- previous_captures,
- capture,
- )),
- new_connector_response,
- )
+
+ Some(MultipleCaptureData::new_for_create(
+ previous_captures,
+ capture,
+ ))
} else {
- let connector_response = db
- .find_connector_response_by_payment_id_merchant_id_attempt_id(
- &payment_attempt.payment_id,
- &payment_attempt.merchant_id,
- &payment_attempt.attempt_id,
- storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
- (None, connector_response)
+ None
};
currency = payment_attempt.currency.get_required_value("currency")?;
@@ -223,7 +196,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
refunds: vec![],
disputes: vec![],
attempts: None,
- connector_response,
sessions_token: vec![],
card_cvc: None,
creds_identifier,
diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
index 4e87b386943..038d34ea290 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -170,16 +170,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
)
.await?;
- let connector_response = db
- .find_connector_response_by_payment_id_merchant_id_attempt_id(
- &payment_attempt.payment_id,
- &payment_attempt.merchant_id,
- &payment_attempt.attempt_id,
- storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
-
let redirect_response = request
.feature_metadata
.as_ref()
@@ -219,7 +209,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
payment_intent,
payment_attempt,
currency,
- connector_response,
amount,
email: request.email.clone(),
mandate_id: None,
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 5de281a5e63..21f7db3d0b4 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -157,77 +157,49 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
})
.map(|x| x.transpose());
- let (mut payment_attempt, shipping_address, billing_address, connector_response) =
- match payment_intent.status {
- api_models::enums::IntentStatus::RequiresCustomerAction
- | api_models::enums::IntentStatus::RequiresMerchantAction
- | api_models::enums::IntentStatus::RequiresPaymentMethod
- | api_models::enums::IntentStatus::RequiresConfirmation => {
- let attempt_type = helpers::AttemptType::SameOld;
-
- let attempt_id = payment_intent.active_attempt.get_id();
- let connector_response_fut = attempt_type.get_connector_response(
+ let (mut payment_attempt, shipping_address, billing_address) = match payment_intent.status {
+ api_models::enums::IntentStatus::RequiresCustomerAction
+ | api_models::enums::IntentStatus::RequiresMerchantAction
+ | api_models::enums::IntentStatus::RequiresPaymentMethod
+ | api_models::enums::IntentStatus::RequiresConfirmation => {
+ let (payment_attempt, shipping_address, billing_address, _) = futures::try_join!(
+ payment_attempt_fut,
+ shipping_address_fut,
+ billing_address_fut,
+ config_update_fut
+ )?;
+
+ (payment_attempt, shipping_address, billing_address)
+ }
+ _ => {
+ let (mut payment_attempt, shipping_address, billing_address, _) = futures::try_join!(
+ payment_attempt_fut,
+ shipping_address_fut,
+ billing_address_fut,
+ config_update_fut
+ )?;
+
+ let attempt_type = helpers::get_attempt_type(
+ &payment_intent,
+ &payment_attempt,
+ request,
+ "confirm",
+ )?;
+
+ (payment_intent, payment_attempt) = attempt_type
+ .modify_payment_intent_and_payment_attempt(
+ // 3
+ request,
+ payment_intent,
+ payment_attempt,
db,
- &payment_intent.payment_id,
- &payment_intent.merchant_id,
- attempt_id.as_str(),
storage_scheme,
- );
-
- let (payment_attempt, shipping_address, billing_address, connector_response, _) =
- futures::try_join!(
- payment_attempt_fut,
- shipping_address_fut,
- billing_address_fut,
- connector_response_fut,
- config_update_fut
- )?;
-
- (
- payment_attempt,
- shipping_address,
- billing_address,
- connector_response,
)
- }
- _ => {
- let (mut payment_attempt, shipping_address, billing_address, _) = futures::try_join!(
- payment_attempt_fut,
- shipping_address_fut,
- billing_address_fut,
- config_update_fut
- )?;
-
- let attempt_type = helpers::get_attempt_type(
- &payment_intent,
- &payment_attempt,
- request,
- "confirm",
- )?;
-
- (payment_intent, payment_attempt) = attempt_type
- .modify_payment_intent_and_payment_attempt(
- // 3
- request,
- payment_intent,
- payment_attempt,
- db,
- storage_scheme,
- )
- .await?;
-
- let connector_response = attempt_type
- .get_or_insert_connector_response(&payment_attempt, db, storage_scheme)
- .await?;
+ .await?;
- (
- payment_attempt,
- shipping_address,
- billing_address,
- connector_response,
- )
- }
- };
+ (payment_attempt, shipping_address, billing_address)
+ }
+ };
payment_intent.order_details = request
.get_order_details_as_value()
@@ -354,7 +326,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
payment_intent,
payment_attempt,
currency,
- connector_response,
amount,
email: request.email.clone(),
mandate_id: None,
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index adb3c415532..97bb8437130 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -62,7 +62,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
let ephemeral_key = Self::get_ephemeral_key(request, state, merchant_account).await;
let merchant_id = &merchant_account.merchant_id;
let storage_scheme = merchant_account.storage_scheme;
- let (payment_intent, payment_attempt, connector_response);
+ let (payment_intent, payment_attempt);
let money @ (amount, currency) = payments_create_request_validation(request)?;
@@ -196,16 +196,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
payment_id: payment_id.clone(),
})?;
- connector_response = db
- .insert_connector_response(
- Self::make_connector_response(&payment_attempt),
- storage_scheme,
- )
- .await
- .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment {
- payment_id: payment_id.clone(),
- })?;
-
let mandate_id = request
.mandate_id
.as_ref()
@@ -300,7 +290,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
disputes: vec![],
attempts: None,
force_sync: None,
- connector_response,
sessions_token: vec![],
card_cvc: request.card_cvc.clone(),
creds_identifier,
@@ -727,24 +716,6 @@ impl PaymentCreate {
})
}
- #[instrument(skip_all)]
- pub fn make_connector_response(
- payment_attempt: &PaymentAttempt,
- ) -> storage::ConnectorResponseNew {
- storage::ConnectorResponseNew {
- payment_id: payment_attempt.payment_id.clone(),
- merchant_id: payment_attempt.merchant_id.clone(),
- attempt_id: payment_attempt.attempt_id.clone(),
- created_at: payment_attempt.created_at,
- modified_at: payment_attempt.modified_at,
- connector_name: payment_attempt.connector.clone(),
- connector_transaction_id: None,
- authentication_data: None,
- encoded_data: None,
- updated_by: payment_attempt.updated_by.clone(),
- }
- }
-
#[instrument(skip_all)]
pub async fn get_ephemeral_key(
request: &api::PaymentsRequest,
diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs
index 33f6c23c836..7e4fe0951b0 100644
--- a/crates/router/src/core/payments/operations/payment_method_validate.rs
+++ b/crates/router/src/core/payments/operations/payment_method_validate.rs
@@ -7,7 +7,7 @@ use error_stack::ResultExt;
use router_derive::PaymentOperation;
use router_env::{instrument, tracing};
-use super::{BoxedOperation, Domain, GetTracker, PaymentCreate, UpdateTracker, ValidateRequest};
+use super::{BoxedOperation, Domain, GetTracker, UpdateTracker, ValidateRequest};
use crate::{
consts,
core::{
@@ -89,7 +89,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
let merchant_id = &merchant_account.merchant_id;
let storage_scheme = merchant_account.storage_scheme;
- let (payment_intent, payment_attempt, connector_response);
+ let (payment_intent, payment_attempt);
let payment_id = payment_id
.get_payment_intent_id()
@@ -135,19 +135,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
}
}?;
- connector_response = match db
- .insert_connector_response(
- PaymentCreate::make_connector_response(&payment_attempt),
- storage_scheme,
- )
- .await
- {
- Ok(connector_resp) => Ok(connector_resp),
- Err(err) => {
- Err(err.change_context(errors::ApiErrorResponse::VerificationFailed { data: None }))
- }
- }?;
-
let creds_identifier = request
.merchant_connector_details
.as_ref()
@@ -180,7 +167,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
mandate_connector: None,
setup_mandate: request.mandate_data.clone().map(Into::into),
token: request.payment_token.clone(),
- connector_response,
payment_method_data: request.payment_method_data.clone(),
confirm: Some(true),
address: types::PaymentAddress::default(),
diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs
index 415ab3eccfe..a6c2561aaee 100644
--- a/crates/router/src/core/payments/operations/payment_reject.rs
+++ b/crates/router/src/core/payments/operations/payment_reject.rs
@@ -104,15 +104,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
)
.await?;
- let connector_response = db
- .find_connector_response_by_payment_id_merchant_id_attempt_id(
- &payment_attempt.payment_id,
- &payment_attempt.merchant_id,
- &payment_attempt.attempt_id,
- storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let currency = payment_attempt.currency.get_required_value("currency")?;
let amount = payment_attempt.amount.into();
@@ -147,7 +138,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
refunds: vec![],
disputes: vec![],
attempts: None,
- connector_response,
+
sessions_token: vec![],
card_cvc: None,
creds_identifier: None,
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 60d3bc165a9..77c34494966 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -296,10 +296,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
router_data: types::RouterData<F, T, types::PaymentsResponseData>,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentData<F>> {
- let (capture_update, mut payment_attempt_update, connector_response_update) = match router_data
- .response
- .clone()
- {
+ let (capture_update, mut payment_attempt_update) = match router_data.response.clone() {
Err(err) => {
let (capture_update, attempt_update) = match payment_data.multiple_capture_data {
Some(multiple_capture_data) => {
@@ -356,14 +353,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
)
}
};
- (
- capture_update,
- attempt_update,
- Some(storage::ConnectorResponseUpdate::ErrorUpdate {
- connector_name: Some(router_data.connector.clone()),
- updated_by: storage_scheme.to_string(),
- }),
- )
+ (capture_update, attempt_update)
}
Ok(payments_response) => match payments_response {
types::PaymentsResponseData::PreProcessingResponse {
@@ -394,7 +384,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
updated_by: storage_scheme.to_string(),
};
- (None, Some(payment_attempt_update), None)
+ (None, Some(payment_attempt_update))
}
types::PaymentsResponseData::TransactionResponse {
resource_id,
@@ -409,8 +399,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
| types::ResponseId::EncodedData(id) => Some(id),
};
- let encoded_data = payment_data.connector_response.encoded_data.clone();
- let connector_name = router_data.connector.clone();
+ let encoded_data = payment_data.payment_attempt.encoded_data.clone();
let authentication_data = redirection_data
.map(|data| utils::Encode::<RedirectForm>::encode_to_value(&data))
@@ -478,23 +467,13 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
None
},
updated_by: storage_scheme.to_string(),
+ authentication_data,
+ encoded_data,
}),
),
};
- let connector_response_update = storage::ConnectorResponseUpdate::ResponseUpdate {
- connector_transaction_id,
- authentication_data,
- encoded_data,
- connector_name: Some(connector_name),
- updated_by: storage_scheme.to_string(),
- };
-
- (
- capture_updates,
- payment_attempt_update,
- Some(connector_response_update),
- )
+ (capture_updates, payment_attempt_update)
}
types::PaymentsResponseData::TransactionUnresolvedResponse {
resource_id,
@@ -519,14 +498,13 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
connector_response_reference_id,
updated_by: storage_scheme.to_string(),
}),
- None,
)
}
- types::PaymentsResponseData::SessionResponse { .. } => (None, None, None),
- types::PaymentsResponseData::SessionTokenResponse { .. } => (None, None, None),
- types::PaymentsResponseData::TokenizationResponse { .. } => (None, None, None),
- types::PaymentsResponseData::ConnectorCustomerResponse { .. } => (None, None, None),
- types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => (None, None, None),
+ types::PaymentsResponseData::SessionResponse { .. } => (None, None),
+ types::PaymentsResponseData::SessionTokenResponse { .. } => (None, None),
+ types::PaymentsResponseData::TokenizationResponse { .. } => (None, None),
+ types::PaymentsResponseData::ConnectorCustomerResponse { .. } => (None, None),
+ types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => (None, None),
types::PaymentsResponseData::MultipleCaptureResponse {
capture_sync_response_list,
} => match payment_data.multiple_capture_data {
@@ -535,13 +513,9 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
&multiple_capture_data,
capture_sync_response_list,
)?;
- (
- Some((multiple_capture_data, capture_update_list)),
- None,
- None,
- )
+ (Some((multiple_capture_data, capture_update_list)), None)
}
- None => (None, None, None),
+ None => (None, None),
},
},
};
@@ -571,40 +545,18 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
// Stage 1
let payment_attempt = payment_data.payment_attempt.clone();
- let connector_response = payment_data.connector_response.clone();
-
- let payment_attempt_fut = Box::pin(async move {
- Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(match payment_attempt_update {
- Some(payment_attempt_update) => db
- .update_payment_attempt_with_attempt_id(
- payment_attempt,
- payment_attempt_update,
- storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?,
- None => payment_attempt,
- })
- });
-
- let connector_response_fut = Box::pin(async move {
- Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(match connector_response_update {
- Some(connector_response_update) => db
- .update_connector_response(
- connector_response,
- connector_response_update,
- storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?,
- None => connector_response,
- })
- });
-
- let (payment_attempt, connector_response) =
- futures::try_join!(payment_attempt_fut, connector_response_fut)?;
- payment_data.payment_attempt = payment_attempt;
- payment_data.connector_response = connector_response;
+
+ payment_data.payment_attempt = match payment_attempt_update {
+ Some(payment_attempt_update) => db
+ .update_payment_attempt_with_attempt_id(
+ payment_attempt,
+ payment_attempt_update,
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?,
+ None => payment_attempt,
+ };
let amount_captured = get_total_amount_captured(
router_data.request,
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 354c62648bb..52677ab3cc8 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -126,20 +126,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
payment_intent.shipping_address_id = shipping_address.clone().map(|x| x.address_id);
payment_intent.billing_address_id = billing_address.clone().map(|x| x.address_id);
- let connector_response = db
- .find_connector_response_by_payment_id_merchant_id_attempt_id(
- &payment_intent.payment_id,
- &payment_intent.merchant_id,
- &payment_attempt.attempt_id,
- storage_scheme,
- )
- .await
- .map_err(|error| {
- error
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Database error when finding connector response")
- })?;
-
let customer_details = payments::CustomerDetails {
customer_id: payment_intent.customer_id.clone(),
name: None,
@@ -190,7 +176,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
disputes: vec![],
attempts: None,
sessions_token: vec![],
- connector_response,
card_cvc: None,
creds_identifier,
pm_token: None,
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index e9fa301bf07..5578f6b3dc1 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -126,20 +126,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
..CustomerDetails::default()
};
- let connector_response = db
- .find_connector_response_by_payment_id_merchant_id_attempt_id(
- &payment_intent.payment_id,
- &payment_intent.merchant_id,
- &payment_attempt.attempt_id,
- storage_scheme,
- )
- .await
- .map_err(|error| {
- error
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Database error when finding connector response")
- })?;
-
Ok((
Box::new(self),
PaymentData {
@@ -150,7 +136,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
email: None,
mandate_id: None,
mandate_connector: None,
- connector_response,
setup_mandate: None,
token: payment_attempt.payment_token.clone(),
address: PaymentAddress {
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index 96aac6c9d79..83e7131b267 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -226,7 +226,7 @@ async fn get_tracker_for_sync<
PaymentData<F>,
Option<CustomerDetails>,
)> {
- let (payment_intent, payment_attempt, currency, amount);
+ let (payment_intent, mut payment_attempt, currency, amount);
(payment_intent, payment_attempt) = get_payment_intent_payment_attempt(
db,
@@ -250,18 +250,7 @@ async fn get_tracker_for_sync<
let payment_id_str = payment_attempt.payment_id.clone();
- let mut connector_response = db
- .find_connector_response_by_payment_id_merchant_id_attempt_id(
- &payment_intent.payment_id,
- &payment_intent.merchant_id,
- &payment_attempt.attempt_id,
- storage_scheme,
- )
- .await
- .change_context(errors::ApiErrorResponse::PaymentNotFound)
- .attach_printable("Database error when finding connector response")?;
-
- connector_response.encoded_data = request.param.clone();
+ payment_attempt.encoded_data = request.param.clone();
currency = payment_attempt.currency.get_required_value("currency")?;
amount = payment_attempt.amount.into();
@@ -349,7 +338,7 @@ async fn get_tracker_for_sync<
format!("Error while retrieving frm_response, merchant_id: {}, payment_id: {payment_id_str}", &merchant_account.merchant_id)
});
- let contains_encoded_data = connector_response.encoded_data.is_some();
+ let contains_encoded_data = payment_attempt.encoded_data.is_some();
let creds_identifier = request
.merchant_connector_details
@@ -373,7 +362,6 @@ async fn get_tracker_for_sync<
PaymentData {
flow: PhantomData,
payment_intent,
- connector_response,
currency,
amount,
email: None,
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 622d0975439..0a49c830b73 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -219,20 +219,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
)?;
}
- let connector_response = db
- .find_connector_response_by_payment_id_merchant_id_attempt_id(
- &payment_intent.payment_id,
- &payment_intent.merchant_id,
- &payment_attempt.attempt_id,
- storage_scheme,
- )
- .await
- .map_err(|error| {
- error
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Database error when finding connector response")
- })?;
-
let mandate_id = request
.mandate_id
.as_ref()
@@ -341,7 +327,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
refunds: vec![],
disputes: vec![],
attempts: None,
- connector_response,
sessions_token: vec![],
card_cvc: request.card_cvc.clone(),
creds_identifier,
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index c6252982638..6c6b4ae9339 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -460,14 +460,8 @@ where
let output = Ok(match payment_request {
Some(_request) => {
- if payments::is_start_pay(&operation)
- && payment_data
- .connector_response
- .authentication_data
- .is_some()
- {
- let redirection_data = payment_data
- .connector_response
+ if payments::is_start_pay(&operation) && payment_attempt.authentication_data.is_some() {
+ let redirection_data = payment_attempt
.authentication_data
.get_required_value("redirection_data")?;
@@ -523,16 +517,15 @@ where
display_to_timestamp: wait_screen_data.display_to_timestamp,
}
}))
- .or(payment_data
- .connector_response
- .authentication_data
- .map(|_| api_models::payments::NextActionData::RedirectToUrl {
+ .or(payment_attempt.authentication_data.as_ref().map(|_| {
+ api_models::payments::NextActionData::RedirectToUrl {
redirect_to_url: helpers::create_startpay_url(
server,
&payment_attempt,
&payment_intent,
),
- }));
+ }
+ }));
};
// next action check for third party sdk session (for ex: Apple pay through trustpay has third party sdk session response)
@@ -1056,7 +1049,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData
}
None => types::ResponseId::NoResponseId,
},
- encoded_data: payment_data.connector_response.encoded_data,
+ encoded_data: payment_data.payment_attempt.encoded_data,
capture_method: payment_data.payment_attempt.capture_method,
connector_meta: payment_data.payment_attempt.connector_metadata,
sync_type: match payment_data.multiple_capture_data {
@@ -1356,7 +1349,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz
browser_info,
email: payment_data.email,
payment_method_data: payment_data.payment_method_data,
- connector_transaction_id: payment_data.connector_response.connector_transaction_id,
+ connector_transaction_id: payment_data.payment_attempt.connector_transaction_id,
redirect_response,
connector_meta: payment_data.payment_attempt.connector_metadata,
})
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index 3efef2c40f2..6fe34d8dd69 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -5,7 +5,6 @@ pub mod cache;
pub mod capture;
pub mod cards_info;
pub mod configs;
-pub mod connector_response;
pub mod customers;
pub mod dispute;
pub mod ephemeral_key;
@@ -52,7 +51,6 @@ pub trait StorageInterface:
+ api_keys::ApiKeyInterface
+ configs::ConfigInterface
+ capture::CaptureInterface
- + connector_response::ConnectorResponseInterface
+ customers::CustomerInterface
+ dispute::DisputeInterface
+ ephemeral_key::EphemeralKeyInterface
diff --git a/crates/router/src/db/connector_response.rs b/crates/router/src/db/connector_response.rs
deleted file mode 100644
index 354231d136e..00000000000
--- a/crates/router/src/db/connector_response.rs
+++ /dev/null
@@ -1,343 +0,0 @@
-use error_stack::{IntoReport, ResultExt};
-use router_env::{instrument, tracing};
-
-use super::{MockDb, Store};
-use crate::{
- core::errors::{self, CustomResult},
- types::storage::{self as storage_type, enums},
-};
-
-#[async_trait::async_trait]
-pub trait ConnectorResponseInterface {
- async fn insert_connector_response(
- &self,
- connector_response: storage_type::ConnectorResponseNew,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<storage_type::ConnectorResponse, errors::StorageError>;
-
- async fn find_connector_response_by_payment_id_merchant_id_attempt_id(
- &self,
- payment_id: &str,
- merchant_id: &str,
- attempt_id: &str,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<storage_type::ConnectorResponse, errors::StorageError>;
-
- async fn update_connector_response(
- &self,
- this: storage_type::ConnectorResponse,
- payment_attempt: storage_type::ConnectorResponseUpdate,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<storage_type::ConnectorResponse, errors::StorageError>;
-}
-
-#[cfg(not(feature = "kv_store"))]
-mod storage {
- use error_stack::IntoReport;
- use router_env::{instrument, tracing};
-
- use super::Store;
- use crate::{
- connection,
- core::errors::{self, CustomResult},
- types::storage::{self as storage_type, enums},
- };
-
- #[async_trait::async_trait]
- impl super::ConnectorResponseInterface for Store {
- #[instrument(skip_all)]
- async fn insert_connector_response(
- &self,
- connector_response: storage_type::ConnectorResponseNew,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<storage_type::ConnectorResponse, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- connector_response
- .insert(&conn)
- .await
- .map_err(Into::into)
- .into_report()
- }
-
- #[instrument(skip_all)]
- async fn find_connector_response_by_payment_id_merchant_id_attempt_id(
- &self,
- payment_id: &str,
- merchant_id: &str,
- attempt_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<storage_type::ConnectorResponse, errors::StorageError> {
- let conn = connection::pg_connection_read(self).await?;
- storage_type::ConnectorResponse::find_by_payment_id_merchant_id_attempt_id(
- &conn,
- payment_id,
- merchant_id,
- attempt_id,
- )
- .await
- .map_err(Into::into)
- .into_report()
- }
-
- async fn update_connector_response(
- &self,
- this: storage_type::ConnectorResponse,
- connector_response_update: storage_type::ConnectorResponseUpdate,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<storage_type::ConnectorResponse, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- this.update(&conn, connector_response_update)
- .await
- .map_err(Into::into)
- .into_report()
- }
- }
-}
-
-#[cfg(feature = "kv_store")]
-mod storage {
-
- use diesel_models::enums as storage_enums;
- use error_stack::{IntoReport, ResultExt};
- use redis_interface::HsetnxReply;
- use router_env::{instrument, tracing};
- use storage_impl::redis::kv_store::{kv_wrapper, KvOperation};
-
- use super::Store;
- use crate::{
- connection,
- core::errors::{self, CustomResult},
- types::storage::{self as storage_type, enums, kv},
- utils::db_utils,
- };
-
- #[async_trait::async_trait]
- impl super::ConnectorResponseInterface for Store {
- #[instrument(skip_all)]
- async fn insert_connector_response(
- &self,
- connector_response: storage_type::ConnectorResponseNew,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<storage_type::ConnectorResponse, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
-
- match storage_scheme {
- storage_enums::MerchantStorageScheme::PostgresOnly => connector_response
- .insert(&conn)
- .await
- .map_err(Into::into)
- .into_report(),
- storage_enums::MerchantStorageScheme::RedisKv => {
- let merchant_id = &connector_response.merchant_id;
- let payment_id = &connector_response.payment_id;
- let attempt_id = &connector_response.attempt_id;
-
- let key = format!("mid_{merchant_id}_pid_{payment_id}");
- let field = format!("connector_resp_{merchant_id}_{payment_id}_{attempt_id}");
-
- let created_connector_resp = storage_type::ConnectorResponse {
- id: Default::default(),
- payment_id: connector_response.payment_id.clone(),
- merchant_id: connector_response.merchant_id.clone(),
- attempt_id: connector_response.attempt_id.clone(),
- created_at: connector_response.created_at,
- modified_at: connector_response.modified_at,
- connector_name: connector_response.connector_name.clone(),
- connector_transaction_id: connector_response
- .connector_transaction_id
- .clone(),
- authentication_data: connector_response.authentication_data.clone(),
- encoded_data: connector_response.encoded_data.clone(),
- updated_by: storage_scheme.to_string(),
- };
-
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Insert {
- insertable: kv::Insertable::ConnectorResponse(
- connector_response.clone(),
- ),
- },
- };
-
- match kv_wrapper::<storage_type::ConnectorResponse, _, _>(
- self,
- KvOperation::HSetNx(&field, &created_connector_resp, redis_entry),
- &key,
- )
- .await
- .change_context(errors::StorageError::KVError)?
- .try_into_hsetnx()
- {
- Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue {
- entity: "address",
- key: Some(key),
- })
- .into_report(),
- Ok(HsetnxReply::KeySet) => Ok(created_connector_resp),
- Err(er) => Err(er).change_context(errors::StorageError::KVError),
- }
- }
- }
- }
-
- #[instrument(skip_all)]
- async fn find_connector_response_by_payment_id_merchant_id_attempt_id(
- &self,
- payment_id: &str,
- merchant_id: &str,
- attempt_id: &str,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<storage_type::ConnectorResponse, errors::StorageError> {
- let conn = connection::pg_connection_read(self).await?;
- let database_call = || async {
- storage_type::ConnectorResponse::find_by_payment_id_merchant_id_attempt_id(
- &conn,
- payment_id,
- merchant_id,
- attempt_id,
- )
- .await
- .map_err(Into::into)
- .into_report()
- };
- match storage_scheme {
- storage_enums::MerchantStorageScheme::PostgresOnly => database_call().await,
- storage_enums::MerchantStorageScheme::RedisKv => {
- let key = format!("mid_{merchant_id}_pid_{payment_id}");
- let field = format!("connector_resp_{merchant_id}_{payment_id}_{attempt_id}");
-
- db_utils::try_redis_get_else_try_database_get(
- async {
- kv_wrapper(
- self,
- KvOperation::<diesel_models::Address>::HGet(&field),
- key,
- )
- .await?
- .try_into_hget()
- },
- database_call,
- )
- .await
- }
- }
- }
-
- async fn update_connector_response(
- &self,
- this: storage_type::ConnectorResponse,
- connector_response_update: storage_type::ConnectorResponseUpdate,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<storage_type::ConnectorResponse, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- match storage_scheme {
- storage_enums::MerchantStorageScheme::PostgresOnly => this
- .update(&conn, connector_response_update)
- .await
- .map_err(Into::into)
- .into_report(),
- storage_enums::MerchantStorageScheme::RedisKv => {
- let key = format!("mid_{}_pid_{}", this.merchant_id, this.payment_id);
- let updated_connector_response = connector_response_update
- .clone()
- .apply_changeset(this.clone());
- let redis_value = serde_json::to_string(&updated_connector_response)
- .into_report()
- .change_context(errors::StorageError::KVError)?;
- let field = format!(
- "connector_resp_{}_{}_{}",
- &updated_connector_response.merchant_id,
- &updated_connector_response.payment_id,
- &updated_connector_response.attempt_id
- );
-
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Update {
- updatable: kv::Updateable::ConnectorResponseUpdate(
- kv::ConnectorResponseUpdateMems {
- orig: this,
- update_data: connector_response_update,
- },
- ),
- },
- };
-
- kv_wrapper::<(), _, _>(
- self,
- KvOperation::Hset::<storage_type::ConnectorResponse>(
- (&field, redis_value),
- redis_entry,
- ),
- &key,
- )
- .await
- .change_context(errors::StorageError::KVError)?
- .try_into_hset()
- .change_context(errors::StorageError::KVError)?;
-
- Ok(updated_connector_response)
- }
- }
- }
- }
-}
-
-#[async_trait::async_trait]
-impl ConnectorResponseInterface for MockDb {
- #[instrument(skip_all)]
- async fn insert_connector_response(
- &self,
- new: storage_type::ConnectorResponseNew,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<storage_type::ConnectorResponse, errors::StorageError> {
- let mut connector_response = self.connector_response.lock().await;
- let response = storage_type::ConnectorResponse {
- id: connector_response
- .len()
- .try_into()
- .into_report()
- .change_context(errors::StorageError::MockDbError)?,
- payment_id: new.payment_id,
- merchant_id: new.merchant_id,
- attempt_id: new.attempt_id,
- created_at: new.created_at,
- modified_at: new.modified_at,
- connector_name: new.connector_name,
- connector_transaction_id: new.connector_transaction_id,
- authentication_data: new.authentication_data,
- encoded_data: new.encoded_data,
- updated_by: storage_scheme.to_string(),
- };
- connector_response.push(response.clone());
- Ok(response)
- }
-
- #[instrument(skip_all)]
- async fn find_connector_response_by_payment_id_merchant_id_attempt_id(
- &self,
- _payment_id: &str,
- _merchant_id: &str,
- _attempt_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<storage_type::ConnectorResponse, errors::StorageError> {
- // [#172]: Implement function for `MockDb`
- Err(errors::StorageError::MockDbError)?
- }
-
- // safety: interface only used for testing
- #[allow(clippy::unwrap_used)]
- async fn update_connector_response(
- &self,
- this: storage_type::ConnectorResponse,
- connector_response_update: storage_type::ConnectorResponseUpdate,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<storage_type::ConnectorResponse, errors::StorageError> {
- let mut connector_response = self.connector_response.lock().await;
- let response = connector_response
- .iter_mut()
- .find(|item| item.id == this.id)
- .unwrap();
- *response = connector_response_update.apply_changeset(response.clone());
- Ok(response.clone())
- }
-}
diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs
index 1e7c34a420b..c63ff5fb7f8 100644
--- a/crates/router/src/types/storage.rs
+++ b/crates/router/src/types/storage.rs
@@ -4,7 +4,6 @@ pub mod business_profile;
pub mod capture;
pub mod cards_info;
pub mod configs;
-pub mod connector_response;
pub mod customers;
pub mod dispute;
pub mod enums;
@@ -41,11 +40,11 @@ pub use data_models::payments::{
};
pub use self::{
- address::*, api_keys::*, capture::*, cards_info::*, configs::*, connector_response::*,
- customers::*, dispute::*, ephemeral_key::*, events::*, file::*, gsm::*, locker_mock_up::*,
- mandate::*, merchant_account::*, merchant_connector_account::*, merchant_key_store::*,
- payment_link::*, payment_method::*, payout_attempt::*, payouts::*, process_tracker::*,
- refund::*, reverse_lookup::*, routing_algorithm::*,
+ address::*, api_keys::*, capture::*, cards_info::*, configs::*, customers::*, dispute::*,
+ ephemeral_key::*, events::*, file::*, gsm::*, locker_mock_up::*, mandate::*,
+ merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_link::*,
+ payment_method::*, payout_attempt::*, payouts::*, process_tracker::*, refund::*,
+ reverse_lookup::*, routing_algorithm::*,
};
use crate::types::api::routing;
diff --git a/crates/router/src/types/storage/connector_response.rs b/crates/router/src/types/storage/connector_response.rs
deleted file mode 100644
index c93c231e3d1..00000000000
--- a/crates/router/src/types/storage/connector_response.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-pub use diesel_models::{
- connector_response::{
- ConnectorResponse, ConnectorResponseNew, ConnectorResponseUpdate,
- ConnectorResponseUpdateInternal,
- },
- enums::MerchantStorageScheme,
-};
-
-pub trait ConnectorResponseExt {
- fn make_new_connector_response(
- payment_id: String,
- merchant_id: String,
- attempt_id: String,
- connector: Option<String>,
- storage_scheme: String,
- ) -> ConnectorResponseNew;
-}
-
-impl ConnectorResponseExt for ConnectorResponse {
- fn make_new_connector_response(
- payment_id: String,
- merchant_id: String,
- attempt_id: String,
- connector: Option<String>,
- storage_scheme: String,
- ) -> ConnectorResponseNew {
- let now = common_utils::date_time::now();
- ConnectorResponseNew {
- payment_id,
- merchant_id,
- attempt_id,
- created_at: now,
- modified_at: now,
- connector_name: connector,
- connector_transaction_id: None,
- authentication_data: None,
- encoded_data: None,
- updated_by: storage_scheme,
- }
- }
-}
diff --git a/crates/router/src/types/storage/kv.rs b/crates/router/src/types/storage/kv.rs
index 2afc73e6637..6bb6c38e7b2 100644
--- a/crates/router/src/types/storage/kv.rs
+++ b/crates/router/src/types/storage/kv.rs
@@ -1,4 +1,4 @@
pub use diesel_models::kv::{
- AddressUpdateMems, ConnectorResponseUpdateMems, DBOperation, Insertable,
- PaymentAttemptUpdateMems, PaymentIntentUpdateMems, RefundUpdateMems, TypedSql, Updateable,
+ AddressUpdateMems, DBOperation, Insertable, PaymentAttemptUpdateMems, PaymentIntentUpdateMems,
+ RefundUpdateMems, TypedSql, Updateable,
};
diff --git a/crates/storage_impl/src/connector_response.rs b/crates/storage_impl/src/connector_response.rs
deleted file mode 100644
index 7d4ff6df94d..00000000000
--- a/crates/storage_impl/src/connector_response.rs
+++ /dev/null
@@ -1,5 +0,0 @@
-use diesel_models::connector_response::ConnectorResponse;
-
-use crate::redis::kv_store::KvStorePartition;
-
-impl KvStorePartition for ConnectorResponse {}
diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs
index cef4a8981a4..00d8703940c 100644
--- a/crates/storage_impl/src/lib.rs
+++ b/crates/storage_impl/src/lib.rs
@@ -8,7 +8,6 @@ use redis::{kv_store::RedisConnInterface, RedisStore};
mod address;
pub mod config;
pub mod connection;
-mod connector_response;
pub mod database;
pub mod errors;
mod lookup;
diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs
index 76bdb1160cc..33f3f7a77f2 100644
--- a/crates/storage_impl/src/mock_db.rs
+++ b/crates/storage_impl/src/mock_db.rs
@@ -27,7 +27,6 @@ pub struct MockDb {
pub customers: Arc<Mutex<Vec<store::Customer>>>,
pub refunds: Arc<Mutex<Vec<store::Refund>>>,
pub processes: Arc<Mutex<Vec<store::ProcessTracker>>>,
- pub connector_response: Arc<Mutex<Vec<store::ConnectorResponse>>>,
pub redis: Arc<RedisStore>,
pub api_keys: Arc<Mutex<Vec<store::ApiKey>>>,
pub ephemeral_keys: Arc<Mutex<Vec<store::EphemeralKey>>>,
@@ -57,7 +56,6 @@ impl MockDb {
customers: Default::default(),
refunds: Default::default(),
processes: Default::default(),
- connector_response: Default::default(),
redis: Arc::new(
RedisStore::new(redis)
.await
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index e3047221b6f..21002917df8 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -1062,7 +1062,6 @@ impl DataModelExt for PaymentAttemptNew {
connector_response_reference_id: self.connector_response_reference_id,
multiple_capture_count: self.multiple_capture_count,
amount_capturable: self.amount_capturable,
-
updated_by: self.updated_by,
authentication_data: self.authentication_data,
encoded_data: self.encoded_data,
@@ -1244,6 +1243,8 @@ impl DataModelExt for PaymentAttemptUpdate {
connector_response_reference_id,
amount_capturable,
updated_by,
+ authentication_data,
+ encoded_data,
} => DieselPaymentAttemptUpdate::ResponseUpdate {
status,
connector,
@@ -1259,6 +1260,8 @@ impl DataModelExt for PaymentAttemptUpdate {
connector_response_reference_id,
amount_capturable,
updated_by,
+ authentication_data,
+ encoded_data,
},
Self::UnresolvedResponseUpdate {
status,
@@ -1481,6 +1484,8 @@ impl DataModelExt for PaymentAttemptUpdate {
connector_response_reference_id,
amount_capturable,
updated_by,
+ authentication_data,
+ encoded_data,
} => Self::ResponseUpdate {
status,
connector,
@@ -1496,6 +1501,8 @@ impl DataModelExt for PaymentAttemptUpdate {
connector_response_reference_id,
amount_capturable,
updated_by,
+ authentication_data,
+ encoded_data,
},
DieselPaymentAttemptUpdate::UnresolvedResponseUpdate {
status,
diff --git a/migrations/2023-11-08-144951_drop_connector_response_table/down.sql b/migrations/2023-11-08-144951_drop_connector_response_table/down.sql
new file mode 100644
index 00000000000..ff9ca4e4f9c
--- /dev/null
+++ b/migrations/2023-11-08-144951_drop_connector_response_table/down.sql
@@ -0,0 +1,34 @@
+-- This file should undo anything in `up.sql`
+CREATE TABLE connector_response (
+ id SERIAL PRIMARY KEY,
+ payment_id VARCHAR(255) NOT NULL,
+ merchant_id VARCHAR(255) NOT NULL,
+ txn_id VARCHAR(255) NOT NULL,
+ created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP,
+ modified_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP,
+ connector_name VARCHAR(32) NOT NULL,
+ connector_transaction_id VARCHAR(255),
+ authentication_data JSON,
+ encoded_data TEXT
+);
+
+CREATE UNIQUE INDEX connector_response_id_index ON connector_response (payment_id, merchant_id, txn_id);
+
+ALTER TABLE connector_response ALTER COLUMN connector_name DROP NOT NULL;
+ALTER TABLE connector_response RENAME COLUMN txn_id TO attempt_id;
+ALTER TABLE connector_response
+ ALTER COLUMN payment_id TYPE VARCHAR(64),
+ ALTER COLUMN merchant_id TYPE VARCHAR(64),
+ ALTER COLUMN attempt_id TYPE VARCHAR(64),
+ ALTER COLUMN connector_name TYPE VARCHAR(64),
+ ALTER COLUMN connector_transaction_id TYPE VARCHAR(128);
+
+
+
+ALTER TABLE connector_response
+ALTER COLUMN modified_at DROP DEFAULT;
+
+ALTER TABLE connector_response
+ALTER COLUMN created_at DROP DEFAULT;
+
+ALTER TABLE connector_response ADD column updated_by VARCHAR(32) NOT NULL DEFAULT 'postgres_only';
diff --git a/migrations/2023-11-08-144951_drop_connector_response_table/up.sql b/migrations/2023-11-08-144951_drop_connector_response_table/up.sql
new file mode 100644
index 00000000000..0059a6b38dc
--- /dev/null
+++ b/migrations/2023-11-08-144951_drop_connector_response_table/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+DROP TABLE connector_response; --NOT to run in deployment envs
\ No newline at end of file
|
refactor
|
remove connector response table and use payment_attempt instead (#2644)
|
58771b8985a53c83185805f770fee26c5836c645
|
2024-01-31 15:42:17
|
Sakil Mostak
|
fix(configs): Add configs for Payme 3DS (#3415)
| false
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 00c325f058e..f7e9fa70f6e 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -352,6 +352,7 @@ bluesnap = { payment_method = "card" }
bankofamerica = { payment_method = "card" }
cybersource = { payment_method = "card" }
nmi = { payment_method = "card" }
+payme = {payment_method = "card" }
[dummy_connector]
enabled = true # Whether dummy connector is enabled or not
diff --git a/config/development.toml b/config/development.toml
index 681db4ac5d1..584bdf751a2 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -434,6 +434,7 @@ bluesnap = {payment_method = "card"}
bankofamerica = {payment_method = "card"}
cybersource = {payment_method = "card"}
nmi = {payment_method = "card"}
+payme = {payment_method = "card"}
[connector_customer]
connector_list = "gocardless,stax,stripe"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index d468f1dd412..67fca85929d 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -245,6 +245,7 @@ bluesnap = {payment_method = "card"}
bankofamerica = {payment_method = "card"}
cybersource = {payment_method = "card"}
nmi = {payment_method = "card"}
+payme = {payment_method = "card"}
[dummy_connector]
enabled = true
|
fix
|
Add configs for Payme 3DS (#3415)
|
2ea1fd6c9c3273199d8fbe5d4537f67b4b68ccf3
|
2022-12-08 14:28:46
|
Jagan
|
fix(build): fix build issue in local and docker setup (#81)
| false
|
diff --git a/config/Development.toml b/config/Development.toml
index 1f1e5513079..6bfe448d44f 100644
--- a/config/Development.toml
+++ b/config/Development.toml
@@ -24,7 +24,9 @@ pool_size = 5
temp_card_key = "OJobAzAwOlibOhygIZOqOGideGUdEBeX" # 32 character long key
[locker]
+host = ""
mock_locker = true
+basilisk_host = ""
[jwekey]
locker_key_identifier1 = ""
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index e3beee6b51f..310e1660325 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -32,8 +32,17 @@ pool_size = 5
temp_card_key = "OJobAzAwOlibOhygIZOqOGideGUdEBeX" # 32 character long key
[locker]
+host = ""
+mock_locker = true
+basilisk_host = ""
[jwekey]
+locker_key_identifier1 = ""
+locker_key_identifier2 = ""
+locker_encryption_key1 = ""
+locker_encryption_key2 = ""
+locker_decryption_key1 = ""
+locker_decryption_key2 = ""
[redis]
host = "redis-queue"
|
fix
|
fix build issue in local and docker setup (#81)
|
fcfd567bfe55747dcb05c88def96373a707f8c78
|
2024-03-18 15:31:51
|
Sahkal Poddar
|
refactor(payment_link): Make performance optimisation for payment_link (#4092)
| false
|
diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html
index f258b4fefd3..732e331892f 100644
--- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html
+++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html
@@ -4,13 +4,12 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Payments requested by HyperSwitch</title>
+ {{ preload_link_tags }}
+ <link rel="preconnect" href="https://fonts.gstatic.com">
+ <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800">
<style>
{{rendered_css}}
</style>
- <link
- rel="stylesheet"
- href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800"
- />
</head>
<body class="hide-scrollbar">
<div id="payment-details-shimmer">
diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js
index 3e262b45dfa..da6899923b4 100644
--- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js
+++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js
@@ -402,8 +402,8 @@ function initializeSDK() {
: paymentDetails.sdk_layout;
var unifiedCheckoutOptions = {
- displaySavedPaymentMethodsCheckbox: true,
- displaySavedPaymentMethods: true,
+ displaySavedPaymentMethodsCheckbox: false,
+ displaySavedPaymentMethods: false,
layout: {
type: type, //accordion , tabs, spaced accordion
spacedAccordionItems: paymentDetails.sdk_layout === "spaced_accordion",
@@ -623,6 +623,8 @@ function renderPaymentDetails(paymentDetails) {
// Create merchant logo's node
var merchantLogoNode = document.createElement("img");
merchantLogoNode.src = paymentDetails.merchant_logo;
+ merchantLogoNode.setAttribute("width", "48"); // Set width to 100 pixels
+ merchantLogoNode.setAttribute("height", "48");
// Create expiry node
var paymentExpiryNode = document.createElement("div");
@@ -755,6 +757,9 @@ function renderCartItem(
nameAndQuantityWrapperNode.className = "hyper-checkout-cart-product-details";
// Image
var productImageNode = document.createElement("img");
+ productImageNode.setAttribute("width", 56);
+ productImageNode.setAttribute("height", 56);
+
productImageNode.className = "hyper-checkout-cart-product-image";
productImageNode.src = item.product_img_link;
// Product title
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index a4c6bdd0a16..40a9713a8cf 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -1994,6 +1994,11 @@ pub fn build_payment_link_html(
let _ = tera.add_raw_template("payment_link", &html_template);
+ context.insert(
+ "preload_link_tags",
+ &get_preload_link_html_template(&payment_link_data.sdk_url),
+ );
+
context.insert(
"hyperloader_sdk_link",
&get_hyper_loader_sdk(&payment_link_data.sdk_url),
@@ -2014,6 +2019,14 @@ fn get_hyper_loader_sdk(sdk_url: &str) -> String {
format!("<script src=\"{sdk_url}\" onload=\"initializeSDK()\"></script>")
}
+fn get_preload_link_html_template(sdk_url: &str) -> String {
+ format!(
+ r#"<link rel="preload" href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800" as="style">
+ <link rel="preload" href="{sdk_url}" as="script">"#,
+ sdk_url = sdk_url
+ )
+}
+
pub fn get_payment_link_status(
payment_link_data: PaymentLinkStatusData,
) -> CustomResult<String, errors::ApiErrorResponse> {
|
refactor
|
Make performance optimisation for payment_link (#4092)
|
0a65e8f92587bc0cd1aa65fc3a18c1b09aef930f
|
2023-09-20 18:44:46
|
github-actions
|
chore(version): v1.42.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 36c31d35d8f..1e0b5a56593 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,26 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 1.42.0 (2023-09-20)
+
+### Features
+
+- **connector:** [Trustpay] Add Blik payment method for trustpay ([#2152](https://github.com/juspay/hyperswitch/pull/2152)) ([`d0eec9e`](https://github.com/juspay/hyperswitch/commit/d0eec9e357a2ef6074c9a02239337378fbf8412a))
+
+### Bug Fixes
+
+- **connector:** [SQUARE] Fix payments cancel issue ([#2162](https://github.com/juspay/hyperswitch/pull/2162)) ([`081545e`](https://github.com/juspay/hyperswitch/commit/081545e9121861ac7c1867a5e3f4c59ef848eeeb))
+
+### Refactors
+
+- **configs:** Make TOML file an optional source of application configuration ([#2185](https://github.com/juspay/hyperswitch/pull/2185)) ([`69fbebf`](https://github.com/juspay/hyperswitch/commit/69fbebf4630047ac33defc010811d1b4c4c9051a))
+- **core:** Error thrown for wrong mca in applepay_verification flow change from 5xx to 4xx ([#2189](https://github.com/juspay/hyperswitch/pull/2189)) ([`656e710`](https://github.com/juspay/hyperswitch/commit/656e7106b44ba27a9058191259596e0a399aa20b))
+
+**Full Changelog:** [`v1.41.0...v1.42.0`](https://github.com/juspay/hyperswitch/compare/v1.41.0...v1.42.0)
+
+- - -
+
+
## 1.41.0 (2023-09-20)
### Features
|
chore
|
v1.42.0
|
d3521e7e76b327d88ec5506302102e66f014cb95
|
2024-08-22 17:02:38
|
Hrithikesh
|
feat: add new routes for profile level list apis (#5589)
| false
|
diff --git a/crates/openapi/src/routes/disputes.rs b/crates/openapi/src/routes/disputes.rs
index 491edae4101..c5875d67a9a 100644
--- a/crates/openapi/src/routes/disputes.rs
+++ b/crates/openapi/src/routes/disputes.rs
@@ -42,3 +42,30 @@ pub async fn retrieve_dispute() {}
security(("api_key" = []))
)]
pub async fn retrieve_disputes_list() {}
+
+/// Disputes - List Disputes for The Given Business Profiles
+/// Lists all the Disputes for a merchant
+#[utoipa::path(
+ get,
+ path = "/disputes/profile/list",
+ params(
+ ("limit" = Option<i64>, Query, description = "The maximum number of Dispute Objects to include in the response"),
+ ("dispute_status" = Option<DisputeStatus>, Query, description = "The status of dispute"),
+ ("dispute_stage" = Option<DisputeStage>, Query, description = "The stage of dispute"),
+ ("reason" = Option<String>, Query, description = "The reason for dispute"),
+ ("connector" = Option<String>, Query, description = "The connector linked to dispute"),
+ ("received_time" = Option<PrimitiveDateTime>, Query, description = "The time at which dispute is received"),
+ ("received_time.lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the dispute received time"),
+ ("received_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the dispute received time"),
+ ("received_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the dispute received time"),
+ ("received_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the dispute received time"),
+ ),
+ responses(
+ (status = 200, description = "The dispute list was retrieved successfully", body = Vec<DisputeResponse>),
+ (status = 401, description = "Unauthorized request")
+ ),
+ tag = "Disputes",
+ operation_id = "List Disputes for The given Business Profiles",
+ security(("api_key" = []))
+)]
+pub async fn retrieve_disputes_list_profile() {}
diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs
index 653fa16c75e..0e3bb9fe072 100644
--- a/crates/openapi/src/routes/payments.rs
+++ b/crates/openapi/src/routes/payments.rs
@@ -459,6 +459,33 @@ pub fn payments_cancel() {}
)]
pub fn payments_list() {}
+/// Business Profile level Payments - List
+///
+/// To list the payments
+#[utoipa::path(
+ get,
+ path = "/payments/list",
+ params(
+ ("customer_id" = String, Query, description = "The identifier for the customer"),
+ ("starting_after" = String, Query, description = "A cursor for use in pagination, fetch the next list after some object"),
+ ("ending_before" = String, Query, description = "A cursor for use in pagination, fetch the previous list before some object"),
+ ("limit" = i64, Query, description = "Limit on the number of objects to return"),
+ ("created" = PrimitiveDateTime, Query, description = "The time at which payment is created"),
+ ("created_lt" = PrimitiveDateTime, Query, description = "Time less than the payment created time"),
+ ("created_gt" = PrimitiveDateTime, Query, description = "Time greater than the payment created time"),
+ ("created_lte" = PrimitiveDateTime, Query, description = "Time less than or equals to the payment created time"),
+ ("created_gte" = PrimitiveDateTime, Query, description = "Time greater than or equals to the payment created time")
+ ),
+ responses(
+ (status = 200, description = "Received payment list"),
+ (status = 404, description = "No payments found")
+ ),
+ tag = "Payments",
+ operation_id = "List all Payments for the Profile",
+ security(("api_key" = []))
+)]
+pub async fn profile_payments_list() {}
+
/// Payments - Incremental Authorization
///
/// Authorized amount for a payment can be incremented if it is in status: requires_capture
diff --git a/crates/openapi/src/routes/payouts.rs b/crates/openapi/src/routes/payouts.rs
index 0a429041afe..3f085592ef1 100644
--- a/crates/openapi/src/routes/payouts.rs
+++ b/crates/openapi/src/routes/payouts.rs
@@ -107,6 +107,28 @@ pub async fn payouts_fulfill() {}
)]
pub async fn payouts_list() {}
+/// Payouts - List for the Given Profiles
+#[utoipa::path(
+ get,
+ path = "/payouts/profile/list",
+ params(
+ ("customer_id" = String, Query, description = "The identifier for customer"),
+ ("starting_after" = String, Query, description = "A cursor for use in pagination, fetch the next list after some object"),
+ ("ending_before" = String, Query, description = "A cursor for use in pagination, fetch the previous list before some object"),
+ ("limit" = String, Query, description = "limit on the number of objects to return"),
+ ("created" = String, Query, description = "The time at which payout is created"),
+ ("time_range" = String, Query, description = "The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).")
+ ),
+ responses(
+ (status = 200, description = "Payouts listed", body = PayoutListResponse),
+ (status = 404, description = "Payout not found")
+ ),
+ tag = "Payouts",
+ operation_id = "List payouts using generic constraints for the given Profiles",
+ security(("api_key" = []))
+)]
+pub async fn payouts_list_profile() {}
+
/// Payouts - List available filters
#[utoipa::path(
post,
@@ -136,6 +158,21 @@ pub async fn payouts_list_filters() {}
)]
pub async fn payouts_list_by_filter() {}
+/// Payouts - List using filters for the given Profiles
+#[utoipa::path(
+ post,
+ path = "/payouts/list",
+ request_body=PayoutListFilterConstraints,
+ responses(
+ (status = 200, description = "Payouts filtered", body = PayoutListResponse),
+ (status = 404, description = "Payout not found")
+ ),
+ tag = "Payouts",
+ operation_id = "Filter payouts using specific constraints for the given Profiles",
+ security(("api_key" = []))
+)]
+pub async fn payouts_list_by_filter_profile() {}
+
/// Payouts - Confirm
#[utoipa::path(
post,
diff --git a/crates/openapi/src/routes/refunds.rs b/crates/openapi/src/routes/refunds.rs
index aa4728869be..5c72fe8b48f 100644
--- a/crates/openapi/src/routes/refunds.rs
+++ b/crates/openapi/src/routes/refunds.rs
@@ -128,6 +128,22 @@ pub async fn refunds_update() {}
)]
pub fn refunds_list() {}
+/// Refunds - List For the Given profiles
+///
+/// Lists all the refunds associated with the merchant or a payment_id if payment_id is not provided
+#[utoipa::path(
+ post,
+ path = "/refunds/profile/list",
+ request_body=RefundListRequest,
+ responses(
+ (status = 200, description = "List of refunds", body = RefundListResponse),
+ ),
+ tag = "Refunds",
+ operation_id = "List all Refunds for the given Profiles",
+ security(("api_key" = []))
+)]
+pub fn refunds_list_profile() {}
+
/// Refunds - Filter
///
/// To list the refunds filters associated with list of connectors, currencies and payment statuses
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index 46b679f0508..80ee0494847 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -544,6 +544,57 @@ pub async fn payment_connector_list(
)
.await
}
+/// Merchant Connector - List
+///
+/// List Merchant Connector Details for the merchant
+#[utoipa::path(
+ get,
+ path = "/accounts/{account_id}/profile/connectors",
+ params(
+ ("account_id" = String, Path, description = "The unique identifier for the merchant account"),
+ ),
+ responses(
+ (status = 200, description = "Merchant Connector list retrieved successfully", body = Vec<MerchantConnectorResponse>),
+ (status = 404, description = "Merchant Connector does not exist in records"),
+ (status = 401, description = "Unauthorized request")
+ ),
+ tag = "Merchant Connector Account",
+ operation_id = "List all Merchant Connectors for The given Profile",
+ security(("admin_api_key" = []))
+)]
+#[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsList))]
+pub async fn payment_connector_list_profile(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<common_utils::id_type::MerchantId>,
+) -> HttpResponse {
+ let flow = Flow::MerchantConnectorsList;
+ let merchant_id = path.into_inner();
+
+ api::server_wrap(
+ flow,
+ state,
+ &req,
+ merchant_id.to_owned(),
+ |state, auth, merchant_id, _| {
+ list_payment_connectors(
+ state,
+ merchant_id,
+ auth.profile_id.map(|profile_id| vec![profile_id]),
+ )
+ },
+ auth::auth_type(
+ &auth::AdminApiAuthWithMerchantId::default(),
+ &auth::JWTAuthMerchantFromRoute {
+ merchant_id,
+ required_permission: Permission::MerchantConnectorAccountRead,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ )
+ .await
+}
/// Merchant Connector - Update
///
/// To update an existing Merchant Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc.
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index ae691885b45..d52c1cef45a 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -537,9 +537,18 @@ impl Payments {
.route(web::get().to(payments_list))
.route(web::post().to(payments_list_by_filter)),
)
+ .service(
+ web::resource("/profile/list")
+ .route(web::get().to(profile_payments_list))
+ .route(web::post().to(profile_payments_list_by_filter)),
+ )
.service(web::resource("/filter").route(web::post().to(get_filters_for_payments)))
.service(web::resource("/v2/filter").route(web::get().to(get_payment_filters)))
.service(web::resource("/aggregate").route(web::get().to(get_payments_aggregates)))
+ .service(
+ web::resource("/v2/profile/filter")
+ .route(web::get().to(get_payment_filters_profile)),
+ )
.service(
web::resource("/{payment_id}/manual-update")
.route(web::put().to(payments_manual_update)),
@@ -948,8 +957,13 @@ impl Refunds {
{
route = route
.service(web::resource("/list").route(web::post().to(refunds_list)))
+ .service(web::resource("/profile/list").route(web::post().to(refunds_list_profile)))
.service(web::resource("/filter").route(web::post().to(refunds_filter_list)))
.service(web::resource("/v2/filter").route(web::get().to(get_refunds_filters)))
+ .service(
+ web::resource("/v2/profile/filter")
+ .route(web::get().to(get_refunds_filters_profile)),
+ )
.service(
web::resource("/{id}/manual-update")
.route(web::put().to(refunds_manual_update)),
@@ -987,6 +1001,11 @@ impl Payouts {
.route(web::get().to(payouts_list))
.route(web::post().to(payouts_list_by_filter)),
)
+ .service(
+ web::resource("/profile/list")
+ .route(web::get().to(payouts_list_profile))
+ .route(web::post().to(payouts_list_by_filter_profile)),
+ )
.service(
web::resource("/filter").route(web::post().to(payouts_list_available_filters)),
);
@@ -1218,6 +1237,10 @@ impl MerchantConnectorAccount {
.route(web::post().to(connector_create))
.route(web::get().to(payment_connector_list)),
)
+ .service(
+ web::resource("/{merchant_id}/profile/connectors")
+ .route(web::get().to(payment_connector_list_profile)),
+ )
.service(
web::resource("/{merchant_id}/connectors/{merchant_connector_id}")
.route(web::get().to(connector_retrieve))
@@ -1369,6 +1392,9 @@ impl Disputes {
web::scope("/disputes")
.app_data(web::Data::new(state))
.service(web::resource("/list").route(web::get().to(retrieve_disputes_list)))
+ .service(
+ web::resource("/profile/list").route(web::get().to(retrieve_disputes_list_profile)),
+ )
.service(web::resource("/accept/{dispute_id}").route(web::post().to(accept_dispute)))
.service(
web::resource("/evidence")
diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs
index a6670414f6f..e8edcd704d7 100644
--- a/crates/router/src/routes/disputes.rs
+++ b/crates/router/src/routes/disputes.rs
@@ -104,6 +104,62 @@ pub async fn retrieve_disputes_list(
))
.await
}
+
+/// Disputes - List Disputes for The Given Business Profiles
+#[utoipa::path(
+ get,
+ path = "/disputes/profile/list",
+ params(
+ ("limit" = Option<i64>, Query, description = "The maximum number of Dispute Objects to include in the response"),
+ ("dispute_status" = Option<DisputeStatus>, Query, description = "The status of dispute"),
+ ("dispute_stage" = Option<DisputeStage>, Query, description = "The stage of dispute"),
+ ("reason" = Option<String>, Query, description = "The reason for dispute"),
+ ("connector" = Option<String>, Query, description = "The connector linked to dispute"),
+ ("received_time" = Option<PrimitiveDateTime>, Query, description = "The time at which dispute is received"),
+ ("received_time.lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the dispute received time"),
+ ("received_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the dispute received time"),
+ ("received_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the dispute received time"),
+ ("received_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the dispute received time"),
+ ),
+ responses(
+ (status = 200, description = "The dispute list was retrieved successfully", body = Vec<DisputeResponse>),
+ (status = 401, description = "Unauthorized request")
+ ),
+ tag = "Disputes",
+ operation_id = "List Disputes for The given Business Profiles",
+ security(("api_key" = []))
+)]
+#[instrument(skip_all, fields(flow = ?Flow::DisputesList))]
+pub async fn retrieve_disputes_list_profile(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ payload: web::Query<dispute_models::DisputeListConstraints>,
+) -> HttpResponse {
+ let flow = Flow::DisputesList;
+ let payload = payload.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth, req, _| {
+ disputes::retrieve_disputes_list(
+ state,
+ auth.merchant_account,
+ auth.profile_id.map(|profile_id| vec![profile_id]),
+ req,
+ )
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuth(Permission::DisputeRead),
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
/// Disputes - Accept Dispute
#[utoipa::path(
get,
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index d0c4cf42b7f..11cdf4eb7e9 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -1003,6 +1003,63 @@ pub async fn payments_list(
))
.await
}
+/// Business Profile level Payments - List
+///
+/// To list the payments
+#[utoipa::path(
+ get,
+ path = "/payments/list",
+ params(
+ ("customer_id" = String, Query, description = "The identifier for the customer"),
+ ("starting_after" = String, Query, description = "A cursor for use in pagination, fetch the next list after some object"),
+ ("ending_before" = String, Query, description = "A cursor for use in pagination, fetch the previous list before some object"),
+ ("limit" = i64, Query, description = "Limit on the number of objects to return"),
+ ("created" = PrimitiveDateTime, Query, description = "The time at which payment is created"),
+ ("created_lt" = PrimitiveDateTime, Query, description = "Time less than the payment created time"),
+ ("created_gt" = PrimitiveDateTime, Query, description = "Time greater than the payment created time"),
+ ("created_lte" = PrimitiveDateTime, Query, description = "Time less than or equals to the payment created time"),
+ ("created_gte" = PrimitiveDateTime, Query, description = "Time greater than or equals to the payment created time")
+ ),
+ responses(
+ (status = 200, description = "Received payment list"),
+ (status = 404, description = "No payments found")
+ ),
+ tag = "Payments",
+ operation_id = "List all Payments for the Profile",
+ security(("api_key" = []))
+)]
+#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]
+#[cfg(feature = "olap")]
+pub async fn profile_payments_list(
+ state: web::Data<app::AppState>,
+ req: actix_web::HttpRequest,
+ payload: web::Query<payment_types::PaymentListConstraints>,
+) -> impl Responder {
+ let flow = Flow::PaymentsList;
+ let payload = payload.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth, req, _| {
+ payments::list_payments(
+ state,
+ auth.merchant_account,
+ auth.profile_id.map(|profile_id| vec![profile_id]),
+ auth.key_store,
+ req,
+ )
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuth(Permission::PaymentRead),
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]
#[cfg(feature = "olap")]
pub async fn payments_list_by_filter(
@@ -1031,6 +1088,36 @@ pub async fn payments_list_by_filter(
))
.await
}
+
+#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]
+#[cfg(feature = "olap")]
+pub async fn profile_payments_list_by_filter(
+ state: web::Data<app::AppState>,
+ req: actix_web::HttpRequest,
+ payload: web::Json<payment_types::PaymentListFilterConstraints>,
+) -> impl Responder {
+ let flow = Flow::PaymentsList;
+ let payload = payload.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: auth::AuthenticationData, req, _| {
+ payments::apply_filters_on_payments(
+ state,
+ auth.merchant_account,
+ auth.profile_id.map(|profile_id| vec![profile_id]),
+ auth.key_store,
+ req,
+ )
+ },
+ &auth::JWTAuth(Permission::PaymentRead),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]
#[cfg(feature = "olap")]
pub async fn get_filters_for_payments(
@@ -1075,6 +1162,31 @@ pub async fn get_payment_filters(
.await
}
+#[instrument(skip_all, fields(flow = ?Flow::PaymentsFilters))]
+#[cfg(feature = "olap")]
+pub async fn get_payment_filters_profile(
+ state: web::Data<app::AppState>,
+ req: actix_web::HttpRequest,
+) -> impl Responder {
+ let flow = Flow::PaymentsFilters;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ (),
+ |state, auth: auth::AuthenticationData, _, _| {
+ payments::get_payment_filters(
+ state,
+ auth.merchant_account,
+ auth.profile_id.map(|profile_id| vec![profile_id]),
+ )
+ },
+ &auth::JWTAuth(Permission::PaymentRead),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[instrument(skip_all, fields(flow = ?Flow::PaymentsAggregate))]
#[cfg(feature = "olap")]
pub async fn get_payments_aggregates(
diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs
index 40c2e36cc58..bc14a619745 100644
--- a/crates/router/src/routes/payouts.rs
+++ b/crates/router/src/routes/payouts.rs
@@ -221,6 +221,41 @@ pub async fn payouts_list(
.await
}
+/// Payouts - List Profile
+#[cfg(feature = "olap")]
+#[instrument(skip_all, fields(flow = ?Flow::PayoutsList))]
+pub async fn payouts_list_profile(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Query<payout_types::PayoutListConstraints>,
+) -> HttpResponse {
+ let flow = Flow::PayoutsList;
+ let payload = json_payload.into_inner();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth, req, _| {
+ payouts_list_core(
+ state,
+ auth.merchant_account,
+ auth.profile_id.map(|profile_id| vec![profile_id]),
+ auth.key_store,
+ req,
+ )
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuth(Permission::PayoutRead),
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
/// Payouts - Filtered list
#[cfg(feature = "olap")]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsList))]
@@ -250,6 +285,41 @@ pub async fn payouts_list_by_filter(
.await
}
+/// Payouts - Filtered list
+#[cfg(feature = "olap")]
+#[instrument(skip_all, fields(flow = ?Flow::PayoutsList))]
+pub async fn payouts_list_by_filter_profile(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<payout_types::PayoutListFilterConstraints>,
+) -> HttpResponse {
+ let flow = Flow::PayoutsList;
+ let payload = json_payload.into_inner();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth, req, _| {
+ payouts_filtered_list_core(
+ state,
+ auth.merchant_account,
+ auth.profile_id.map(|profile_id| vec![profile_id]),
+ auth.key_store,
+ req,
+ )
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuth(Permission::PayoutRead),
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
/// Payouts - Available filters
#[cfg(feature = "olap")]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsFilter))]
diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs
index 2a0d619e38b..bdef96794f4 100644
--- a/crates/router/src/routes/refunds.rs
+++ b/crates/router/src/routes/refunds.rs
@@ -241,6 +241,51 @@ pub async fn refunds_list(
.await
}
+/// Refunds - List at profile level
+///
+/// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided
+#[utoipa::path(
+ post,
+ path = "/refunds/profile/list",
+ request_body=RefundListRequest,
+ responses(
+ (status = 200, description = "List of refunds", body = RefundListResponse),
+ ),
+ tag = "Refunds",
+ operation_id = "List all Refunds",
+ security(("api_key" = []))
+)]
+#[instrument(skip_all, fields(flow = ?Flow::RefundsList))]
+#[cfg(feature = "olap")]
+pub async fn refunds_list_profile(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ payload: web::Json<api_models::refunds::RefundListRequest>,
+) -> HttpResponse {
+ let flow = Flow::RefundsList;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload.into_inner(),
+ |state, auth, req, _| {
+ refund_list(
+ state,
+ auth.merchant_account,
+ auth.profile_id.map(|profile_id| vec![profile_id]),
+ req,
+ )
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuth(Permission::RefundRead),
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
/// Refunds - Filter
///
/// To list the refunds filters associated with list of connectors, currencies and payment statuses
@@ -312,6 +357,48 @@ pub async fn get_refunds_filters(state: web::Data<AppState>, req: HttpRequest) -
.await
}
+/// Refunds - Filter V2 at profile level
+///
+/// To list the refunds filters associated with list of connectors, currencies and payment statuses
+#[utoipa::path(
+ get,
+ path = "/refunds/v2/filter/profile",
+ responses(
+ (status = 200, description = "List of static filters", body = RefundListFilters),
+ ),
+ tag = "Refunds",
+ operation_id = "List all filters for Refunds",
+ security(("api_key" = []))
+)]
+#[instrument(skip_all, fields(flow = ?Flow::RefundsFilters))]
+#[cfg(feature = "olap")]
+pub async fn get_refunds_filters_profile(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+) -> HttpResponse {
+ let flow = Flow::RefundsFilters;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ (),
+ |state, auth, _, _| {
+ get_filters_for_refunds(
+ state,
+ auth.merchant_account,
+ auth.profile_id.map(|profile_id| vec![profile_id]),
+ )
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuth(Permission::RefundRead),
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[instrument(skip_all, fields(flow = ?Flow::RefundsManualUpdate))]
#[cfg(feature = "olap")]
pub async fn refunds_manual_update(
|
feat
|
add new routes for profile level list apis (#5589)
|
e44eb13c6188df4863dc6f960e35b2ab6e96c064
|
2024-10-07 19:49:33
|
Sakil Mostak
|
refactor(dynamic_fields): rename sepa in dynamic fields (#6234)
| false
|
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index 3debb56722f..67cf28e1a6a 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -11515,9 +11515,9 @@ impl Default for super::settings::RequiredFields {
}
),
(
- "payment_method_data.bank_debit.sepa.iban".to_string(),
+ "payment_method_data.bank_debit.sepa_bank_debit.iban".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.bank_debit.sepa.iban".to_string(),
+ required_field: "payment_method_data.bank_debit.sepa_bank_debit.iban".to_string(),
display_name: "iban".to_string(),
field_type: enums::FieldType::UserIban,
value: None,
@@ -11558,9 +11558,9 @@ impl Default for super::settings::RequiredFields {
}
),
(
- "payment_method_data.bank_debit.sepa.iban".to_string(),
+ "payment_method_data.bank_debit.sepa_bank_debit.iban".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.bank_debit.sepa.iban".to_string(),
+ required_field: "payment_method_data.bank_debit.sepa_bank_debit.iban".to_string(),
display_name: "iban".to_string(),
field_type: enums::FieldType::UserIban,
value: None,
@@ -11601,9 +11601,9 @@ impl Default for super::settings::RequiredFields {
}
),
(
- "payment_method_data.bank_debit.sepa.iban".to_string(),
+ "payment_method_data.bank_debit.sepa_bank_debit.iban".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.bank_debit.sepa.iban".to_string(),
+ required_field: "payment_method_data.bank_debit.sepa_bank_debit.iban".to_string(),
display_name: "iban".to_string(),
field_type: enums::FieldType::UserIban,
value: None,
|
refactor
|
rename sepa in dynamic fields (#6234)
|
9d6e1c0a5d012d39f1b2b9585b41e1f94894df21
|
2023-02-24 18:15:24
|
Arjun Karthik
|
docs(api_models): fix typo (#634)
| false
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index a06d6420103..142bef10b42 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -18,7 +18,7 @@ pub enum PaymentOp {
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct PaymentsRequest {
- /// Unique identifier for the payment. This ensures impotency for multiple payments
+ /// Unique identifier for the payment. This ensures idempotency for multiple payments
/// that have been done by a single merchant. This field is auto generated and is returned in the API response.
#[schema(
value_type = Option<String>,
@@ -574,7 +574,7 @@ pub struct NextAction {
#[derive(Setter, Clone, Default, Debug, Eq, PartialEq, serde::Serialize, ToSchema)]
pub struct PaymentsResponse {
- /// Unique identifier for the payment. This ensures impotency for multiple payments
+ /// Unique identifier for the payment. This ensures idempotency for multiple payments
/// that have been done by a single merchant.
#[schema(
min_length = 30,
@@ -1221,7 +1221,7 @@ pub struct PaymentsCancelRequest {
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct PaymentsStartRequest {
- /// Unique identifier for the payment. This ensures impotency for multiple payments
+ /// Unique identifier for the payment. This ensures idempotency for multiple payments
/// that have been done by a single merchant. This field is auto generated and is returned in the API response.
pub payment_id: String,
/// The identifier for the Merchant Account.
diff --git a/openapi/generated.json b/openapi/generated.json
index ad3192abbc4..e94630c1e4c 100644
--- a/openapi/generated.json
+++ b/openapi/generated.json
@@ -4149,7 +4149,7 @@
"properties": {
"payment_id": {
"type": "string",
- "description": "Unique identifier for the payment. This ensures impotency for multiple payments\nthat have been done by a single merchant. This field is auto generated and is returned in the API response.",
+ "description": "Unique identifier for the payment. This ensures idempotency for multiple payments\nthat have been done by a single merchant. This field is auto generated and is returned in the API response.",
"example": "pay_mbabizu24mvu3mela5njyhpit4",
"maxLength": 30,
"minLength": 30
@@ -4316,7 +4316,7 @@
"properties": {
"payment_id": {
"type": "string",
- "description": "Unique identifier for the payment. This ensures impotency for multiple payments\nthat have been done by a single merchant.",
+ "description": "Unique identifier for the payment. This ensures idempotency for multiple payments\nthat have been done by a single merchant.",
"example": "pay_mbabizu24mvu3mela5njyhpit4",
"maxLength": 30,
"minLength": 30
@@ -4575,7 +4575,7 @@
"properties": {
"payment_id": {
"type": "string",
- "description": "Unique identifier for the payment. This ensures impotency for multiple payments\nthat have been done by a single merchant. This field is auto generated and is returned in the API response."
+ "description": "Unique identifier for the payment. This ensures idempotency for multiple payments\nthat have been done by a single merchant. This field is auto generated and is returned in the API response."
},
"merchant_id": {
"type": "string",
|
docs
|
fix typo (#634)
|
70eb2940ecef503cbf9a898d0f8382f9abe83057
|
2024-04-04 05:34:15
|
github-actions
|
chore(postman): update Postman collection files
| false
|
diff --git a/postman/collection-json/airwallex.postman_collection.json b/postman/collection-json/airwallex.postman_collection.json
index 3e30cc02a57..3e6b467f9bd 100644
--- a/postman/collection-json/airwallex.postman_collection.json
+++ b/postman/collection-json/airwallex.postman_collection.json
@@ -7319,4 +7319,4 @@
"type": "string"
}
]
-}
\ No newline at end of file
+}
diff --git a/postman/collection-json/bambora_3ds.postman_collection.json b/postman/collection-json/bambora_3ds.postman_collection.json
index d4857bead1f..f8f34a9ece4 100644
--- a/postman/collection-json/bambora_3ds.postman_collection.json
+++ b/postman/collection-json/bambora_3ds.postman_collection.json
@@ -1613,4 +1613,4 @@
"type": "string"
}
]
-}
\ No newline at end of file
+}
diff --git a/postman/collection-json/bluesnap.postman_collection.json b/postman/collection-json/bluesnap.postman_collection.json
index eb6e2079621..d1188336c11 100644
--- a/postman/collection-json/bluesnap.postman_collection.json
+++ b/postman/collection-json/bluesnap.postman_collection.json
@@ -11602,4 +11602,4 @@
"type": "string"
}
]
-}
\ No newline at end of file
+}
diff --git a/postman/collection-json/multisafepay.postman_collection.json b/postman/collection-json/multisafepay.postman_collection.json
index 245c68bf17a..fe8efb5ad0f 100644
--- a/postman/collection-json/multisafepay.postman_collection.json
+++ b/postman/collection-json/multisafepay.postman_collection.json
@@ -3762,4 +3762,4 @@
"type": "string"
}
]
-}
\ No newline at end of file
+}
diff --git a/postman/collection-json/nexinets.postman_collection.json b/postman/collection-json/nexinets.postman_collection.json
index deb5494d6de..5bbdf1a0df3 100644
--- a/postman/collection-json/nexinets.postman_collection.json
+++ b/postman/collection-json/nexinets.postman_collection.json
@@ -8526,4 +8526,4 @@
"type": "string"
}
]
-}
\ No newline at end of file
+}
diff --git a/postman/collection-json/rapyd.postman_collection.json b/postman/collection-json/rapyd.postman_collection.json
index db62ccaef15..a5af6de62e8 100644
--- a/postman/collection-json/rapyd.postman_collection.json
+++ b/postman/collection-json/rapyd.postman_collection.json
@@ -4315,4 +4315,4 @@
"type": "string"
}
]
-}
\ No newline at end of file
+}
diff --git a/postman/collection-json/shift4.postman_collection.json b/postman/collection-json/shift4.postman_collection.json
index ba7a905a514..7432bbf32ac 100644
--- a/postman/collection-json/shift4.postman_collection.json
+++ b/postman/collection-json/shift4.postman_collection.json
@@ -8976,4 +8976,4 @@
"type": "string"
}
]
-}
\ No newline at end of file
+}
diff --git a/postman/collection-json/trustpay.postman_collection.json b/postman/collection-json/trustpay.postman_collection.json
index 1b0536e1022..a9051b994ca 100644
--- a/postman/collection-json/trustpay.postman_collection.json
+++ b/postman/collection-json/trustpay.postman_collection.json
@@ -6410,4 +6410,4 @@
"type": "string"
}
]
-}
\ No newline at end of file
+}
|
chore
|
update Postman collection files
|
9bcffa6436e6b9207b1711768737a13783a2e907
|
2025-03-04 05:57:53
|
github-actions
|
chore(version): 2025.03.04.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 97a17ab26eb..bfcca5e604d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,35 @@
All notable changes to HyperSwitch will be documented here.
+- - -
+
+## 2025.03.04.0
+
+### Features
+
+- **connector:**
+ - Introduce `feature_matrix` api to coinbase, iatapay, nexixpay and square ([#7339](https://github.com/juspay/hyperswitch/pull/7339)) ([`c56f571`](https://github.com/juspay/hyperswitch/commit/c56f5719a1e088cbc0003168ec9b6198dde52a29))
+ - Add template code for stripebilling ([#7228](https://github.com/juspay/hyperswitch/pull/7228)) ([`af8778e`](https://github.com/juspay/hyperswitch/commit/af8778e0091fb4dd92bac55c3972c1ca99303aff))
+- **router:** Add support for retries with clear pan and network token payment method data ([#6905](https://github.com/juspay/hyperswitch/pull/6905)) ([`44eec7a`](https://github.com/juspay/hyperswitch/commit/44eec7a9946f123293a6c7e046ba9eee42334aa0))
+
+### Bug Fixes
+
+- **connector:**
+ - GooglePay fixed in Ayden ([#7393](https://github.com/juspay/hyperswitch/pull/7393)) ([`96a11ac`](https://github.com/juspay/hyperswitch/commit/96a11ac1c963d850e40fce1ed76684e72e2b884d))
+ - [BITPAY] Fixed Currency Conversion ([#7378](https://github.com/juspay/hyperswitch/pull/7378)) ([`5d24286`](https://github.com/juspay/hyperswitch/commit/5d24286101c7b32d36904a89cdd5eb2c5abd990c))
+ - [CASHTOCODE] Populate error reason ([#7154](https://github.com/juspay/hyperswitch/pull/7154)) ([`f8cd2f2`](https://github.com/juspay/hyperswitch/commit/f8cd2f25972ac41c32780c383b42eca3121735e1))
+
+### Refactors
+
+- **relay:** Add trait based implementation for relay ([#7264](https://github.com/juspay/hyperswitch/pull/7264)) ([`cdfbb82`](https://github.com/juspay/hyperswitch/commit/cdfbb82ffa893d65d1707d6795f07c0a71e8d0a9))
+
+### Miscellaneous Tasks
+
+- **docker:** Prefix Hyperswitch Docker image URIs with `docker.juspay.io` ([#7368](https://github.com/juspay/hyperswitch/pull/7368)) ([`e6d626d`](https://github.com/juspay/hyperswitch/commit/e6d626d334467df8cbf36266554b89adde12daea))
+
+**Full Changelog:** [`2025.02.28.0...2025.03.04.0`](https://github.com/juspay/hyperswitch/compare/2025.02.28.0...2025.03.04.0)
+
+
- - -
## 2025.02.28.0
|
chore
|
2025.03.04.0
|
7d43c5a7367ed9f85b98ae39856e361c1f2ecda4
|
2024-01-08 19:51:15
|
likhinbopanna
|
ci(postman): Adyen assertion fix for expired card test case (#3279)
| false
|
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid Exp month)/event.test.js b/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid Exp month)/event.test.js
index 93bd98b4ccb..1e8dabda827 100644
--- a/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid Exp month)/event.test.js
+++ b/postman/collection-dir/adyen_uk/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid Exp month)/event.test.js
@@ -75,12 +75,12 @@ if (jsonData?.error?.type) {
);
}
-// Response body should have value "invalid_request" for "error type"
-if (jsonData?.error?.message) {
+// Response body should have value "connector error" for "error type"
+if (jsonData?.error?.type) {
pm.test(
- "[POST]::/payments - Content check if value for 'error.message' matches 'Card Expired'",
+ "[POST]::/payments - Content check if value for 'error.type' matches 'invalid_request'",
function () {
- pm.expect(jsonData.error.message).to.eql("Card Expired");
+ pm.expect(jsonData.error.type).to.eql("invalid_request");
},
);
}
|
ci
|
Adyen assertion fix for expired card test case (#3279)
|
dcfa7b0846f562c033cc1ff6a10849aa34973496
|
2023-01-20 13:44:08
|
Kartikeya Hegde
|
fix(refund): add error code in refund table (#427)
| false
|
diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs
index b78d1521f8b..ffa1c781a85 100644
--- a/crates/api_models/src/refunds.rs
+++ b/crates/api_models/src/refunds.rs
@@ -76,6 +76,7 @@ pub struct RefundResponse {
#[schema(value_type = Option<Object>)]
pub metadata: Option<serde_json::Value>,
pub error_message: Option<String>,
+ pub error_code: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub created_at: Option<PrimitiveDateTime>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 536c51cb3f1..b1face64dde 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -145,6 +145,7 @@ pub async fn trigger_refund_to_gateway(
Err(err) => storage::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::Failure),
refund_error_message: Some(err.message),
+ refund_error_code: Some(err.code),
},
Ok(response) => storage::RefundUpdate::Update {
connector_refund_id: response.connector_refund_id,
@@ -292,6 +293,7 @@ pub async fn sync_refund_with_gateway(
Err(error_message) => storage::RefundUpdate::ErrorUpdate {
refund_status: None,
refund_error_message: Some(error_message.message),
+ refund_error_code: Some(error_message.code),
},
Ok(response) => storage::RefundUpdate::Update {
connector_refund_id: response.connector_refund_id,
@@ -538,6 +540,7 @@ impl From<Foreign<storage::Refund>> for Foreign<api::RefundResponse> {
status: refund.refund_status.foreign_into(),
metadata: refund.metadata,
error_message: refund.refund_error_message,
+ error_code: refund.refund_error_code,
created_at: Some(refund.created_at),
updated_at: Some(refund.updated_at),
}
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index 4615f601374..958adf728b7 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -286,7 +286,8 @@ mod storage {
refund_amount: new.refund_amount,
refund_status: new.refund_status,
sent_to_gateway: new.sent_to_gateway,
- refund_error_message: new.refund_error_message.clone(),
+ refund_error_message: None,
+ refund_error_code: None,
metadata: new.metadata.clone(),
refund_arn: new.refund_arn.clone(),
created_at: new.created_at.unwrap_or_else(date_time::now),
@@ -637,7 +638,8 @@ impl RefundInterface for MockDb {
refund_amount: new.refund_amount,
refund_status: new.refund_status,
sent_to_gateway: new.sent_to_gateway,
- refund_error_message: new.refund_error_message,
+ refund_error_message: None,
+ refund_error_code: None,
metadata: new.metadata,
refund_arn: new.refund_arn.clone(),
created_at: new.created_at.unwrap_or(current_time),
diff --git a/crates/storage_models/src/refund.rs b/crates/storage_models/src/refund.rs
index dc2636bc4b7..e451acd1314 100644
--- a/crates/storage_models/src/refund.rs
+++ b/crates/storage_models/src/refund.rs
@@ -25,6 +25,7 @@ pub struct Refund {
pub refund_status: storage_enums::RefundStatus,
pub sent_to_gateway: bool,
pub refund_error_message: Option<String>,
+ pub refund_error_code: Option<String>,
pub metadata: Option<serde_json::Value>,
pub refund_arn: Option<String>,
pub created_at: PrimitiveDateTime,
@@ -62,7 +63,6 @@ pub struct RefundNew {
pub refund_amount: i64,
pub refund_status: storage_enums::RefundStatus,
pub sent_to_gateway: bool,
- pub refund_error_message: Option<String>,
pub metadata: Option<serde_json::Value>,
pub refund_arn: Option<String>,
pub created_at: Option<PrimitiveDateTime>,
@@ -93,6 +93,7 @@ pub enum RefundUpdate {
ErrorUpdate {
refund_status: Option<storage_enums::RefundStatus>,
refund_error_message: Option<String>,
+ refund_error_code: Option<String>,
},
}
@@ -103,6 +104,7 @@ pub struct RefundUpdateInternal {
refund_status: Option<storage_enums::RefundStatus>,
sent_to_gateway: Option<bool>,
refund_error_message: Option<String>,
+ refund_error_code: Option<String>,
refund_arn: Option<String>,
metadata: Option<serde_json::Value>,
refund_reason: Option<String>,
@@ -143,9 +145,11 @@ impl From<RefundUpdate> for RefundUpdateInternal {
RefundUpdate::ErrorUpdate {
refund_status,
refund_error_message,
+ refund_error_code,
} => Self {
refund_status,
refund_error_message,
+ refund_error_code,
..Default::default()
},
}
@@ -160,6 +164,7 @@ impl RefundUpdate {
refund_status: pa_update.refund_status.unwrap_or(source.refund_status),
sent_to_gateway: pa_update.sent_to_gateway.unwrap_or(source.sent_to_gateway),
refund_error_message: pa_update.refund_error_message,
+ refund_error_code: pa_update.refund_error_code,
refund_arn: pa_update.refund_arn,
metadata: pa_update.metadata,
..source
diff --git a/crates/storage_models/src/schema.rs b/crates/storage_models/src/schema.rs
index c4d6a143eb2..7e0929cb51a 100644
--- a/crates/storage_models/src/schema.rs
+++ b/crates/storage_models/src/schema.rs
@@ -322,6 +322,7 @@ diesel::table! {
refund_status -> RefundStatus,
sent_to_gateway -> Bool,
refund_error_message -> Nullable<Text>,
+ refund_error_code -> Nullable<Varchar>,
metadata -> Nullable<Json>,
refund_arn -> Nullable<Varchar>,
created_at -> Timestamp,
diff --git a/migrations/2023-01-19-122511_add_refund_error_code/down.sql b/migrations/2023-01-19-122511_add_refund_error_code/down.sql
new file mode 100644
index 00000000000..0c314ba081f
--- /dev/null
+++ b/migrations/2023-01-19-122511_add_refund_error_code/down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE refund
+DROP COLUMN IF EXISTS refund_error_code;
diff --git a/migrations/2023-01-19-122511_add_refund_error_code/up.sql b/migrations/2023-01-19-122511_add_refund_error_code/up.sql
new file mode 100644
index 00000000000..1f3c792947a
--- /dev/null
+++ b/migrations/2023-01-19-122511_add_refund_error_code/up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE refund
+ADD IF NOT EXISTS refund_error_code TEXT DEFAULT NULL;
|
fix
|
add error code in refund table (#427)
|
b3d5d3b3dcdde7480df8493714986b5e737e97e0
|
2023-09-18 14:14:28
|
ItsMeShashank
|
refactor(router): use billing address for payment method list filters as opposed to shipping address (#2176)
| false
|
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index d74a3320568..83d2fd13617 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -888,7 +888,7 @@ pub async fn list_payment_methods(
&mut response,
payment_intent.as_ref(),
payment_attempt.as_ref(),
- shipping_address.as_ref(),
+ billing_address.as_ref(),
mca.connector_name,
pm_config_mapping,
&state.conf.mandates.supported_payment_methods,
|
refactor
|
use billing address for payment method list filters as opposed to shipping address (#2176)
|
bf06a5b51161365af7a3570a986455fefdf2c61b
|
2024-05-14 18:15:42
|
Sai Harsha Vardhan
|
feat(router): send `openurl_if_required` post_message in external 3ds flow for return_url redirection from sdk (#4642)
| false
|
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index ae6dc0e86f9..6f0d0998968 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -1168,7 +1168,7 @@ pub fn get_html_redirect_response_for_external_authentication(
try {{
// if inside iframe, send post message to parent for redirection
if (window.self !== window.parent) {{
- window.top.postMessage({{openurl: return_url}}, '*')
+ window.top.postMessage({{openurl_if_required: return_url}}, '*')
// if parent, redirect self to return_url
}} else {{
window.location.href = return_url
@@ -1176,7 +1176,7 @@ pub fn get_html_redirect_response_for_external_authentication(
}}
catch(err) {{
// if error occurs, send post message to parent and wait for 10 secs to redirect. if doesn't redirect, redirect self to return_url
- window.top.postMessage({{openurl: return_url}}, '*')
+ window.top.postMessage({{openurl_if_required: return_url}}, '*')
setTimeout(function() {{
window.location.href = return_url
}}, 10000);
|
feat
|
send `openurl_if_required` post_message in external 3ds flow for return_url redirection from sdk (#4642)
|
fb254b8924808e6a2b2a9a31dbed78749836e8d3
|
2024-02-16 15:41:44
|
Narayan Bhat
|
refactor(openapi): enable other features in api_models when running openapi (#3649)
| false
|
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml
index 1e8e0f47eb9..03370e5e990 100644
--- a/crates/api_models/Cargo.toml
+++ b/crates/api_models/Cargo.toml
@@ -19,7 +19,7 @@ detailed_errors = []
payouts = []
frm = []
olap = []
-openapi = ["common_enums/openapi"]
+openapi = ["common_enums/openapi", "olap", "backwards_compatibility", "business_profile_routing", "connector_choice_mca_id", "recon", "dummy_connector", "olap"]
recon = []
[dependencies]
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 2f3dfa82831..7f724729d90 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -17,11 +17,10 @@ email = ["external_services/email", "olap"]
frm = []
stripe = ["dep:serde_qs"]
release = ["aws_kms", "stripe", "aws_s3", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon"]
-olap = ["data_models/olap", "storage_impl/olap", "scheduler/olap","api_models/olap","dep:analytics"]
+olap = ["data_models/olap", "storage_impl/olap", "scheduler/olap", "api_models/olap", "dep:analytics"]
oltp = ["storage_impl/oltp"]
kv_store = ["scheduler/kv_store"]
accounts_cache = []
-openapi = ["olap", "oltp", "payouts", "dep:openapi"]
vergen = ["router_env/vergen"]
backwards_compatibility = ["api_models/backwards_compatibility"]
business_profile_routing = ["api_models/business_profile_routing"]
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 06c1a8d8063..eda3747b940 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -6607,6 +6607,13 @@
"type": "string",
"description": "A connector is an integration to fulfill payments",
"enum": [
+ "phonypay",
+ "fauxpay",
+ "pretendpay",
+ "stripe_test",
+ "adyen_test",
+ "checkout_test",
+ "paypal_test",
"aci",
"adyen",
"airwallex",
@@ -10300,6 +10307,7 @@
"description": "Routing Algorithm specific to merchants",
"required": [
"id",
+ "profile_id",
"name",
"description",
"algorithm",
@@ -10310,6 +10318,9 @@
"id": {
"type": "string"
},
+ "profile_id": {
+ "type": "string"
+ },
"name": {
"type": "string"
},
@@ -15446,7 +15457,7 @@
"connector": {
"$ref": "#/components/schemas/RoutableConnectors"
},
- "sub_label": {
+ "merchant_connector_id": {
"type": "string",
"nullable": true
}
@@ -15456,6 +15467,13 @@
"type": "string",
"description": "Connectors eligible for payments routing",
"enum": [
+ "phonypay",
+ "fauxpay",
+ "pretendpay",
+ "stripe_test",
+ "adyen_test",
+ "checkout_test",
+ "paypal_test",
"aci",
"adyen",
"airwallex",
@@ -15655,6 +15673,7 @@
"type": "object",
"required": [
"id",
+ "profile_id",
"name",
"kind",
"description",
@@ -15665,6 +15684,9 @@
"id": {
"type": "string"
},
+ "profile_id": {
+ "type": "string"
+ },
"name": {
"type": "string"
},
|
refactor
|
enable other features in api_models when running openapi (#3649)
|
9a4b1d023eac97d664aac0497264bcf19fdeec86
|
2022-12-19 19:33:52
|
Sanchith Hegde
|
ci: temporarily disable path-based filtering (#177)
| false
|
diff --git a/.github/workflows/CI-skip-ignored-files.yml b/.github/workflows/CI-skip-ignored-files.yml
deleted file mode 100644
index 0e803549bb5..00000000000
--- a/.github/workflows/CI-skip-ignored-files.yml
+++ /dev/null
@@ -1,77 +0,0 @@
-# Skip CI checks on ignored files in CI workflow
-# Reference: https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/defining-the-mergeability-of-pull-requests/troubleshooting-required-status-checks#handling-skipped-but-required-checks
-name: CI
-
-on:
- push:
- branches:
- - main
- paths-ignore:
- - ".github/workflows/**"
- - "crates/**"
- - "examples/**"
- - "Cargo.lock"
- - "Cargo.toml"
-
- pull_request:
- types:
- - "labeled"
- - "opened"
- - "ready_for_review"
- - "reopened"
- - "synchronize"
- paths-ignore:
- - ".github/workflows/**"
- - "crates/**"
- - "examples/**"
- - "Cargo.lock"
- - "Cargo.toml"
-
-concurrency:
- group: ${{ github.workflow }}-${{ github.ref }}
- cancel-in-progress: true
-
-jobs:
- formatting:
- name: Check formatting
- if: ${{ github.ref == 'refs/heads/main' || contains(github.event.pull_request.labels.*.name, 'S-awaiting-merge') }}
- runs-on: ubuntu-latest
- steps:
- - name: Skip formatting
- shell: bash
- run: 'echo "Skipping formatting check"'
-
- check-msrv:
- name: Check compilation on MSRV toolchain
- if: ${{ github.ref == 'refs/heads/main' || contains(github.event.pull_request.labels.*.name, 'S-awaiting-merge') }}
- runs-on: ${{ matrix.os }}
- strategy:
- matrix:
- os:
- - ubuntu-latest
- steps:
- - name: Skip compilation checks
- shell: bash
- run: 'echo "Skipping MSRV compilation checks"'
-
- # cargo-deny:
- # name: Run cargo-deny
- # if: ${{ github.ref == 'refs/heads/main' || contains(github.event.pull_request.labels.*.name, 'S-awaiting-merge') }}
- # runs-on: ubuntu-latest
- # steps:
- # - name: Skip cargo-deny
- # shell: bash
- # run: 'echo "Skipping cargo-deny checks"'
-
- test:
- name: Run tests on stable toolchain
- if: ${{ github.ref == 'refs/heads/main' || contains(github.event.pull_request.labels.*.name, 'S-awaiting-merge') }}
- runs-on: ${{ matrix.os }}
- strategy:
- matrix:
- os:
- - ubuntu-latest
- steps:
- - name: Skip compilation checks
- shell: bash
- run: 'echo "Skipping stable toolchain compilation checks"'
diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml
index 84727fe76b5..2924edc4178 100644
--- a/.github/workflows/CI.yml
+++ b/.github/workflows/CI.yml
@@ -4,12 +4,12 @@ on:
push:
branches:
- main
- paths:
- - ".github/workflows/**"
- - "crates/**"
- - "examples/**"
- - "Cargo.lock"
- - "Cargo.toml"
+ # paths:
+ # - ".github/workflows/**"
+ # - "crates/**"
+ # - "examples/**"
+ # - "Cargo.lock"
+ # - "Cargo.toml"
pull_request:
types:
@@ -18,12 +18,12 @@ on:
- "ready_for_review"
- "reopened"
- "synchronize"
- paths:
- - ".github/workflows/**"
- - "crates/**"
- - "examples/**"
- - "Cargo.lock"
- - "Cargo.toml"
+ # paths:
+ # - ".github/workflows/**"
+ # - "crates/**"
+ # - "examples/**"
+ # - "Cargo.lock"
+ # - "Cargo.toml"
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
|
ci
|
temporarily disable path-based filtering (#177)
|
4728d946e24c2c548e7cdc23c34238ff028f1076
|
2023-05-03 02:25:53
|
Sai Harsha Vardhan
|
feat(router): added support for optional defend dispute api call and added evidence submission flow for checkout connector (#979)
| false
|
diff --git a/crates/api_models/src/disputes.rs b/crates/api_models/src/disputes.rs
index 8dc56fba940..a8d10e01f6a 100644
--- a/crates/api_models/src/disputes.rs
+++ b/crates/api_models/src/disputes.rs
@@ -122,6 +122,10 @@ pub struct SubmitEvidenceRequest {
pub shipping_documentation: Option<String>,
/// Tracking number of shipped product
pub shipping_tracking_number: Option<String>,
+ /// File Id showing two distinct transactions when customer claims a payment was charged twice
+ pub invoice_showing_distinct_transactions: Option<String>,
+ /// File Id of recurring transaction agreement
+ pub recurring_transaction_agreement: Option<String>,
/// Any additional supporting file
pub uncategorized_file: Option<String>,
/// Any additional evidence statements
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 229c034f46d..ac615d7a4f0 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -627,7 +627,10 @@ impl Connector {
)
}
pub fn supports_file_storage_module(&self) -> bool {
- matches!(self, Self::Stripe)
+ matches!(self, Self::Stripe | Self::Checkout)
+ }
+ pub fn requires_defend_dispute(&self) -> bool {
+ matches!(self, Self::Checkout)
}
}
diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs
index 25e4a6e14e8..9a651594f15 100644
--- a/crates/router/src/connector/checkout.rs
+++ b/crates/router/src/connector/checkout.rs
@@ -118,6 +118,7 @@ impl api::ConnectorAccessToken for Checkout {}
impl api::AcceptDispute for Checkout {}
impl api::PaymentToken for Checkout {}
impl api::Dispute for Checkout {}
+impl api::DefendDispute for Checkout {}
impl
ConnectorIntegration<
@@ -766,43 +767,12 @@ impl
&self,
res: types::Response,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- let response: checkout::ErrorResponse = if res.response.is_empty() {
- checkout::ErrorResponse {
- request_id: None,
- error_type: if res.status_code == 401 {
- Some("Invalid Api Key".to_owned())
- } else {
- None
- },
- error_codes: None,
- }
- } else {
- res.response
- .parse_struct("ErrorResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?
- };
-
- Ok(types::ErrorResponse {
- status_code: res.status_code,
- code: response
- .error_codes
- .unwrap_or_else(|| vec![consts::NO_ERROR_CODE.to_string()])
- .join(" & "),
- message: response
- .error_type
- .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
- reason: None,
- })
+ self.build_error_response(res)
}
}
impl api::UploadFile for Checkout {}
-impl ConnectorIntegration<api::Upload, types::UploadFileRequestData, types::UploadFileResponse>
- for Checkout
-{
-}
-
#[async_trait::async_trait]
impl api::FileUpload for Checkout {
fn validate_file_upload(
@@ -832,6 +802,240 @@ impl api::FileUpload for Checkout {
}
}
+impl ConnectorIntegration<api::Upload, types::UploadFileRequestData, types::UploadFileResponse>
+ for Checkout
+{
+ fn get_headers(
+ &self,
+ req: &types::RouterData<
+ api::Upload,
+ types::UploadFileRequestData,
+ types::UploadFileResponse,
+ >,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.get_auth_header(&req.connector_auth_type)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ "multipart/form-data"
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::UploadFileRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!("{}{}", self.base_url(connectors), "files"))
+ }
+
+ fn get_request_form_data(
+ &self,
+ req: &types::UploadFileRouterData,
+ ) -> CustomResult<Option<reqwest::multipart::Form>, errors::ConnectorError> {
+ let checkout_req = transformers::construct_file_upload_request(req.clone())?;
+ Ok(Some(checkout_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::UploadFileRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::UploadFileType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::UploadFileType::get_headers(self, req, connectors)?)
+ .form_data(types::UploadFileType::get_request_form_data(self, req)?)
+ .content_type(services::request::ContentType::FormData)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::UploadFileRouterData,
+ res: types::Response,
+ ) -> CustomResult<
+ types::RouterData<api::Upload, types::UploadFileRequestData, types::UploadFileResponse>,
+ errors::ConnectorError,
+ > {
+ let response: checkout::FileUploadResponse = res
+ .response
+ .parse_struct("Checkout FileUploadResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ Ok(types::UploadFileRouterData {
+ response: Ok(types::UploadFileResponse {
+ provider_file_id: response.file_id,
+ }),
+ ..data.clone()
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: types::Response,
+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl api::SubmitEvidence for Checkout {}
+
+impl
+ ConnectorIntegration<
+ api::Evidence,
+ types::SubmitEvidenceRequestData,
+ types::SubmitEvidenceResponse,
+ > for Checkout
+{
+ fn get_headers(
+ &self,
+ req: &types::SubmitEvidenceRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ let mut header = vec![(
+ headers::CONTENT_TYPE.to_string(),
+ types::SubmitEvidenceType::get_content_type(self).to_string(),
+ )];
+ let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
+ header.append(&mut api_key);
+ Ok(header)
+ }
+
+ fn get_url(
+ &self,
+ req: &types::SubmitEvidenceRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}disputes/{}/evidence",
+ self.base_url(connectors),
+ req.request.connector_dispute_id,
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::SubmitEvidenceRouterData,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let checkout_req = checkout::Evidence::try_from(req)?;
+ let checkout_req_string =
+ utils::Encode::<checkout::Evidence>::encode_to_string_of_json(&checkout_req)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(checkout_req_string))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::SubmitEvidenceRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Put)
+ .url(&types::SubmitEvidenceType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::SubmitEvidenceType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::SubmitEvidenceType::get_request_body(self, req)?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::SubmitEvidenceRouterData,
+ _res: types::Response,
+ ) -> CustomResult<types::SubmitEvidenceRouterData, errors::ConnectorError> {
+ Ok(types::SubmitEvidenceRouterData {
+ response: Ok(types::SubmitEvidenceResponse {
+ dispute_status: api_models::enums::DisputeStatus::DisputeChallenged,
+ connector_status: None,
+ }),
+ ..data.clone()
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: types::Response,
+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl
+ ConnectorIntegration<api::Defend, types::DefendDisputeRequestData, types::DefendDisputeResponse>
+ for Checkout
+{
+ fn get_headers(
+ &self,
+ req: &types::DefendDisputeRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ let mut header = vec![(
+ headers::CONTENT_TYPE.to_string(),
+ types::DefendDisputeType::get_content_type(self).to_string(),
+ )];
+ let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
+ header.append(&mut api_key);
+ Ok(header)
+ }
+
+ fn get_url(
+ &self,
+ req: &types::DefendDisputeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}disputes/{}/evidence",
+ self.base_url(connectors),
+ req.request.connector_dispute_id,
+ ))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::DefendDisputeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::DefendDisputeType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::DefendDisputeType::get_headers(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::DefendDisputeRouterData,
+ _res: types::Response,
+ ) -> CustomResult<types::DefendDisputeRouterData, errors::ConnectorError> {
+ Ok(types::DefendDisputeRouterData {
+ response: Ok(types::DefendDisputeResponse {
+ dispute_status: api::enums::DisputeStatus::DisputeChallenged,
+ connector_status: None,
+ }),
+ ..data.clone()
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: types::Response,
+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
#[async_trait::async_trait]
impl api::IncomingWebhook for Checkout {
fn get_webhook_source_verification_algorithm(
diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs
index 1de1256d7ee..fe309f250d9 100644
--- a/crates/router/src/connector/checkout/transformers.rs
+++ b/crates/router/src/connector/checkout/transformers.rs
@@ -1,4 +1,5 @@
-use error_stack::IntoReport;
+use common_utils::errors::CustomResult;
+use error_stack::{IntoReport, ResultExt};
use serde::{Deserialize, Serialize};
use url::Url;
@@ -775,3 +776,67 @@ impl From<CheckoutTxnType> for api_models::enums::DisputeStage {
pub struct CheckoutWebhookObjectResource {
pub data: serde_json::Value,
}
+
+pub fn construct_file_upload_request(
+ file_upload_router_data: types::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
+ .to_string()
+ .split('/')
+ .last()
+ .unwrap_or_default()
+ ))
+ .mime_str(request.file_type.as_ref())
+ .into_report()
+ .change_context(errors::ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failure in constructing file data")?;
+ multipart = multipart.part("file", file_data);
+ Ok(multipart)
+}
+
+#[derive(Debug, Deserialize)]
+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<&types::SubmitEvidenceRouterData> for Evidence {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::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,
+ })
+ }
+}
diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs
index dbdcb7cf485..ec76347ff71 100644
--- a/crates/router/src/connector/stripe.rs
+++ b/crates/router/src/connector/stripe.rs
@@ -1128,7 +1128,6 @@ impl
let stripe_req = stripe::Evidence::try_from(req)?;
let stripe_req_string = utils::Encode::<stripe::Evidence>::url_encode(&stripe_req)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
- print!("Stripe request: {:?}", stripe_req_string);
Ok(Some(stripe_req_string))
}
diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rs
index 4b7a0316346..613e7c91e13 100644
--- a/crates/router/src/core/disputes.rs
+++ b/crates/router/src/core/disputes.rs
@@ -15,8 +15,8 @@ use crate::{
api::{self, disputes},
storage::{self, enums as storage_enums},
transformers::{ForeignFrom, ForeignInto},
- AcceptDisputeRequestData, AcceptDisputeResponse, SubmitEvidenceRequestData,
- SubmitEvidenceResponse,
+ AcceptDisputeRequestData, AcceptDisputeResponse, DefendDisputeRequestData,
+ DefendDisputeResponse, SubmitEvidenceRequestData, SubmitEvidenceResponse,
},
};
@@ -245,12 +245,54 @@ pub async fn submit_evidence(
status_code: err.status_code,
reason: err.reason,
})?;
+ //Defend Dispute Optionally if connector expects to defend / submit evidence in a separate api call
+ let (dispute_status, connector_status) =
+ if connector_data.connector_name.requires_defend_dispute() {
+ let connector_integration_defend_dispute: services::BoxedConnectorIntegration<
+ '_,
+ api::Defend,
+ DefendDisputeRequestData,
+ DefendDisputeResponse,
+ > = connector_data.connector.get_connector_integration();
+ let defend_dispute_router_data = utils::construct_defend_dispute_router_data(
+ state,
+ &payment_intent,
+ &payment_attempt,
+ &merchant_account,
+ &dispute,
+ )
+ .await?;
+ let defend_response = services::execute_connector_processing_step(
+ state,
+ connector_integration_defend_dispute,
+ &defend_dispute_router_data,
+ payments::CallConnectorAction::Trigger,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while calling defend dispute connector api")?;
+ let defend_dispute_response = defend_response.response.map_err(|err| {
+ errors::ApiErrorResponse::ExternalConnectorError {
+ code: err.code,
+ message: err.message,
+ connector: dispute.connector.clone(),
+ status_code: err.status_code,
+ reason: err.reason,
+ }
+ })?;
+ (
+ defend_dispute_response.dispute_status,
+ defend_dispute_response.connector_status,
+ )
+ } else {
+ (
+ submit_evidence_response.dispute_status,
+ submit_evidence_response.connector_status,
+ )
+ };
let update_dispute = storage_models::dispute::DisputeUpdate::StatusUpdate {
- dispute_status: submit_evidence_response
- .dispute_status
- .clone()
- .foreign_into(),
- connector_status: submit_evidence_response.connector_status.clone(),
+ dispute_status: dispute_status.foreign_into(),
+ connector_status,
};
let updated_dispute = db
.update_dispute(dispute.clone(), update_dispute)
diff --git a/crates/router/src/core/disputes/transformers.rs b/crates/router/src/core/disputes/transformers.rs
index 9080941a3b5..63a3697413a 100644
--- a/crates/router/src/core/disputes/transformers.rs
+++ b/crates/router/src/core/disputes/transformers.rs
@@ -60,6 +60,22 @@ pub async fn get_evidence_request_data(
merchant_account,
)
.await?;
+ let (
+ invoice_showing_distinct_transactions,
+ invoice_showing_distinct_transactions_provider_file_id,
+ ) = retrieve_file_and_provider_file_id_from_file_id(
+ state,
+ evidence_request.invoice_showing_distinct_transactions,
+ merchant_account,
+ )
+ .await?;
+ let (recurring_transaction_agreement, recurring_transaction_agreement_provider_file_id) =
+ retrieve_file_and_provider_file_id_from_file_id(
+ state,
+ evidence_request.recurring_transaction_agreement,
+ merchant_account,
+ )
+ .await?;
let (uncategorized_file, uncategorized_file_provider_file_id) =
retrieve_file_and_provider_file_id_from_file_id(
state,
@@ -99,6 +115,10 @@ pub async fn get_evidence_request_data(
shipping_documentation,
shipping_documentation_provider_file_id,
shipping_tracking_number: evidence_request.shipping_tracking_number,
+ invoice_showing_distinct_transactions,
+ invoice_showing_distinct_transactions_provider_file_id,
+ recurring_transaction_agreement,
+ recurring_transaction_agreement_provider_file_id,
uncategorized_file,
uncategorized_file_provider_file_id,
uncategorized_text: evidence_request.uncategorized_text,
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index cb85ef82a2d..182ec6efe81 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -309,7 +309,6 @@ default_imp_for_submit_evidence!(
connector::Bambora,
connector::Bluesnap,
connector::Braintree,
- connector::Checkout,
connector::Cybersource,
connector::Coinbase,
connector::Dlocal,
@@ -332,3 +331,50 @@ default_imp_for_submit_evidence!(
connector::Worldpay,
connector::Zen
);
+
+macro_rules! default_imp_for_defend_dispute{
+ ($($path:ident::$connector:ident),*)=> {
+ $(
+ impl api::DefendDispute for $path::$connector {}
+ impl
+ services::ConnectorIntegration<
+ api::Defend,
+ types::DefendDisputeRequestData,
+ types::DefendDisputeResponse,
+ > for $path::$connector
+ {}
+ )*
+ };
+}
+
+default_imp_for_defend_dispute!(
+ connector::Aci,
+ connector::Adyen,
+ connector::Airwallex,
+ connector::Authorizedotnet,
+ connector::Bambora,
+ connector::Bluesnap,
+ connector::Braintree,
+ connector::Cybersource,
+ connector::Coinbase,
+ connector::Dlocal,
+ connector::Fiserv,
+ connector::Forte,
+ connector::Globalpay,
+ connector::Klarna,
+ connector::Mollie,
+ connector::Multisafepay,
+ connector::Nexinets,
+ connector::Nuvei,
+ connector::Payeezy,
+ connector::Paypal,
+ connector::Payu,
+ connector::Rapyd,
+ connector::Stripe,
+ connector::Shift4,
+ connector::Trustpay,
+ connector::Opennode,
+ connector::Worldline,
+ connector::Worldpay,
+ connector::Zen
+);
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index 98a899ce7fd..f2f06f07e67 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -13,6 +13,7 @@ use crate::{
types::{
self,
storage::{self, enums},
+ ErrorResponse,
},
utils::{generate_id, OptionExt, ValueExt},
};
@@ -400,3 +401,62 @@ pub async fn construct_upload_file_router_data<'a>(
};
Ok(router_data)
}
+
+#[instrument(skip_all)]
+pub async fn construct_defend_dispute_router_data<'a>(
+ state: &'a AppState,
+ payment_intent: &'a storage::PaymentIntent,
+ payment_attempt: &storage::PaymentAttempt,
+ merchant_account: &storage::MerchantAccount,
+ dispute: &storage::Dispute,
+) -> RouterResult<types::DefendDisputeRouterData> {
+ let db = &*state.store;
+ let connector_id = &dispute.connector;
+ let connector_label = helpers::get_connector_label(
+ payment_intent.business_country,
+ &payment_intent.business_label,
+ payment_attempt.business_sub_label.as_ref(),
+ connector_id,
+ );
+ let merchant_connector_account = helpers::get_merchant_connector_account(
+ db,
+ merchant_account.merchant_id.as_str(),
+ &connector_label,
+ None,
+ )
+ .await?;
+ let auth_type: types::ConnectorAuthType = merchant_connector_account
+ .get_connector_account_details()
+ .parse_value("ConnectorAuthType")
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ let payment_method = payment_attempt
+ .payment_method
+ .get_required_value("payment_method_type")?;
+ let router_data = types::RouterData {
+ flow: PhantomData,
+ merchant_id: merchant_account.merchant_id.clone(),
+ connector: connector_id.to_string(),
+ payment_id: payment_attempt.payment_id.clone(),
+ attempt_id: payment_attempt.attempt_id.clone(),
+ status: payment_attempt.status,
+ payment_method,
+ connector_auth_type: auth_type,
+ description: None,
+ return_url: payment_intent.return_url.clone(),
+ payment_method_id: payment_attempt.payment_method_id.clone(),
+ address: PaymentAddress::default(),
+ auth_type: payment_attempt.authentication_type.unwrap_or_default(),
+ connector_meta_data: merchant_connector_account.get_metadata(),
+ amount_captured: payment_intent.amount_captured,
+ request: types::DefendDisputeRequestData {
+ dispute_id: dispute.dispute_id.clone(),
+ connector_dispute_id: dispute.connector_dispute_id.clone(),
+ },
+ response: Err(ErrorResponse::get_not_implemented()),
+ access_token: None,
+ session_token: None,
+ reference_id: None,
+ payment_method_token: None,
+ };
+ Ok(router_data)
+}
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 2e08c680812..a18c07d9e97 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -120,6 +120,12 @@ pub type SubmitEvidenceType = dyn services::ConnectorIntegration<
pub type UploadFileType =
dyn services::ConnectorIntegration<api::Upload, UploadFileRequestData, UploadFileResponse>;
+pub type DefendDisputeType = dyn services::ConnectorIntegration<
+ api::Defend,
+ DefendDisputeRequestData,
+ DefendDisputeResponse,
+>;
+
pub type VerifyRouterData = RouterData<api::Verify, VerifyRequestData, PaymentsResponseData>;
pub type AcceptDisputeRouterData =
@@ -130,6 +136,9 @@ pub type SubmitEvidenceRouterData =
pub type UploadFileRouterData = RouterData<api::Upload, UploadFileRequestData, UploadFileResponse>;
+pub type DefendDisputeRouterData =
+ RouterData<api::Defend, DefendDisputeRequestData, DefendDisputeResponse>;
+
#[derive(Debug, Clone)]
pub struct RouterData<Flow, Request, Response> {
pub flow: PhantomData<Flow>,
@@ -425,6 +434,10 @@ pub struct SubmitEvidenceRequestData {
pub shipping_documentation: Option<Vec<u8>>,
pub shipping_documentation_provider_file_id: Option<String>,
pub shipping_tracking_number: Option<String>,
+ pub invoice_showing_distinct_transactions: Option<Vec<u8>>,
+ pub invoice_showing_distinct_transactions_provider_file_id: Option<String>,
+ pub recurring_transaction_agreement: Option<Vec<u8>>,
+ pub recurring_transaction_agreement_provider_file_id: Option<String>,
pub uncategorized_file: Option<Vec<u8>>,
pub uncategorized_file_provider_file_id: Option<String>,
pub uncategorized_text: Option<String>,
@@ -436,6 +449,18 @@ pub struct SubmitEvidenceResponse {
pub connector_status: Option<String>,
}
+#[derive(Default, Debug, Clone)]
+pub struct DefendDisputeRequestData {
+ pub dispute_id: String,
+ pub connector_dispute_id: String,
+}
+
+#[derive(Default, Debug, Clone)]
+pub struct DefendDisputeResponse {
+ pub dispute_status: api_models::enums::DisputeStatus,
+ pub connector_status: Option<String>,
+}
+
#[derive(Clone, Debug)]
pub struct UploadFileRequestData {
pub file_key: String,
diff --git a/crates/router/src/types/api/disputes.rs b/crates/router/src/types/api/disputes.rs
index 246c4b15cf6..9763fad8f3b 100644
--- a/crates/router/src/types/api/disputes.rs
+++ b/crates/router/src/types/api/disputes.rs
@@ -45,4 +45,16 @@ pub trait SubmitEvidence:
{
}
-pub trait Dispute: super::ConnectorCommon + AcceptDispute + SubmitEvidence {}
+#[derive(Debug, Clone)]
+pub struct Defend;
+
+pub trait DefendDispute:
+ services::ConnectorIntegration<
+ Defend,
+ types::DefendDisputeRequestData,
+ types::DefendDisputeResponse,
+>
+{
+}
+
+pub trait Dispute: super::ConnectorCommon + AcceptDispute + SubmitEvidence + DefendDispute {}
diff --git a/crates/router/src/types/api/files.rs b/crates/router/src/types/api/files.rs
index 1a61bad3f98..eaf4015ccda 100644
--- a/crates/router/src/types/api/files.rs
+++ b/crates/router/src/types/api/files.rs
@@ -12,13 +12,15 @@ pub struct FileId {
pub enum FileUploadProvider {
Router,
Stripe,
+ Checkout,
}
impl TryFrom<&types::Connector> for FileUploadProvider {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(item: &types::Connector) -> Result<Self, Self::Error> {
- match item {
- &types::Connector::Stripe => Ok(Self::Stripe),
+ match *item {
+ types::Connector::Stripe => Ok(Self::Stripe),
+ types::Connector::Checkout => Ok(Self::Checkout),
_ => Err(errors::ApiErrorResponse::NotSupported {
message: "Connector not supported as file provider".to_owned(),
}
diff --git a/crates/storage_models/src/enums.rs b/crates/storage_models/src/enums.rs
index 81165c789b8..bff7bbb5aa7 100644
--- a/crates/storage_models/src/enums.rs
+++ b/crates/storage_models/src/enums.rs
@@ -817,4 +817,5 @@ pub enum FileUploadProvider {
#[default]
Router,
Stripe,
+ Checkout,
}
|
feat
|
added support for optional defend dispute api call and added evidence submission flow for checkout connector (#979)
|
9683b2a8955f876d99625cd5cf70c4bdf3836e9e
|
2025-03-12 16:14:09
|
Sandeep Kumar
|
feat(analytics): modified authentication queries and added generate report for authentications (#7483)
| false
|
diff --git a/crates/analytics/src/auth_events/core.rs b/crates/analytics/src/auth_events/core.rs
index a2640be6ead..bdcbdd86a94 100644
--- a/crates/analytics/src/auth_events/core.rs
+++ b/crates/analytics/src/auth_events/core.rs
@@ -165,6 +165,7 @@ pub async fn get_filters(
.filter_map(|fil: AuthEventFilterRow| match dim {
AuthEventDimensions::AuthenticationStatus => fil.authentication_status.map(|i| i.as_ref().to_string()),
AuthEventDimensions::TransactionStatus => fil.trans_status.map(|i| i.as_ref().to_string()),
+ AuthEventDimensions::AuthenticationType => fil.authentication_type.map(|i| i.as_ref().to_string()),
AuthEventDimensions::ErrorMessage => fil.error_message,
AuthEventDimensions::AuthenticationConnector => fil.authentication_connector.map(|i| i.as_ref().to_string()),
AuthEventDimensions::MessageVersion => fil.message_version,
diff --git a/crates/analytics/src/auth_events/filters.rs b/crates/analytics/src/auth_events/filters.rs
index da8e0b7cfa3..5f65eeaa279 100644
--- a/crates/analytics/src/auth_events/filters.rs
+++ b/crates/analytics/src/auth_events/filters.rs
@@ -1,4 +1,5 @@
use api_models::analytics::{auth_events::AuthEventDimensions, Granularity, TimeRange};
+use common_enums::DecoupledAuthenticationType;
use common_utils::errors::ReportSwitchExt;
use diesel_models::enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus};
use error_stack::ResultExt;
@@ -54,6 +55,7 @@ where
pub struct AuthEventFilterRow {
pub authentication_status: Option<DBEnumWrapper<AuthenticationStatus>>,
pub trans_status: Option<DBEnumWrapper<TransactionStatus>>,
+ pub authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>>,
pub error_message: Option<String>,
pub authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>>,
pub message_version: Option<String>,
diff --git a/crates/analytics/src/auth_events/metrics.rs b/crates/analytics/src/auth_events/metrics.rs
index fd94aac614c..a3d0fe7b683 100644
--- a/crates/analytics/src/auth_events/metrics.rs
+++ b/crates/analytics/src/auth_events/metrics.rs
@@ -41,6 +41,7 @@ pub struct AuthEventMetricRow {
pub count: Option<i64>,
pub authentication_status: Option<DBEnumWrapper<storage_enums::AuthenticationStatus>>,
pub trans_status: Option<DBEnumWrapper<storage_enums::TransactionStatus>>,
+ pub authentication_type: Option<DBEnumWrapper<storage_enums::DecoupledAuthenticationType>>,
pub error_message: Option<String>,
pub authentication_connector: Option<DBEnumWrapper<storage_enums::AuthenticationConnectors>>,
pub message_version: Option<String>,
diff --git a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs
index 32c76385409..b82d1ef4c35 100644
--- a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs
+++ b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs
@@ -70,7 +70,10 @@ where
.switch()?;
query_builder
- .add_negative_filter_clause("authentication_status", AuthenticationStatus::Pending)
+ .add_filter_in_range_clause(
+ "authentication_status",
+ &[AuthenticationStatus::Success, AuthenticationStatus::Failed],
+ )
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
time_range
@@ -103,6 +106,7 @@ where
AuthEventMetricsBucketIdentifier::new(
i.authentication_status.as_ref().map(|i| i.0),
i.trans_status.as_ref().map(|i| i.0.clone()),
+ i.authentication_type.as_ref().map(|i| i.0),
i.error_message.clone(),
i.authentication_connector.as_ref().map(|i| i.0),
i.message_version.clone(),
diff --git a/crates/analytics/src/auth_events/metrics/authentication_count.rs b/crates/analytics/src/auth_events/metrics/authentication_count.rs
index 39df41f53aa..682e8a07f6b 100644
--- a/crates/analytics/src/auth_events/metrics/authentication_count.rs
+++ b/crates/analytics/src/auth_events/metrics/authentication_count.rs
@@ -96,6 +96,7 @@ where
AuthEventMetricsBucketIdentifier::new(
i.authentication_status.as_ref().map(|i| i.0),
i.trans_status.as_ref().map(|i| i.0.clone()),
+ i.authentication_type.as_ref().map(|i| i.0),
i.error_message.clone(),
i.authentication_connector.as_ref().map(|i| i.0),
i.message_version.clone(),
diff --git a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs
index cdb89b796dd..047511d477c 100644
--- a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs
+++ b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs
@@ -12,8 +12,8 @@ use time::PrimitiveDateTime;
use super::AuthEventMetricRow;
use crate::{
query::{
- Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql,
- Window,
+ Aggregate, FilterTypes, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket,
+ ToSql, Window,
},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
@@ -45,11 +45,9 @@ where
for dim in dimensions.iter() {
query_builder.add_select_column(dim).switch()?;
}
+
query_builder
- .add_select_column(Aggregate::Count {
- field: None,
- alias: Some("count"),
- })
+ .add_select_column("sum(sign_flag) AS count")
.switch()?;
query_builder
@@ -94,6 +92,11 @@ where
.switch()?;
}
+ query_builder
+ .add_order_by_clause("count", Order::Descending)
+ .attach_printable("Error adding order by clause")
+ .switch()?;
+
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
@@ -112,6 +115,7 @@ where
AuthEventMetricsBucketIdentifier::new(
i.authentication_status.as_ref().map(|i| i.0),
i.trans_status.as_ref().map(|i| i.0.clone()),
+ i.authentication_type.as_ref().map(|i| i.0),
i.error_message.clone(),
i.authentication_connector.as_ref().map(|i| i.0),
i.message_version.clone(),
diff --git a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs
index 37f9dfd1c1f..9342e9047e0 100644
--- a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs
+++ b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs
@@ -107,6 +107,7 @@ where
AuthEventMetricsBucketIdentifier::new(
i.authentication_status.as_ref().map(|i| i.0),
i.trans_status.as_ref().map(|i| i.0.clone()),
+ i.authentication_type.as_ref().map(|i| i.0),
i.error_message.clone(),
i.authentication_connector.as_ref().map(|i| i.0),
i.message_version.clone(),
diff --git a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs
index 039ef00dd6e..984350efe6b 100644
--- a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs
+++ b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs
@@ -101,6 +101,7 @@ where
AuthEventMetricsBucketIdentifier::new(
i.authentication_status.as_ref().map(|i| i.0),
i.trans_status.as_ref().map(|i| i.0.clone()),
+ i.authentication_type.as_ref().map(|i| i.0),
i.error_message.clone(),
i.authentication_connector.as_ref().map(|i| i.0),
i.message_version.clone(),
diff --git a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs
index beccc093b19..5a2a9400b20 100644
--- a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs
+++ b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs
@@ -4,6 +4,7 @@ use api_models::analytics::{
auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier},
Granularity, TimeRange,
};
+use common_enums::{AuthenticationStatus, DecoupledAuthenticationType};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
@@ -67,11 +68,17 @@ where
.switch()?;
query_builder
- .add_filter_clause("trans_status", "C".to_string())
+ .add_filter_clause(
+ "authentication_type",
+ DecoupledAuthenticationType::Challenge,
+ )
.switch()?;
query_builder
- .add_negative_filter_clause("authentication_status", "pending")
+ .add_filter_in_range_clause(
+ "authentication_status",
+ &[AuthenticationStatus::Success, AuthenticationStatus::Failed],
+ )
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
time_range
@@ -104,6 +111,7 @@ where
AuthEventMetricsBucketIdentifier::new(
i.authentication_status.as_ref().map(|i| i.0),
i.trans_status.as_ref().map(|i| i.0.clone()),
+ i.authentication_type.as_ref().map(|i| i.0),
i.error_message.clone(),
i.authentication_connector.as_ref().map(|i| i.0),
i.message_version.clone(),
diff --git a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs
index 4d07cffba94..279844388f2 100644
--- a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs
+++ b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs
@@ -4,6 +4,7 @@ use api_models::analytics::{
auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier},
Granularity, TimeRange,
};
+use common_enums::DecoupledAuthenticationType;
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
@@ -67,7 +68,10 @@ where
.switch()?;
query_builder
- .add_filter_clause("trans_status", "C".to_string())
+ .add_filter_clause(
+ "authentication_type",
+ DecoupledAuthenticationType::Challenge,
+ )
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
time_range
@@ -99,6 +103,7 @@ where
AuthEventMetricsBucketIdentifier::new(
i.authentication_status.as_ref().map(|i| i.0),
i.trans_status.as_ref().map(|i| i.0.clone()),
+ i.authentication_type.as_ref().map(|i| i.0),
i.error_message.clone(),
i.authentication_connector.as_ref().map(|i| i.0),
i.message_version.clone(),
diff --git a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs
index 310a45f0530..91e8cc54289 100644
--- a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs
+++ b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs
@@ -4,7 +4,7 @@ use api_models::analytics::{
auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier},
Granularity, TimeRange,
};
-use common_enums::AuthenticationStatus;
+use common_enums::{AuthenticationStatus, DecoupledAuthenticationType};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
@@ -72,7 +72,10 @@ where
.switch()?;
query_builder
- .add_filter_clause("trans_status", "C".to_string())
+ .add_filter_clause(
+ "authentication_type",
+ DecoupledAuthenticationType::Challenge,
+ )
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
time_range
@@ -105,6 +108,7 @@ where
AuthEventMetricsBucketIdentifier::new(
i.authentication_status.as_ref().map(|i| i.0),
i.trans_status.as_ref().map(|i| i.0.clone()),
+ i.authentication_type.as_ref().map(|i| i.0),
i.error_message.clone(),
i.authentication_connector.as_ref().map(|i| i.0),
i.message_version.clone(),
diff --git a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs
index 24857bfb840..b08edb10113 100644
--- a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs
+++ b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs
@@ -4,6 +4,7 @@ use api_models::analytics::{
auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier},
Granularity, TimeRange,
};
+use common_enums::DecoupledAuthenticationType;
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
@@ -67,7 +68,10 @@ where
.switch()?;
query_builder
- .add_filter_clause("trans_status", "Y".to_string())
+ .add_filter_clause(
+ "authentication_type",
+ DecoupledAuthenticationType::Frictionless,
+ )
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
time_range
@@ -100,6 +104,7 @@ where
AuthEventMetricsBucketIdentifier::new(
i.authentication_status.as_ref().map(|i| i.0),
i.trans_status.as_ref().map(|i| i.0.clone()),
+ i.authentication_type.as_ref().map(|i| i.0),
i.error_message.clone(),
i.authentication_connector.as_ref().map(|i| i.0),
i.message_version.clone(),
diff --git a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs
index 79fef8a16d0..80417ac64bf 100644
--- a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs
+++ b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs
@@ -4,7 +4,7 @@ use api_models::analytics::{
auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier},
Granularity, TimeRange,
};
-use common_enums::AuthenticationStatus;
+use common_enums::{AuthenticationStatus, DecoupledAuthenticationType};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
@@ -68,7 +68,10 @@ where
.switch()?;
query_builder
- .add_filter_clause("trans_status", "Y".to_string())
+ .add_filter_clause(
+ "authentication_type",
+ DecoupledAuthenticationType::Frictionless,
+ )
.switch()?;
query_builder
@@ -105,6 +108,7 @@ where
AuthEventMetricsBucketIdentifier::new(
i.authentication_status.as_ref().map(|i| i.0),
i.trans_status.as_ref().map(|i| i.0.clone()),
+ i.authentication_type.as_ref().map(|i| i.0),
i.error_message.clone(),
i.authentication_connector.as_ref().map(|i| i.0),
i.message_version.clone(),
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs
index f698b1161a0..89f5cbd5b9c 100644
--- a/crates/analytics/src/lib.rs
+++ b/crates/analytics/src/lib.rs
@@ -1123,6 +1123,7 @@ pub struct ReportConfig {
pub payment_function: String,
pub refund_function: String,
pub dispute_function: String,
+ pub authentication_function: String,
pub region: String,
}
@@ -1151,6 +1152,7 @@ pub enum AnalyticsFlow {
GeneratePaymentReport,
GenerateDisputeReport,
GenerateRefundReport,
+ GenerateAuthenticationReport,
GetApiEventMetrics,
GetApiEventFilters,
GetConnectorEvents,
diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs
index d483ce43605..5effd9e70a7 100644
--- a/crates/analytics/src/query.rs
+++ b/crates/analytics/src/query.rs
@@ -19,7 +19,9 @@ use api_models::{
},
refunds::RefundStatus,
};
-use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus};
+use common_enums::{
+ AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus,
+};
use common_utils::{
errors::{CustomResult, ParsingError},
id_type::{MerchantId, OrganizationId, ProfileId},
@@ -506,6 +508,7 @@ impl_to_sql_for_to_string!(
TransactionStatus,
AuthenticationStatus,
AuthenticationConnectors,
+ DecoupledAuthenticationType,
Flow,
&String,
&bool,
diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs
index a6db92e753f..6a6237e6783 100644
--- a/crates/analytics/src/sqlx.rs
+++ b/crates/analytics/src/sqlx.rs
@@ -4,7 +4,9 @@ use api_models::{
analytics::{frm::FrmTransactionType, refunds::RefundType},
enums::{DisputeStage, DisputeStatus},
};
-use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus};
+use common_enums::{
+ AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus,
+};
use common_utils::{
errors::{CustomResult, ParsingError},
DbConnectionParams,
@@ -100,6 +102,7 @@ db_type!(DisputeStatus);
db_type!(AuthenticationStatus);
db_type!(TransactionStatus);
db_type!(AuthenticationConnectors);
+db_type!(DecoupledAuthenticationType);
impl<'q, Type> Encode<'q, Postgres> for DBEnumWrapper<Type>
where
@@ -208,6 +211,11 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
+ let authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>> =
+ row.try_get("authentication_type").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
@@ -237,6 +245,7 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow
Ok(Self {
authentication_status,
trans_status,
+ authentication_type,
error_message,
authentication_connector,
message_version,
@@ -259,6 +268,11 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
+ let authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>> =
+ row.try_get("authentication_type").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
@@ -277,6 +291,7 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow
Ok(Self {
authentication_status,
trans_status,
+ authentication_type,
error_message,
authentication_connector,
message_version,
diff --git a/crates/api_models/src/analytics/auth_events.rs b/crates/api_models/src/analytics/auth_events.rs
index 5c2d4ed2064..2360e564642 100644
--- a/crates/api_models/src/analytics/auth_events.rs
+++ b/crates/api_models/src/analytics/auth_events.rs
@@ -3,7 +3,9 @@ use std::{
hash::{Hash, Hasher},
};
-use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus};
+use common_enums::{
+ AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus,
+};
use super::{NameDescription, TimeRange};
@@ -14,6 +16,8 @@ pub struct AuthEventFilters {
#[serde(default)]
pub trans_status: Vec<TransactionStatus>,
#[serde(default)]
+ pub authentication_type: Vec<DecoupledAuthenticationType>,
+ #[serde(default)]
pub error_message: Vec<String>,
#[serde(default)]
pub authentication_connector: Vec<AuthenticationConnectors>,
@@ -42,6 +46,7 @@ pub enum AuthEventDimensions {
#[strum(serialize = "trans_status")]
#[serde(rename = "trans_status")]
TransactionStatus,
+ AuthenticationType,
ErrorMessage,
AuthenticationConnector,
MessageVersion,
@@ -101,6 +106,7 @@ pub mod metric_behaviour {
pub struct ChallengeAttemptCount;
pub struct ChallengeSuccessCount;
pub struct AuthenticationErrorMessage;
+ pub struct AuthenticationFunnel;
}
impl From<AuthEventMetrics> for NameDescription {
@@ -125,6 +131,7 @@ impl From<AuthEventDimensions> for NameDescription {
pub struct AuthEventMetricsBucketIdentifier {
pub authentication_status: Option<AuthenticationStatus>,
pub trans_status: Option<TransactionStatus>,
+ pub authentication_type: Option<DecoupledAuthenticationType>,
pub error_message: Option<String>,
pub authentication_connector: Option<AuthenticationConnectors>,
pub message_version: Option<String>,
@@ -140,6 +147,7 @@ impl AuthEventMetricsBucketIdentifier {
pub fn new(
authentication_status: Option<AuthenticationStatus>,
trans_status: Option<TransactionStatus>,
+ authentication_type: Option<DecoupledAuthenticationType>,
error_message: Option<String>,
authentication_connector: Option<AuthenticationConnectors>,
message_version: Option<String>,
@@ -148,6 +156,7 @@ impl AuthEventMetricsBucketIdentifier {
Self {
authentication_status,
trans_status,
+ authentication_type,
error_message,
authentication_connector,
message_version,
@@ -161,6 +170,7 @@ impl Hash for AuthEventMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.authentication_status.hash(state);
self.trans_status.hash(state);
+ self.authentication_type.hash(state);
self.authentication_connector.hash(state);
self.message_version.hash(state);
self.error_message.hash(state);
diff --git a/crates/api_models/src/analytics/sdk_events.rs b/crates/api_models/src/analytics/sdk_events.rs
index b2abbbe00e1..9a749f1144e 100644
--- a/crates/api_models/src/analytics/sdk_events.rs
+++ b/crates/api_models/src/analytics/sdk_events.rs
@@ -114,6 +114,10 @@ pub enum SdkEventNames {
ThreeDsMethod,
LoaderChanged,
DisplayThreeDsSdk,
+ ThreeDsSdkInit,
+ AreqParamsGeneration,
+ ChallengePresented,
+ ChallengeComplete,
}
pub mod metric_behaviour {
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index 858c16d052f..cc242f86a5b 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -90,6 +90,10 @@ pub mod routes {
web::resource("report/payments")
.route(web::post().to(generate_merchant_payment_report)),
)
+ .service(
+ web::resource("report/authentications")
+ .route(web::post().to(generate_merchant_authentication_report)),
+ )
.service(
web::resource("metrics/sdk_events")
.route(web::post().to(get_sdk_event_metrics)),
@@ -190,6 +194,11 @@ pub mod routes {
web::resource("report/payments")
.route(web::post().to(generate_merchant_payment_report)),
)
+ .service(
+ web::resource("report/authentications").route(
+ web::post().to(generate_merchant_authentication_report),
+ ),
+ )
.service(
web::resource("metrics/api_events")
.route(web::post().to(get_merchant_api_events_metrics)),
@@ -252,6 +261,10 @@ pub mod routes {
web::resource("report/payments")
.route(web::post().to(generate_org_payment_report)),
)
+ .service(
+ web::resource("report/authentications")
+ .route(web::post().to(generate_org_authentication_report)),
+ )
.service(
web::resource("metrics/sankey")
.route(web::post().to(get_org_sankey)),
@@ -306,6 +319,11 @@ pub mod routes {
web::resource("report/payments")
.route(web::post().to(generate_profile_payment_report)),
)
+ .service(
+ web::resource("report/authentications").route(
+ web::post().to(generate_profile_authentication_report),
+ ),
+ )
.service(
web::resource("api_event_logs")
.route(web::get().to(get_profile_api_events)),
@@ -1746,6 +1764,7 @@ pub mod routes {
))
.await
}
+
#[cfg(feature = "v1")]
pub async fn generate_org_payment_report(
state: web::Data<AppState>,
@@ -1850,6 +1869,161 @@ pub mod routes {
.await
}
+ #[cfg(feature = "v1")]
+ pub async fn generate_merchant_authentication_report(
+ state: web::Data<AppState>,
+ req: actix_web::HttpRequest,
+ json_payload: web::Json<ReportRequest>,
+ ) -> impl Responder {
+ let flow = AnalyticsFlow::GenerateAuthenticationReport;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ json_payload.into_inner(),
+ |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {
+ let user = UserInterface::find_user_by_id(&*state.global_store, &user_id)
+ .await
+ .change_context(AnalyticsError::UnknownError)?;
+
+ let user_email = UserEmail::from_pii_email(user.email)
+ .change_context(AnalyticsError::UnknownError)?
+ .get_secret();
+
+ let org_id = auth.merchant_account.get_org_id();
+ let merchant_id = auth.merchant_account.get_id();
+ let lambda_req = GenerateReportRequest {
+ request: payload,
+ merchant_id: Some(merchant_id.clone()),
+ auth: AuthInfo::MerchantLevel {
+ org_id: org_id.clone(),
+ merchant_ids: vec![merchant_id.clone()],
+ },
+ email: user_email,
+ };
+
+ let json_bytes =
+ serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;
+ invoke_lambda(
+ &state.conf.report_download_config.authentication_function,
+ &state.conf.report_download_config.region,
+ &json_bytes,
+ )
+ .await
+ .map(ApplicationResponse::Json)
+ },
+ &auth::JWTAuth {
+ permission: Permission::MerchantReportRead,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ }
+
+ #[cfg(feature = "v1")]
+ pub async fn generate_org_authentication_report(
+ state: web::Data<AppState>,
+ req: actix_web::HttpRequest,
+ json_payload: web::Json<ReportRequest>,
+ ) -> impl Responder {
+ let flow = AnalyticsFlow::GenerateAuthenticationReport;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ json_payload.into_inner(),
+ |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {
+ let user = UserInterface::find_user_by_id(&*state.global_store, &user_id)
+ .await
+ .change_context(AnalyticsError::UnknownError)?;
+
+ let user_email = UserEmail::from_pii_email(user.email)
+ .change_context(AnalyticsError::UnknownError)?
+ .get_secret();
+
+ let org_id = auth.merchant_account.get_org_id();
+ let lambda_req = GenerateReportRequest {
+ request: payload,
+ merchant_id: None,
+ auth: AuthInfo::OrgLevel {
+ org_id: org_id.clone(),
+ },
+ email: user_email,
+ };
+
+ let json_bytes =
+ serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;
+ invoke_lambda(
+ &state.conf.report_download_config.authentication_function,
+ &state.conf.report_download_config.region,
+ &json_bytes,
+ )
+ .await
+ .map(ApplicationResponse::Json)
+ },
+ &auth::JWTAuth {
+ permission: Permission::OrganizationReportRead,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ }
+
+ #[cfg(feature = "v1")]
+ pub async fn generate_profile_authentication_report(
+ state: web::Data<AppState>,
+ req: actix_web::HttpRequest,
+ json_payload: web::Json<ReportRequest>,
+ ) -> impl Responder {
+ let flow = AnalyticsFlow::GenerateAuthenticationReport;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ json_payload.into_inner(),
+ |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {
+ let user = UserInterface::find_user_by_id(&*state.global_store, &user_id)
+ .await
+ .change_context(AnalyticsError::UnknownError)?;
+
+ let user_email = UserEmail::from_pii_email(user.email)
+ .change_context(AnalyticsError::UnknownError)?
+ .get_secret();
+ let org_id = auth.merchant_account.get_org_id();
+ let merchant_id = auth.merchant_account.get_id();
+ let profile_id = auth
+ .profile_id
+ .ok_or(report!(UserErrors::JwtProfileIdMissing))
+ .change_context(AnalyticsError::AccessForbiddenError)?;
+ let lambda_req = GenerateReportRequest {
+ request: payload,
+ merchant_id: Some(merchant_id.clone()),
+ auth: AuthInfo::ProfileLevel {
+ org_id: org_id.clone(),
+ merchant_id: merchant_id.clone(),
+ profile_ids: vec![profile_id.clone()],
+ },
+ email: user_email,
+ };
+
+ let json_bytes =
+ serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;
+ invoke_lambda(
+ &state.conf.report_download_config.authentication_function,
+ &state.conf.report_download_config.region,
+ &json_bytes,
+ )
+ .await
+ .map(ApplicationResponse::Json)
+ },
+ &auth::JWTAuth {
+ permission: Permission::ProfileReportRead,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ }
+
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetApiEventMetricRequest` element.
|
feat
|
modified authentication queries and added generate report for authentications (#7483)
|
f95ee51bb3b879762d493953b4b6e7c2e0359946
|
2024-12-16 17:26:51
|
Sakil Mostak
|
fix(router): handle default case for card_network for co-badged cards (#6825)
| false
|
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index fa5f5e03e47..ba14457e023 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -4433,7 +4433,7 @@ pub async fn get_additional_payment_data(
api_models::payments::AdditionalPaymentData::Card(Box::new(
api_models::payments::AdditionalCardInfo {
card_issuer: card_info.card_issuer,
- card_network: card_network.or(card_info.card_network),
+ card_network: card_network.clone().or(card_info.card_network),
bank_code: card_info.bank_code,
card_type: card_info.card_type,
card_issuing_country: card_info.card_issuing_country,
@@ -4453,7 +4453,7 @@ pub async fn get_additional_payment_data(
api_models::payments::AdditionalPaymentData::Card(Box::new(
api_models::payments::AdditionalCardInfo {
card_issuer: None,
- card_network: None,
+ card_network,
bank_code: None,
card_type: None,
card_issuing_country: None,
@@ -4696,7 +4696,7 @@ pub async fn get_additional_payment_data(
api_models::payments::AdditionalPaymentData::Card(Box::new(
api_models::payments::AdditionalCardInfo {
card_issuer: card_info.card_issuer,
- card_network: card_network.or(card_info.card_network),
+ card_network: card_network.clone().or(card_info.card_network),
bank_code: card_info.bank_code,
card_type: card_info.card_type,
card_issuing_country: card_info.card_issuing_country,
@@ -4716,7 +4716,7 @@ pub async fn get_additional_payment_data(
api_models::payments::AdditionalPaymentData::Card(Box::new(
api_models::payments::AdditionalCardInfo {
card_issuer: None,
- card_network: None,
+ card_network,
bank_code: None,
card_type: None,
card_issuing_country: None,
|
fix
|
handle default case for card_network for co-badged cards (#6825)
|
b2248fe08b0b075a9d326e862a18f50e5bef12f8
|
2024-04-23 15:04:55
|
Sai Harsha Vardhan
|
chore(configs): add wasm changes for pull_mechanism_enabled config for 3dsecureio connector (#4433)
| false
|
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index 805c4a86cbc..47dad675a4e 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -89,6 +89,7 @@ pub struct ConfigMetadata {
pub acquirer_merchant_id: Option<String>,
pub three_ds_requestor_name: Option<String>,
pub three_ds_requestor_id: Option<String>,
+ pub pull_mechanism_for_external_3ds_enabled: Option<bool>,
}
#[serde_with::skip_serializing_none]
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index b1c66ce1805..9a231f0dc6d 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -2598,6 +2598,7 @@ api_key="Api Key"
mcc="MCC"
merchant_country_code="3 digit numeric country code"
merchant_name="Name of the merchant"
+pull_mechanism_for_external_3ds_enabled=true
[netcetera]
[netcetera.connector_auth.CertificateAuth]
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index ee21ac99b8d..5bb61ec2320 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -2600,6 +2600,7 @@ api_key="Api Key"
mcc="MCC"
merchant_country_code="3 digit numeric country code"
merchant_name="Name of the merchant"
+pull_mechanism_for_external_3ds_enabled=true
[netcetera]
[netcetera.connector_auth.CertificateAuth]
|
chore
|
add wasm changes for pull_mechanism_enabled config for 3dsecureio connector (#4433)
|
e0e843715cd02ac8b2eff2f645fe8471551ee914
|
2024-04-08 17:50:05
|
Swangi Kumari
|
refactor(payment_methods): add BankRedirect payment method data to new domain type to be used in connector module (#4175)
| false
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index de8142ddde2..bff6dbec3ce 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -39,7 +39,7 @@ pub struct BankData {
#[derive(serde::Deserialize)]
pub struct BankCodeInformation {
- pub bank_name: api_enums::BankNames,
+ pub bank_name: common_enums::BankNames,
pub connector_codes: Vec<ConnectorCode>,
}
@@ -51,7 +51,7 @@ pub struct ConnectorCode {
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)]
pub struct BankCodeResponse {
- pub bank_name: Vec<api_enums::BankNames>,
+ pub bank_name: Vec<common_enums::BankNames>,
pub eligible_connectors: Vec<String>,
}
@@ -1571,7 +1571,7 @@ pub struct AdditionalCardInfo {
pub enum AdditionalPaymentData {
Card(Box<AdditionalCardInfo>),
BankRedirect {
- bank_name: Option<api_enums::BankNames>,
+ bank_name: Option<common_enums::BankNames>,
},
Wallet {
apple_pay: Option<ApplepayPaymentMethod>,
@@ -1622,7 +1622,7 @@ pub enum BankRedirectData {
/// The hyperswitch bank code for eps
#[schema(value_type = BankNames, example = "triodos_bank")]
- bank_name: Option<api_enums::BankNames>,
+ bank_name: Option<common_enums::BankNames>,
/// The country for bank payment
#[schema(value_type = CountryAlpha2, example = "US")]
@@ -1651,7 +1651,7 @@ pub enum BankRedirectData {
/// The hyperswitch bank code for ideal
#[schema(value_type = BankNames, example = "abn_amro")]
- bank_name: Option<api_enums::BankNames>,
+ bank_name: Option<common_enums::BankNames>,
/// The country for bank payment
#[schema(value_type = CountryAlpha2, example = "US")]
@@ -1668,7 +1668,7 @@ pub enum BankRedirectData {
OnlineBankingCzechRepublic {
// Issuer banks
#[schema(value_type = BankNames)]
- issuer: api_enums::BankNames,
+ issuer: common_enums::BankNames,
},
OnlineBankingFinland {
// Shopper Email
@@ -1678,17 +1678,17 @@ pub enum BankRedirectData {
OnlineBankingPoland {
// Issuer banks
#[schema(value_type = BankNames)]
- issuer: api_enums::BankNames,
+ issuer: common_enums::BankNames,
},
OnlineBankingSlovakia {
// Issuer value corresponds to the bank
#[schema(value_type = BankNames)]
- issuer: api_enums::BankNames,
+ issuer: common_enums::BankNames,
},
OpenBankingUk {
// Issuer banks
#[schema(value_type = BankNames)]
- issuer: Option<api_enums::BankNames>,
+ issuer: Option<common_enums::BankNames>,
/// The country for bank payment
#[schema(value_type = CountryAlpha2, example = "US")]
country: Option<api_enums::CountryAlpha2>,
@@ -1696,7 +1696,7 @@ pub enum BankRedirectData {
Przelewy24 {
//Issuer banks
#[schema(value_type = Option<BankNames>)]
- bank_name: Option<api_enums::BankNames>,
+ bank_name: Option<common_enums::BankNames>,
// The billing details for bank redirect
billing_details: BankRedirectBilling,
@@ -1721,11 +1721,11 @@ pub enum BankRedirectData {
OnlineBankingFpx {
// Issuer banks
#[schema(value_type = BankNames)]
- issuer: api_enums::BankNames,
+ issuer: common_enums::BankNames,
},
OnlineBankingThailand {
#[schema(value_type = BankNames)]
- issuer: api_enums::BankNames,
+ issuer: common_enums::BankNames,
},
}
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index eea1dedf2a0..932b82ae09c 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2,6 +2,7 @@ use std::num::{ParseFloatError, TryFromIntError};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
+
#[doc(hidden)]
pub mod diesel_exports {
pub use super::{
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 1416012e69c..a15f9a11153 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -323,7 +323,7 @@ pub struct ConnectorBankNames(pub HashMap<String, BanksVector>);
#[derive(Debug, Deserialize, Clone)]
pub struct BanksVector {
#[serde(deserialize_with = "deserialize_hashset")]
- pub banks: HashSet<api_models::enums::BankNames>,
+ pub banks: HashSet<common_enums::enums::BankNames>,
}
#[derive(Debug, Deserialize, Clone, Default)]
diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs
index d72d6d6fafe..b8f3af69145 100644
--- a/crates/router/src/connector/aci/transformers.rs
+++ b/crates/router/src/connector/aci/transformers.rs
@@ -1,6 +1,5 @@
use std::str::FromStr;
-use api_models::enums::BankNames;
use common_utils::pii::Email;
use error_stack::report;
use masking::{ExposeInterface, Secret};
@@ -153,19 +152,19 @@ impl TryFrom<&domain::WalletData> for PaymentDetails {
impl
TryFrom<(
&AciRouterData<&types::PaymentsAuthorizeRouterData>,
- &api_models::payments::BankRedirectData,
+ &domain::BankRedirectData,
)> for PaymentDetails
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&types::PaymentsAuthorizeRouterData>,
- &api_models::payments::BankRedirectData,
+ &domain::BankRedirectData,
),
) -> Result<Self, Self::Error> {
let (item, bank_redirect_data) = value;
let payment_data = match bank_redirect_data {
- api_models::payments::BankRedirectData::Eps { country, .. } => {
+ domain::BankRedirectData::Eps { country, .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Eps,
bank_account_country: Some(country.ok_or(
@@ -182,7 +181,7 @@ impl
customer_email: None,
}))
}
- api_models::payments::BankRedirectData::Giropay {
+ domain::BankRedirectData::Giropay {
bank_account_bic,
bank_account_iban,
country,
@@ -202,7 +201,7 @@ impl
merchant_transaction_id: None,
customer_email: None,
})),
- api_models::payments::BankRedirectData::Ideal {
+ domain::BankRedirectData::Ideal {
bank_name, country, ..
} => Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Ideal,
@@ -223,7 +222,7 @@ impl
merchant_transaction_id: None,
customer_email: None,
})),
- api_models::payments::BankRedirectData::Sofort { country, .. } => {
+ domain::BankRedirectData::Sofort { country, .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Sofortueberweisung,
bank_account_country: Some(country.to_owned().ok_or(
@@ -240,7 +239,7 @@ impl
customer_email: None,
}))
}
- api_models::payments::BankRedirectData::Przelewy24 {
+ domain::BankRedirectData::Przelewy24 {
billing_details, ..
} => Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Przelewy,
@@ -253,7 +252,7 @@ impl
merchant_transaction_id: None,
customer_email: billing_details.email.to_owned(),
})),
- api_models::payments::BankRedirectData::Interac { email, country } => {
+ domain::BankRedirectData::Interac { email, country } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::InteracOnline,
bank_account_country: Some(country.to_owned()),
@@ -266,7 +265,7 @@ impl
customer_email: Some(email.to_owned()),
}))
}
- api_models::payments::BankRedirectData::Trustly { country } => {
+ domain::BankRedirectData::Trustly { country } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Trustly,
bank_account_country: None,
@@ -281,16 +280,16 @@ impl
customer_email: None,
}))
}
- api_models::payments::BankRedirectData::Bizum { .. }
- | api_models::payments::BankRedirectData::Blik { .. }
- | api_models::payments::BankRedirectData::BancontactCard { .. }
- | api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { .. }
- | api_models::payments::BankRedirectData::OnlineBankingFinland { .. }
- | api_models::payments::BankRedirectData::OnlineBankingFpx { .. }
- | api_models::payments::BankRedirectData::OnlineBankingPoland { .. }
- | api_models::payments::BankRedirectData::OnlineBankingSlovakia { .. }
- | api_models::payments::BankRedirectData::OnlineBankingThailand { .. }
- | api_models::payments::BankRedirectData::OpenBankingUk { .. } => Err(
+ domain::BankRedirectData::Bizum { .. }
+ | domain::BankRedirectData::Blik { .. }
+ | domain::BankRedirectData::BancontactCard { .. }
+ | domain::BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | domain::BankRedirectData::OnlineBankingFinland { .. }
+ | domain::BankRedirectData::OnlineBankingFpx { .. }
+ | domain::BankRedirectData::OnlineBankingPoland { .. }
+ | domain::BankRedirectData::OnlineBankingSlovakia { .. }
+ | domain::BankRedirectData::OnlineBankingThailand { .. }
+ | domain::BankRedirectData::OpenBankingUk { .. } => Err(
errors::ConnectorError::NotImplemented("Payment method".to_string()),
)?,
};
@@ -320,7 +319,7 @@ pub struct BankRedirectionPMData {
#[serde(rename = "bankAccount.country")]
bank_account_country: Option<api_models::enums::CountryAlpha2>,
#[serde(rename = "bankAccount.bankName")]
- bank_account_bank_name: Option<BankNames>,
+ bank_account_bank_name: Option<common_enums::BankNames>,
#[serde(rename = "bankAccount.bic")]
bank_account_bic: Option<Secret<String>>,
#[serde(rename = "bankAccount.iban")]
@@ -501,14 +500,14 @@ impl
impl
TryFrom<(
&AciRouterData<&types::PaymentsAuthorizeRouterData>,
- &api_models::payments::BankRedirectData,
+ &domain::BankRedirectData,
)> for AciPaymentsRequest
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&types::PaymentsAuthorizeRouterData>,
- &api_models::payments::BankRedirectData,
+ &domain::BankRedirectData,
),
) -> Result<Self, Self::Error> {
let (item, bank_redirect_data) = value;
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 63c67c80ef4..cc37f464ae6 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -20,7 +20,7 @@ use crate::{
services,
types::{
self,
- api::{self, enums as api_enums},
+ api::enums as api_enums,
domain,
storage::enums as storage_enums,
transformers::{ForeignFrom, ForeignTryFrom},
@@ -746,13 +746,13 @@ impl TryFrom<&Box<payments::JCSVoucherData>> for JCSVoucherData {
}
}
-impl TryFrom<&api_enums::BankNames> for OnlineBankingCzechRepublicBanks {
+impl TryFrom<&common_enums::BankNames> for OnlineBankingCzechRepublicBanks {
type Error = Error;
- fn try_from(bank_name: &api_enums::BankNames) -> Result<Self, Self::Error> {
+ fn try_from(bank_name: &common_enums::BankNames) -> Result<Self, Self::Error> {
match bank_name {
- api::enums::BankNames::KomercniBanka => Ok(Self::KB),
- api::enums::BankNames::CeskaSporitelna => Ok(Self::CS),
- api::enums::BankNames::PlatnoscOnlineKartaPlatnicza => Ok(Self::C),
+ common_enums::BankNames::KomercniBanka => Ok(Self::KB),
+ common_enums::BankNames::CeskaSporitelna => Ok(Self::CS),
+ common_enums::BankNames::PlatnoscOnlineKartaPlatnicza => Ok(Self::C),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Adyen"),
))?,
@@ -809,29 +809,29 @@ pub enum OnlineBankingPolandBanks {
ETransferPocztowy24,
}
-impl TryFrom<&api_enums::BankNames> for OnlineBankingPolandBanks {
+impl TryFrom<&common_enums::BankNames> for OnlineBankingPolandBanks {
type Error = Error;
- fn try_from(bank_name: &api_enums::BankNames) -> Result<Self, Self::Error> {
+ fn try_from(bank_name: &common_enums::BankNames) -> Result<Self, Self::Error> {
match bank_name {
- api_models::enums::BankNames::BlikPSP => Ok(Self::BlikPSP),
- api_models::enums::BankNames::PlaceZIPKO => Ok(Self::PlaceZIPKO),
- api_models::enums::BankNames::MBank => Ok(Self::MBank),
- api_models::enums::BankNames::PayWithING => Ok(Self::PayWithING),
- api_models::enums::BankNames::SantanderPrzelew24 => Ok(Self::SantanderPrzelew24),
- api_models::enums::BankNames::BankPEKAOSA => Ok(Self::BankPEKAOSA),
- api_models::enums::BankNames::BankMillennium => Ok(Self::BankMillennium),
- api_models::enums::BankNames::PayWithAliorBank => Ok(Self::PayWithAliorBank),
- api_models::enums::BankNames::BankiSpoldzielcze => Ok(Self::BankiSpoldzielcze),
- api_models::enums::BankNames::PayWithInteligo => Ok(Self::PayWithInteligo),
- api_models::enums::BankNames::BNPParibasPoland => Ok(Self::BNPParibasPoland),
- api_models::enums::BankNames::BankNowySA => Ok(Self::BankNowySA),
- api_models::enums::BankNames::CreditAgricole => Ok(Self::CreditAgricole),
- api_models::enums::BankNames::PayWithBOS => Ok(Self::PayWithBOS),
- api_models::enums::BankNames::PayWithCitiHandlowy => Ok(Self::PayWithCitiHandlowy),
- api_models::enums::BankNames::PayWithPlusBank => Ok(Self::PayWithPlusBank),
- api_models::enums::BankNames::ToyotaBank => Ok(Self::ToyotaBank),
- api_models::enums::BankNames::VeloBank => Ok(Self::VeloBank),
- api_models::enums::BankNames::ETransferPocztowy24 => Ok(Self::ETransferPocztowy24),
+ common_enums::BankNames::BlikPSP => Ok(Self::BlikPSP),
+ common_enums::BankNames::PlaceZIPKO => Ok(Self::PlaceZIPKO),
+ common_enums::BankNames::MBank => Ok(Self::MBank),
+ common_enums::BankNames::PayWithING => Ok(Self::PayWithING),
+ common_enums::BankNames::SantanderPrzelew24 => Ok(Self::SantanderPrzelew24),
+ common_enums::BankNames::BankPEKAOSA => Ok(Self::BankPEKAOSA),
+ common_enums::BankNames::BankMillennium => Ok(Self::BankMillennium),
+ common_enums::BankNames::PayWithAliorBank => Ok(Self::PayWithAliorBank),
+ common_enums::BankNames::BankiSpoldzielcze => Ok(Self::BankiSpoldzielcze),
+ common_enums::BankNames::PayWithInteligo => Ok(Self::PayWithInteligo),
+ common_enums::BankNames::BNPParibasPoland => Ok(Self::BNPParibasPoland),
+ common_enums::BankNames::BankNowySA => Ok(Self::BankNowySA),
+ common_enums::BankNames::CreditAgricole => Ok(Self::CreditAgricole),
+ common_enums::BankNames::PayWithBOS => Ok(Self::PayWithBOS),
+ common_enums::BankNames::PayWithCitiHandlowy => Ok(Self::PayWithCitiHandlowy),
+ common_enums::BankNames::PayWithPlusBank => Ok(Self::PayWithPlusBank),
+ common_enums::BankNames::ToyotaBank => Ok(Self::ToyotaBank),
+ common_enums::BankNames::VeloBank => Ok(Self::VeloBank),
+ common_enums::BankNames::ETransferPocztowy24 => Ok(Self::ETransferPocztowy24),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Adyen"),
))?,
@@ -874,15 +874,15 @@ pub enum OnlineBankingSlovakiaBanks {
Viamo,
}
-impl TryFrom<&api_enums::BankNames> for OnlineBankingSlovakiaBanks {
+impl TryFrom<&common_enums::BankNames> for OnlineBankingSlovakiaBanks {
type Error = Error;
- fn try_from(bank_name: &api_enums::BankNames) -> Result<Self, Self::Error> {
+ fn try_from(bank_name: &common_enums::BankNames) -> Result<Self, Self::Error> {
match bank_name {
- api::enums::BankNames::EPlatbyVUB => Ok(Self::Vub),
- api::enums::BankNames::PostovaBanka => Ok(Self::Posto),
- api::enums::BankNames::SporoPay => Ok(Self::Sporo),
- api::enums::BankNames::TatraPay => Ok(Self::Tatra),
- api::enums::BankNames::Viamo => Ok(Self::Viamo),
+ common_enums::BankNames::EPlatbyVUB => Ok(Self::Vub),
+ common_enums::BankNames::PostovaBanka => Ok(Self::Posto),
+ common_enums::BankNames::SporoPay => Ok(Self::Sporo),
+ common_enums::BankNames::TatraPay => Ok(Self::Tatra),
+ common_enums::BankNames::Viamo => Ok(Self::Viamo),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Adyen"),
))?,
@@ -890,28 +890,28 @@ impl TryFrom<&api_enums::BankNames> for OnlineBankingSlovakiaBanks {
}
}
-impl TryFrom<&api_enums::BankNames> for OnlineBankingFpxIssuer {
+impl TryFrom<&common_enums::BankNames> for OnlineBankingFpxIssuer {
type Error = Error;
- fn try_from(bank_name: &api_enums::BankNames) -> Result<Self, Self::Error> {
+ fn try_from(bank_name: &common_enums::BankNames) -> Result<Self, Self::Error> {
match bank_name {
- api::enums::BankNames::AffinBank => Ok(Self::FpxAbb),
- api::enums::BankNames::AgroBank => Ok(Self::FpxAgrobank),
- api::enums::BankNames::AllianceBank => Ok(Self::FpxAbmb),
- api::enums::BankNames::AmBank => Ok(Self::FpxAmb),
- api::enums::BankNames::BankIslam => Ok(Self::FpxBimb),
- api::enums::BankNames::BankMuamalat => Ok(Self::FpxBmmb),
- api::enums::BankNames::BankRakyat => Ok(Self::FpxBkrm),
- api::enums::BankNames::BankSimpananNasional => Ok(Self::FpxBsn),
- api::enums::BankNames::CimbBank => Ok(Self::FpxCimbclicks),
- api::enums::BankNames::HongLeongBank => Ok(Self::FpxHlb),
- api::enums::BankNames::HsbcBank => Ok(Self::FpxHsbc),
- api::enums::BankNames::KuwaitFinanceHouse => Ok(Self::FpxKfh),
- api::enums::BankNames::Maybank => Ok(Self::FpxMb2u),
- api::enums::BankNames::OcbcBank => Ok(Self::FpxOcbc),
- api::enums::BankNames::PublicBank => Ok(Self::FpxPbb),
- api::enums::BankNames::RhbBank => Ok(Self::FpxRhb),
- api::enums::BankNames::StandardCharteredBank => Ok(Self::FpxScb),
- api::enums::BankNames::UobBank => Ok(Self::FpxUob),
+ common_enums::BankNames::AffinBank => Ok(Self::FpxAbb),
+ common_enums::BankNames::AgroBank => Ok(Self::FpxAgrobank),
+ common_enums::BankNames::AllianceBank => Ok(Self::FpxAbmb),
+ common_enums::BankNames::AmBank => Ok(Self::FpxAmb),
+ common_enums::BankNames::BankIslam => Ok(Self::FpxBimb),
+ common_enums::BankNames::BankMuamalat => Ok(Self::FpxBmmb),
+ common_enums::BankNames::BankRakyat => Ok(Self::FpxBkrm),
+ common_enums::BankNames::BankSimpananNasional => Ok(Self::FpxBsn),
+ common_enums::BankNames::CimbBank => Ok(Self::FpxCimbclicks),
+ common_enums::BankNames::HongLeongBank => Ok(Self::FpxHlb),
+ common_enums::BankNames::HsbcBank => Ok(Self::FpxHsbc),
+ common_enums::BankNames::KuwaitFinanceHouse => Ok(Self::FpxKfh),
+ common_enums::BankNames::Maybank => Ok(Self::FpxMb2u),
+ common_enums::BankNames::OcbcBank => Ok(Self::FpxOcbc),
+ common_enums::BankNames::PublicBank => Ok(Self::FpxPbb),
+ common_enums::BankNames::RhbBank => Ok(Self::FpxRhb),
+ common_enums::BankNames::StandardCharteredBank => Ok(Self::FpxScb),
+ common_enums::BankNames::UobBank => Ok(Self::FpxUob),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Adyen"),
))?,
@@ -919,15 +919,15 @@ impl TryFrom<&api_enums::BankNames> for OnlineBankingFpxIssuer {
}
}
-impl TryFrom<&api_enums::BankNames> for OnlineBankingThailandIssuer {
+impl TryFrom<&common_enums::BankNames> for OnlineBankingThailandIssuer {
type Error = Error;
- fn try_from(bank_name: &api_enums::BankNames) -> Result<Self, Self::Error> {
+ fn try_from(bank_name: &common_enums::BankNames) -> Result<Self, Self::Error> {
match bank_name {
- api::enums::BankNames::BangkokBank => Ok(Self::Bangkokbank),
- api::enums::BankNames::KrungsriBank => Ok(Self::Krungsribank),
- api::enums::BankNames::KrungThaiBank => Ok(Self::Krungthaibank),
- api::enums::BankNames::TheSiamCommercialBank => Ok(Self::Siamcommercialbank),
- api::enums::BankNames::KasikornBank => Ok(Self::Kbank),
+ common_enums::BankNames::BangkokBank => Ok(Self::Bangkokbank),
+ common_enums::BankNames::KrungsriBank => Ok(Self::Krungsribank),
+ common_enums::BankNames::KrungThaiBank => Ok(Self::Krungthaibank),
+ common_enums::BankNames::TheSiamCommercialBank => Ok(Self::Siamcommercialbank),
+ common_enums::BankNames::KasikornBank => Ok(Self::Kbank),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Adyen"),
))?,
@@ -935,157 +935,159 @@ impl TryFrom<&api_enums::BankNames> for OnlineBankingThailandIssuer {
}
}
-impl TryFrom<&api_enums::BankNames> for OpenBankingUKIssuer {
+impl TryFrom<&common_enums::BankNames> for OpenBankingUKIssuer {
type Error = Error;
- fn try_from(bank_name: &api_enums::BankNames) -> Result<Self, Self::Error> {
+ fn try_from(bank_name: &common_enums::BankNames) -> Result<Self, Self::Error> {
match bank_name {
- api::enums::BankNames::OpenBankSuccess => Ok(Self::RedirectSuccess),
- api::enums::BankNames::OpenBankFailure => Ok(Self::RedirectFailure),
- api::enums::BankNames::OpenBankCancelled => Ok(Self::RedirectCancelled),
- api::enums::BankNames::Aib => Ok(Self::Aib),
- api::enums::BankNames::BankOfScotland => Ok(Self::BankOfScotland),
- api::enums::BankNames::Barclays => Ok(Self::Barclays),
- api::enums::BankNames::DanskeBank => Ok(Self::DanskeBank),
- api::enums::BankNames::FirstDirect => Ok(Self::FirstDirect),
- api::enums::BankNames::FirstTrust => Ok(Self::FirstTrust),
- api::enums::BankNames::HsbcBank => Ok(Self::HsbcBank),
- api::enums::BankNames::Halifax => Ok(Self::Halifax),
- api::enums::BankNames::Lloyds => Ok(Self::Lloyds),
- api::enums::BankNames::Monzo => Ok(Self::Monzo),
- api::enums::BankNames::NatWest => Ok(Self::NatWest),
- api::enums::BankNames::NationwideBank => Ok(Self::NationwideBank),
- api::enums::BankNames::Revolut => Ok(Self::Revolut),
- api::enums::BankNames::RoyalBankOfScotland => Ok(Self::RoyalBankOfScotland),
- api::enums::BankNames::SantanderPrzelew24 => Ok(Self::SantanderPrzelew24),
- api::enums::BankNames::Starling => Ok(Self::Starling),
- api::enums::BankNames::TsbBank => Ok(Self::TsbBank),
- api::enums::BankNames::TescoBank => Ok(Self::TescoBank),
- api::enums::BankNames::UlsterBank => Ok(Self::UlsterBank),
- enums::BankNames::AmericanExpress
- | enums::BankNames::AffinBank
- | enums::BankNames::AgroBank
- | enums::BankNames::AllianceBank
- | enums::BankNames::AmBank
- | enums::BankNames::BankOfAmerica
- | enums::BankNames::BankIslam
- | enums::BankNames::BankMuamalat
- | enums::BankNames::BankRakyat
- | enums::BankNames::BankSimpananNasional
- | enums::BankNames::BlikPSP
- | enums::BankNames::CapitalOne
- | enums::BankNames::Chase
- | enums::BankNames::Citi
- | enums::BankNames::CimbBank
- | enums::BankNames::Discover
- | enums::BankNames::NavyFederalCreditUnion
- | enums::BankNames::PentagonFederalCreditUnion
- | enums::BankNames::SynchronyBank
- | enums::BankNames::WellsFargo
- | enums::BankNames::AbnAmro
- | enums::BankNames::AsnBank
- | enums::BankNames::Bunq
- | enums::BankNames::Handelsbanken
- | enums::BankNames::HongLeongBank
- | enums::BankNames::Ing
- | enums::BankNames::Knab
- | enums::BankNames::KuwaitFinanceHouse
- | enums::BankNames::Moneyou
- | enums::BankNames::Rabobank
- | enums::BankNames::Regiobank
- | enums::BankNames::SnsBank
- | enums::BankNames::TriodosBank
- | enums::BankNames::VanLanschot
- | enums::BankNames::ArzteUndApothekerBank
- | enums::BankNames::AustrianAnadiBankAg
- | enums::BankNames::BankAustria
- | enums::BankNames::Bank99Ag
- | enums::BankNames::BankhausCarlSpangler
- | enums::BankNames::BankhausSchelhammerUndSchatteraAg
- | enums::BankNames::BankMillennium
- | enums::BankNames::BankPEKAOSA
- | enums::BankNames::BawagPskAg
- | enums::BankNames::BksBankAg
- | enums::BankNames::BrullKallmusBankAg
- | enums::BankNames::BtvVierLanderBank
- | enums::BankNames::CapitalBankGraweGruppeAg
- | enums::BankNames::CeskaSporitelna
- | enums::BankNames::Dolomitenbank
- | enums::BankNames::EasybankAg
- | enums::BankNames::EPlatbyVUB
- | enums::BankNames::ErsteBankUndSparkassen
- | enums::BankNames::FrieslandBank
- | enums::BankNames::HypoAlpeadriabankInternationalAg
- | enums::BankNames::HypoNoeLbFurNiederosterreichUWien
- | enums::BankNames::HypoOberosterreichSalzburgSteiermark
- | enums::BankNames::HypoTirolBankAg
- | enums::BankNames::HypoVorarlbergBankAg
- | enums::BankNames::HypoBankBurgenlandAktiengesellschaft
- | enums::BankNames::KomercniBanka
- | enums::BankNames::MBank
- | enums::BankNames::MarchfelderBank
- | enums::BankNames::Maybank
- | enums::BankNames::OberbankAg
- | enums::BankNames::OsterreichischeArzteUndApothekerbank
- | enums::BankNames::OcbcBank
- | enums::BankNames::PayWithING
- | enums::BankNames::PlaceZIPKO
- | enums::BankNames::PlatnoscOnlineKartaPlatnicza
- | enums::BankNames::PosojilnicaBankEGen
- | enums::BankNames::PostovaBanka
- | enums::BankNames::PublicBank
- | enums::BankNames::RaiffeisenBankengruppeOsterreich
- | enums::BankNames::RhbBank
- | enums::BankNames::SchelhammerCapitalBankAg
- | enums::BankNames::StandardCharteredBank
- | enums::BankNames::SchoellerbankAg
- | enums::BankNames::SpardaBankWien
- | enums::BankNames::SporoPay
- | enums::BankNames::TatraPay
- | enums::BankNames::Viamo
- | enums::BankNames::VolksbankGruppe
- | enums::BankNames::VolkskreditbankAg
- | enums::BankNames::VrBankBraunau
- | enums::BankNames::UobBank
- | enums::BankNames::PayWithAliorBank
- | enums::BankNames::BankiSpoldzielcze
- | enums::BankNames::PayWithInteligo
- | enums::BankNames::BNPParibasPoland
- | enums::BankNames::BankNowySA
- | enums::BankNames::CreditAgricole
- | enums::BankNames::PayWithBOS
- | enums::BankNames::PayWithCitiHandlowy
- | enums::BankNames::PayWithPlusBank
- | enums::BankNames::ToyotaBank
- | enums::BankNames::VeloBank
- | enums::BankNames::ETransferPocztowy24
- | enums::BankNames::PlusBank
- | enums::BankNames::EtransferPocztowy24
- | enums::BankNames::BankiSpbdzielcze
- | enums::BankNames::BankNowyBfgSa
- | enums::BankNames::GetinBank
- | enums::BankNames::Blik
- | enums::BankNames::NoblePay
- | enums::BankNames::IdeaBank
- | enums::BankNames::EnveloBank
- | enums::BankNames::NestPrzelew
- | enums::BankNames::MbankMtransfer
- | enums::BankNames::Inteligo
- | enums::BankNames::PbacZIpko
- | enums::BankNames::BnpParibas
- | enums::BankNames::BankPekaoSa
- | enums::BankNames::VolkswagenBank
- | enums::BankNames::AliorBank
- | enums::BankNames::Boz
- | enums::BankNames::BangkokBank
- | enums::BankNames::KrungsriBank
- | enums::BankNames::KrungThaiBank
- | enums::BankNames::TheSiamCommercialBank
- | enums::BankNames::Yoursafe
- | enums::BankNames::N26
- | enums::BankNames::NationaleNederlanden
- | enums::BankNames::KasikornBank => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Adyen"),
- ))?,
+ common_enums::BankNames::OpenBankSuccess => Ok(Self::RedirectSuccess),
+ common_enums::BankNames::OpenBankFailure => Ok(Self::RedirectFailure),
+ common_enums::BankNames::OpenBankCancelled => Ok(Self::RedirectCancelled),
+ common_enums::BankNames::Aib => Ok(Self::Aib),
+ common_enums::BankNames::BankOfScotland => Ok(Self::BankOfScotland),
+ common_enums::BankNames::Barclays => Ok(Self::Barclays),
+ common_enums::BankNames::DanskeBank => Ok(Self::DanskeBank),
+ common_enums::BankNames::FirstDirect => Ok(Self::FirstDirect),
+ common_enums::BankNames::FirstTrust => Ok(Self::FirstTrust),
+ common_enums::BankNames::HsbcBank => Ok(Self::HsbcBank),
+ common_enums::BankNames::Halifax => Ok(Self::Halifax),
+ common_enums::BankNames::Lloyds => Ok(Self::Lloyds),
+ common_enums::BankNames::Monzo => Ok(Self::Monzo),
+ common_enums::BankNames::NatWest => Ok(Self::NatWest),
+ common_enums::BankNames::NationwideBank => Ok(Self::NationwideBank),
+ common_enums::BankNames::Revolut => Ok(Self::Revolut),
+ common_enums::BankNames::RoyalBankOfScotland => Ok(Self::RoyalBankOfScotland),
+ common_enums::BankNames::SantanderPrzelew24 => Ok(Self::SantanderPrzelew24),
+ common_enums::BankNames::Starling => Ok(Self::Starling),
+ common_enums::BankNames::TsbBank => Ok(Self::TsbBank),
+ common_enums::BankNames::TescoBank => Ok(Self::TescoBank),
+ common_enums::BankNames::UlsterBank => Ok(Self::UlsterBank),
+ common_enums::BankNames::AmericanExpress
+ | common_enums::BankNames::AffinBank
+ | common_enums::BankNames::AgroBank
+ | common_enums::BankNames::AllianceBank
+ | common_enums::BankNames::AmBank
+ | common_enums::BankNames::BankOfAmerica
+ | common_enums::BankNames::BankIslam
+ | common_enums::BankNames::BankMuamalat
+ | common_enums::BankNames::BankRakyat
+ | common_enums::BankNames::BankSimpananNasional
+ | common_enums::BankNames::BlikPSP
+ | common_enums::BankNames::CapitalOne
+ | common_enums::BankNames::Chase
+ | common_enums::BankNames::Citi
+ | common_enums::BankNames::CimbBank
+ | common_enums::BankNames::Discover
+ | common_enums::BankNames::NavyFederalCreditUnion
+ | common_enums::BankNames::PentagonFederalCreditUnion
+ | common_enums::BankNames::SynchronyBank
+ | common_enums::BankNames::WellsFargo
+ | common_enums::BankNames::AbnAmro
+ | common_enums::BankNames::AsnBank
+ | common_enums::BankNames::Bunq
+ | common_enums::BankNames::Handelsbanken
+ | common_enums::BankNames::HongLeongBank
+ | common_enums::BankNames::Ing
+ | common_enums::BankNames::Knab
+ | common_enums::BankNames::KuwaitFinanceHouse
+ | common_enums::BankNames::Moneyou
+ | common_enums::BankNames::Rabobank
+ | common_enums::BankNames::Regiobank
+ | common_enums::BankNames::SnsBank
+ | common_enums::BankNames::TriodosBank
+ | common_enums::BankNames::VanLanschot
+ | common_enums::BankNames::ArzteUndApothekerBank
+ | common_enums::BankNames::AustrianAnadiBankAg
+ | common_enums::BankNames::BankAustria
+ | common_enums::BankNames::Bank99Ag
+ | common_enums::BankNames::BankhausCarlSpangler
+ | common_enums::BankNames::BankhausSchelhammerUndSchatteraAg
+ | common_enums::BankNames::BankMillennium
+ | common_enums::BankNames::BankPEKAOSA
+ | common_enums::BankNames::BawagPskAg
+ | common_enums::BankNames::BksBankAg
+ | common_enums::BankNames::BrullKallmusBankAg
+ | common_enums::BankNames::BtvVierLanderBank
+ | common_enums::BankNames::CapitalBankGraweGruppeAg
+ | common_enums::BankNames::CeskaSporitelna
+ | common_enums::BankNames::Dolomitenbank
+ | common_enums::BankNames::EasybankAg
+ | common_enums::BankNames::EPlatbyVUB
+ | common_enums::BankNames::ErsteBankUndSparkassen
+ | common_enums::BankNames::FrieslandBank
+ | common_enums::BankNames::HypoAlpeadriabankInternationalAg
+ | common_enums::BankNames::HypoNoeLbFurNiederosterreichUWien
+ | common_enums::BankNames::HypoOberosterreichSalzburgSteiermark
+ | common_enums::BankNames::HypoTirolBankAg
+ | common_enums::BankNames::HypoVorarlbergBankAg
+ | common_enums::BankNames::HypoBankBurgenlandAktiengesellschaft
+ | common_enums::BankNames::KomercniBanka
+ | common_enums::BankNames::MBank
+ | common_enums::BankNames::MarchfelderBank
+ | common_enums::BankNames::Maybank
+ | common_enums::BankNames::OberbankAg
+ | common_enums::BankNames::OsterreichischeArzteUndApothekerbank
+ | common_enums::BankNames::OcbcBank
+ | common_enums::BankNames::PayWithING
+ | common_enums::BankNames::PlaceZIPKO
+ | common_enums::BankNames::PlatnoscOnlineKartaPlatnicza
+ | common_enums::BankNames::PosojilnicaBankEGen
+ | common_enums::BankNames::PostovaBanka
+ | common_enums::BankNames::PublicBank
+ | common_enums::BankNames::RaiffeisenBankengruppeOsterreich
+ | common_enums::BankNames::RhbBank
+ | common_enums::BankNames::SchelhammerCapitalBankAg
+ | common_enums::BankNames::StandardCharteredBank
+ | common_enums::BankNames::SchoellerbankAg
+ | common_enums::BankNames::SpardaBankWien
+ | common_enums::BankNames::SporoPay
+ | common_enums::BankNames::TatraPay
+ | common_enums::BankNames::Viamo
+ | common_enums::BankNames::VolksbankGruppe
+ | common_enums::BankNames::VolkskreditbankAg
+ | common_enums::BankNames::VrBankBraunau
+ | common_enums::BankNames::UobBank
+ | common_enums::BankNames::PayWithAliorBank
+ | common_enums::BankNames::BankiSpoldzielcze
+ | common_enums::BankNames::PayWithInteligo
+ | common_enums::BankNames::BNPParibasPoland
+ | common_enums::BankNames::BankNowySA
+ | common_enums::BankNames::CreditAgricole
+ | common_enums::BankNames::PayWithBOS
+ | common_enums::BankNames::PayWithCitiHandlowy
+ | common_enums::BankNames::PayWithPlusBank
+ | common_enums::BankNames::ToyotaBank
+ | common_enums::BankNames::VeloBank
+ | common_enums::BankNames::ETransferPocztowy24
+ | common_enums::BankNames::PlusBank
+ | common_enums::BankNames::EtransferPocztowy24
+ | common_enums::BankNames::BankiSpbdzielcze
+ | common_enums::BankNames::BankNowyBfgSa
+ | common_enums::BankNames::GetinBank
+ | common_enums::BankNames::Blik
+ | common_enums::BankNames::NoblePay
+ | common_enums::BankNames::IdeaBank
+ | common_enums::BankNames::EnveloBank
+ | common_enums::BankNames::NestPrzelew
+ | common_enums::BankNames::MbankMtransfer
+ | common_enums::BankNames::Inteligo
+ | common_enums::BankNames::PbacZIpko
+ | common_enums::BankNames::BnpParibas
+ | common_enums::BankNames::BankPekaoSa
+ | common_enums::BankNames::VolkswagenBank
+ | common_enums::BankNames::AliorBank
+ | common_enums::BankNames::Boz
+ | common_enums::BankNames::BangkokBank
+ | common_enums::BankNames::KrungsriBank
+ | common_enums::BankNames::KrungThaiBank
+ | common_enums::BankNames::TheSiamCommercialBank
+ | common_enums::BankNames::Yoursafe
+ | common_enums::BankNames::N26
+ | common_enums::BankNames::NationaleNederlanden
+ | common_enums::BankNames::KasikornBank => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Adyen"),
+ ))?
+ }
}
}
}
@@ -1426,58 +1428,48 @@ pub enum OpenBankingUKIssuer {
pub struct AdyenTestBankNames<'a>(&'a str);
-impl<'a> TryFrom<&api_enums::BankNames> for AdyenTestBankNames<'a> {
+impl<'a> TryFrom<&common_enums::BankNames> for AdyenTestBankNames<'a> {
type Error = Error;
- fn try_from(bank: &api_enums::BankNames) -> Result<Self, Self::Error> {
+ fn try_from(bank: &common_enums::BankNames) -> Result<Self, Self::Error> {
Ok(match bank {
- api_models::enums::BankNames::AbnAmro => Self("1121"),
- api_models::enums::BankNames::AsnBank => Self("1151"),
- api_models::enums::BankNames::Bunq => Self("1152"),
- api_models::enums::BankNames::Ing => Self("1154"),
- api_models::enums::BankNames::Knab => Self("1155"),
- api_models::enums::BankNames::N26 => Self("1156"),
- api_models::enums::BankNames::NationaleNederlanden => Self("1157"),
- api_models::enums::BankNames::Rabobank => Self("1157"),
- api_models::enums::BankNames::Regiobank => Self("1158"),
- api_models::enums::BankNames::Revolut => Self("1159"),
- api_models::enums::BankNames::SnsBank => Self("1159"),
- api_models::enums::BankNames::TriodosBank => Self("1159"),
- api_models::enums::BankNames::VanLanschot => Self("1159"),
- api_models::enums::BankNames::Yoursafe => Self("1159"),
- api_models::enums::BankNames::BankAustria => {
- Self("e6819e7a-f663-414b-92ec-cf7c82d2f4e5")
- }
- api_models::enums::BankNames::BawagPskAg => {
- Self("ba7199cc-f057-42f2-9856-2378abf21638")
- }
- api_models::enums::BankNames::Dolomitenbank => {
- Self("d5d5b133-1c0d-4c08-b2be-3c9b116dc326")
- }
- api_models::enums::BankNames::EasybankAg => {
- Self("eff103e6-843d-48b7-a6e6-fbd88f511b11")
- }
- api_models::enums::BankNames::ErsteBankUndSparkassen => {
+ common_enums::BankNames::AbnAmro => Self("1121"),
+ common_enums::BankNames::AsnBank => Self("1151"),
+ common_enums::BankNames::Bunq => Self("1152"),
+ common_enums::BankNames::Ing => Self("1154"),
+ common_enums::BankNames::Knab => Self("1155"),
+ common_enums::BankNames::N26 => Self("1156"),
+ common_enums::BankNames::NationaleNederlanden => Self("1157"),
+ common_enums::BankNames::Rabobank => Self("1157"),
+ common_enums::BankNames::Regiobank => Self("1158"),
+ common_enums::BankNames::Revolut => Self("1159"),
+ common_enums::BankNames::SnsBank => Self("1159"),
+ common_enums::BankNames::TriodosBank => Self("1159"),
+ common_enums::BankNames::VanLanschot => Self("1159"),
+ common_enums::BankNames::Yoursafe => Self("1159"),
+ common_enums::BankNames::BankAustria => Self("e6819e7a-f663-414b-92ec-cf7c82d2f4e5"),
+ common_enums::BankNames::BawagPskAg => Self("ba7199cc-f057-42f2-9856-2378abf21638"),
+ common_enums::BankNames::Dolomitenbank => Self("d5d5b133-1c0d-4c08-b2be-3c9b116dc326"),
+ common_enums::BankNames::EasybankAg => Self("eff103e6-843d-48b7-a6e6-fbd88f511b11"),
+ common_enums::BankNames::ErsteBankUndSparkassen => {
Self("3fdc41fc-3d3d-4ee3-a1fe-cd79cfd58ea3")
}
- api_models::enums::BankNames::HypoTirolBankAg => {
+ common_enums::BankNames::HypoTirolBankAg => {
Self("6765e225-a0dc-4481-9666-e26303d4f221")
}
- api_models::enums::BankNames::PosojilnicaBankEGen => {
+ common_enums::BankNames::PosojilnicaBankEGen => {
Self("65ef4682-4944-499f-828f-5d74ad288376")
}
- api_models::enums::BankNames::RaiffeisenBankengruppeOsterreich => {
+ common_enums::BankNames::RaiffeisenBankengruppeOsterreich => {
Self("ee9fc487-ebe0-486c-8101-17dce5141a67")
}
- api_models::enums::BankNames::SchoellerbankAg => {
+ common_enums::BankNames::SchoellerbankAg => {
Self("1190c4d1-b37a-487e-9355-e0a067f54a9f")
}
- api_models::enums::BankNames::SpardaBankWien => {
- Self("8b0bfeea-fbb0-4337-b3a1-0e25c0f060fc")
- }
- api_models::enums::BankNames::VolksbankGruppe => {
+ common_enums::BankNames::SpardaBankWien => Self("8b0bfeea-fbb0-4337-b3a1-0e25c0f060fc"),
+ common_enums::BankNames::VolksbankGruppe => {
Self("e2e97aaa-de4c-4e18-9431-d99790773433")
}
- api_models::enums::BankNames::VolkskreditbankAg => {
+ common_enums::BankNames::VolkskreditbankAg => {
Self("4a0a975b-0594-4b40-9068-39f77b3a91f9")
}
_ => Err(errors::ConnectorError::NotImplemented(
@@ -1489,24 +1481,24 @@ impl<'a> TryFrom<&api_enums::BankNames> for AdyenTestBankNames<'a> {
pub struct AdyenBankNames<'a>(&'a str);
-impl<'a> TryFrom<&api_enums::BankNames> for AdyenBankNames<'a> {
+impl<'a> TryFrom<&common_enums::BankNames> for AdyenBankNames<'a> {
type Error = Error;
- fn try_from(bank: &api_enums::BankNames) -> Result<Self, Self::Error> {
+ fn try_from(bank: &common_enums::BankNames) -> Result<Self, Self::Error> {
Ok(match bank {
- api_models::enums::BankNames::AbnAmro => Self("0031"),
- api_models::enums::BankNames::AsnBank => Self("0761"),
- api_models::enums::BankNames::Bunq => Self("0802"),
- api_models::enums::BankNames::Ing => Self("0721"),
- api_models::enums::BankNames::Knab => Self("0801"),
- api_models::enums::BankNames::N26 => Self("0807"),
- api_models::enums::BankNames::NationaleNederlanden => Self("0808"),
- api_models::enums::BankNames::Rabobank => Self("0021"),
- api_models::enums::BankNames::Regiobank => Self("0771"),
- api_models::enums::BankNames::Revolut => Self("0805"),
- api_models::enums::BankNames::SnsBank => Self("0751"),
- api_models::enums::BankNames::TriodosBank => Self("0511"),
- api_models::enums::BankNames::VanLanschot => Self("0161"),
- api_models::enums::BankNames::Yoursafe => Self("0806"),
+ common_enums::BankNames::AbnAmro => Self("0031"),
+ common_enums::BankNames::AsnBank => Self("0761"),
+ common_enums::BankNames::Bunq => Self("0802"),
+ common_enums::BankNames::Ing => Self("0721"),
+ common_enums::BankNames::Knab => Self("0801"),
+ common_enums::BankNames::N26 => Self("0807"),
+ common_enums::BankNames::NationaleNederlanden => Self("0808"),
+ common_enums::BankNames::Rabobank => Self("0021"),
+ common_enums::BankNames::Regiobank => Self("0771"),
+ common_enums::BankNames::Revolut => Self("0805"),
+ common_enums::BankNames::SnsBank => Self("0751"),
+ common_enums::BankNames::TriodosBank => Self("0511"),
+ common_enums::BankNames::VanLanschot => Self("0161"),
+ common_enums::BankNames::Yoursafe => Self("0806"),
_ => Err(errors::ConnectorError::NotSupported {
message: String::from("BankRedirect"),
connector: "Adyen",
@@ -2264,15 +2256,13 @@ impl<'a>
}
}
-impl<'a> TryFrom<(&api_models::payments::BankRedirectData, Option<bool>)>
- for AdyenPaymentMethod<'a>
-{
+impl<'a> TryFrom<(&domain::BankRedirectData, Option<bool>)> for AdyenPaymentMethod<'a> {
type Error = Error;
fn try_from(
- (bank_redirect_data, test_mode): (&api_models::payments::BankRedirectData, Option<bool>),
+ (bank_redirect_data, test_mode): (&domain::BankRedirectData, Option<bool>),
) -> Result<Self, Self::Error> {
match bank_redirect_data {
- api_models::payments::BankRedirectData::BancontactCard {
+ domain::BankRedirectData::BancontactCard {
card_number,
card_exp_month,
card_exp_year,
@@ -2308,12 +2298,12 @@ impl<'a> TryFrom<(&api_models::payments::BankRedirectData, Option<bool>)>
.clone(),
},
))),
- api_models::payments::BankRedirectData::Bizum { .. } => {
+ domain::BankRedirectData::Bizum { .. } => {
Ok(AdyenPaymentMethod::Bizum(Box::new(PmdForPaymentType {
payment_type: PaymentType::Bizum,
})))
}
- api_models::payments::BankRedirectData::Blik { blik_code } => {
+ domain::BankRedirectData::Blik { blik_code } => {
Ok(AdyenPaymentMethod::Blik(Box::new(BlikRedirectionData {
payment_type: PaymentType::Blik,
blik_code: Secret::new(blik_code.clone().ok_or(
@@ -2323,8 +2313,8 @@ impl<'a> TryFrom<(&api_models::payments::BankRedirectData, Option<bool>)>
)?),
})))
}
- api_models::payments::BankRedirectData::Eps { bank_name, .. } => Ok(
- AdyenPaymentMethod::Eps(Box::new(BankRedirectionWithIssuer {
+ domain::BankRedirectData::Eps { bank_name, .. } => Ok(AdyenPaymentMethod::Eps(
+ Box::new(BankRedirectionWithIssuer {
payment_type: PaymentType::Eps,
issuer: Some(
AdyenTestBankNames::try_from(&bank_name.ok_or(
@@ -2334,14 +2324,14 @@ impl<'a> TryFrom<(&api_models::payments::BankRedirectData, Option<bool>)>
)?)?
.0,
),
- })),
- ),
- api_models::payments::BankRedirectData::Giropay { .. } => {
+ }),
+ )),
+ domain::BankRedirectData::Giropay { .. } => {
Ok(AdyenPaymentMethod::Giropay(Box::new(PmdForPaymentType {
payment_type: PaymentType::Giropay,
})))
}
- api_models::payments::BankRedirectData::Ideal { bank_name, .. } => {
+ domain::BankRedirectData::Ideal { bank_name, .. } => {
let issuer = if test_mode.unwrap_or(true) {
Some(
AdyenTestBankNames::try_from(&bank_name.ok_or(
@@ -2368,7 +2358,7 @@ impl<'a> TryFrom<(&api_models::payments::BankRedirectData, Option<bool>)>
},
)))
}
- api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { issuer } => {
+ domain::BankRedirectData::OnlineBankingCzechRepublic { issuer } => {
Ok(AdyenPaymentMethod::OnlineBankingCzechRepublic(Box::new(
OnlineBankingCzechRepublicData {
payment_type: PaymentType::OnlineBankingCzechRepublic,
@@ -2376,34 +2366,34 @@ impl<'a> TryFrom<(&api_models::payments::BankRedirectData, Option<bool>)>
},
)))
}
- api_models::payments::BankRedirectData::OnlineBankingFinland { .. } => Ok(
+ domain::BankRedirectData::OnlineBankingFinland { .. } => Ok(
AdyenPaymentMethod::OnlineBankingFinland(Box::new(PmdForPaymentType {
payment_type: PaymentType::OnlineBankingFinland,
})),
),
- api_models::payments::BankRedirectData::OnlineBankingPoland { issuer } => Ok(
+ domain::BankRedirectData::OnlineBankingPoland { issuer } => Ok(
AdyenPaymentMethod::OnlineBankingPoland(Box::new(OnlineBankingPolandData {
payment_type: PaymentType::OnlineBankingPoland,
issuer: OnlineBankingPolandBanks::try_from(issuer)?,
})),
),
- api_models::payments::BankRedirectData::OnlineBankingSlovakia { issuer } => Ok(
+ domain::BankRedirectData::OnlineBankingSlovakia { issuer } => Ok(
AdyenPaymentMethod::OnlineBankingSlovakia(Box::new(OnlineBankingSlovakiaData {
payment_type: PaymentType::OnlineBankingSlovakia,
issuer: OnlineBankingSlovakiaBanks::try_from(issuer)?,
})),
),
- api_models::payments::BankRedirectData::OnlineBankingFpx { issuer } => Ok(
+ domain::BankRedirectData::OnlineBankingFpx { issuer } => Ok(
AdyenPaymentMethod::OnlineBankingFpx(Box::new(OnlineBankingFpxData {
issuer: OnlineBankingFpxIssuer::try_from(issuer)?,
})),
),
- api_models::payments::BankRedirectData::OnlineBankingThailand { issuer } => Ok(
+ domain::BankRedirectData::OnlineBankingThailand { issuer } => Ok(
AdyenPaymentMethod::OnlineBankingThailand(Box::new(OnlineBankingThailandData {
issuer: OnlineBankingThailandIssuer::try_from(issuer)?,
})),
),
- api_models::payments::BankRedirectData::OpenBankingUk { issuer, .. } => Ok(
+ domain::BankRedirectData::OpenBankingUk { issuer, .. } => Ok(
AdyenPaymentMethod::OpenBankingUK(Box::new(OpenBankingUKData {
issuer: match issuer {
Some(bank_name) => OpenBankingUKIssuer::try_from(bank_name)?,
@@ -2413,12 +2403,10 @@ impl<'a> TryFrom<(&api_models::payments::BankRedirectData, Option<bool>)>
},
})),
),
- api_models::payments::BankRedirectData::Sofort { .. } => Ok(AdyenPaymentMethod::Sofort),
- api_models::payments::BankRedirectData::Trustly { .. } => {
- Ok(AdyenPaymentMethod::Trustly)
- }
- payments::BankRedirectData::Interac { .. }
- | payments::BankRedirectData::Przelewy24 { .. } => {
+ domain::BankRedirectData::Sofort { .. } => Ok(AdyenPaymentMethod::Sofort),
+ domain::BankRedirectData::Trustly { .. } => Ok(AdyenPaymentMethod::Trustly),
+ domain::BankRedirectData::Interac { .. }
+ | domain::BankRedirectData::Przelewy24 { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Adyen"),
)
@@ -2902,14 +2890,14 @@ impl<'a>
impl<'a>
TryFrom<(
&AdyenRouterData<&types::PaymentsAuthorizeRouterData>,
- &api_models::payments::BankRedirectData,
+ &domain::BankRedirectData,
)> for AdyenPaymentRequest<'a>
{
type Error = Error;
fn try_from(
value: (
&AdyenRouterData<&types::PaymentsAuthorizeRouterData>,
- &api_models::payments::BankRedirectData,
+ &domain::BankRedirectData,
),
) -> Result<Self, Self::Error> {
let (item, bank_redirect_data) = value;
@@ -2960,12 +2948,12 @@ fn get_redirect_extra_details(
) -> Result<(Option<String>, Option<api_enums::CountryAlpha2>), errors::ConnectorError> {
match item.request.payment_method_data {
domain::PaymentMethodData::BankRedirect(ref redirect_data) => match redirect_data {
- api_models::payments::BankRedirectData::Sofort {
+ domain::BankRedirectData::Sofort {
country,
preferred_language,
..
} => Ok((preferred_language.clone(), *country)),
- api_models::payments::BankRedirectData::OpenBankingUk { country, .. } => {
+ domain::BankRedirectData::OpenBankingUk { country, .. } => {
let country = country.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "country",
})?;
diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs
index b361aca79fa..cfb822715bf 100644
--- a/crates/router/src/connector/globalpay/transformers.rs
+++ b/crates/router/src/connector/globalpay/transformers.rs
@@ -462,22 +462,20 @@ fn get_wallet_data(wallet_data: &domain::WalletData) -> Result<PaymentMethodData
}
}
-impl TryFrom<&api_models::payments::BankRedirectData> for PaymentMethodData {
+impl TryFrom<&domain::BankRedirectData> for PaymentMethodData {
type Error = Error;
- fn try_from(value: &api_models::payments::BankRedirectData) -> Result<Self, Self::Error> {
+ fn try_from(value: &domain::BankRedirectData) -> Result<Self, Self::Error> {
match value {
- api_models::payments::BankRedirectData::Eps { .. } => Ok(Self::Apm(requests::Apm {
+ domain::BankRedirectData::Eps { .. } => Ok(Self::Apm(requests::Apm {
provider: Some(ApmProvider::Eps),
})),
- api_models::payments::BankRedirectData::Giropay { .. } => {
- Ok(Self::Apm(requests::Apm {
- provider: Some(ApmProvider::Giropay),
- }))
- }
- api_models::payments::BankRedirectData::Ideal { .. } => Ok(Self::Apm(requests::Apm {
+ domain::BankRedirectData::Giropay { .. } => Ok(Self::Apm(requests::Apm {
+ provider: Some(ApmProvider::Giropay),
+ })),
+ domain::BankRedirectData::Ideal { .. } => Ok(Self::Apm(requests::Apm {
provider: Some(ApmProvider::Ideal),
})),
- api_models::payments::BankRedirectData::Sofort { .. } => Ok(Self::Apm(requests::Apm {
+ domain::BankRedirectData::Sofort { .. } => Ok(Self::Apm(requests::Apm {
provider: Some(ApmProvider::Sofort),
})),
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
diff --git a/crates/router/src/connector/mollie/transformers.rs b/crates/router/src/connector/mollie/transformers.rs
index 68ea3ab5868..359320eb085 100644
--- a/crates/router/src/connector/mollie/transformers.rs
+++ b/crates/router/src/connector/mollie/transformers.rs
@@ -230,25 +230,25 @@ impl TryFrom<&MollieRouterData<&types::PaymentsAuthorizeRouterData>> for MollieP
}
}
-impl TryFrom<&api_models::payments::BankRedirectData> for PaymentMethodData {
+impl TryFrom<&domain::BankRedirectData> for PaymentMethodData {
type Error = Error;
- fn try_from(value: &api_models::payments::BankRedirectData) -> Result<Self, Self::Error> {
+ fn try_from(value: &domain::BankRedirectData) -> Result<Self, Self::Error> {
match value {
- api_models::payments::BankRedirectData::Eps { .. } => Ok(Self::Eps),
- api_models::payments::BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
- api_models::payments::BankRedirectData::Ideal { .. } => {
+ domain::BankRedirectData::Eps { .. } => Ok(Self::Eps),
+ domain::BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
+ domain::BankRedirectData::Ideal { .. } => {
Ok(Self::Ideal(Box::new(IdealMethodData {
// To do if possible this should be from the payment request
issuer: None,
})))
}
- api_models::payments::BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
- api_models::payments::BankRedirectData::Przelewy24 {
+ domain::BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
+ domain::BankRedirectData::Przelewy24 {
billing_details, ..
} => Ok(Self::Przelewy24(Box::new(Przelewy24MethodData {
billing_email: billing_details.email.clone(),
}))),
- api_models::payments::BankRedirectData::BancontactCard { .. } => Ok(Self::Bancontact),
+ domain::BankRedirectData::BancontactCard { .. } => Ok(Self::Bancontact),
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs
index 693e7671ec9..c6ef4ea1ba8 100644
--- a/crates/router/src/connector/nexinets/transformers.rs
+++ b/crates/router/src/connector/nexinets/transformers.rs
@@ -252,20 +252,20 @@ impl ForeignFrom<(NexinetsPaymentStatus, NexinetsTransactionType)> for enums::At
}
}
-impl TryFrom<&api_models::enums::BankNames> for NexinetsBIC {
+impl TryFrom<&common_enums::enums::BankNames> for NexinetsBIC {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(bank: &api_models::enums::BankNames) -> Result<Self, Self::Error> {
+ fn try_from(bank: &common_enums::enums::BankNames) -> Result<Self, Self::Error> {
match bank {
- api_models::enums::BankNames::AbnAmro => Ok(Self::AbnAmro),
- api_models::enums::BankNames::AsnBank => Ok(Self::AsnBank),
- api_models::enums::BankNames::Bunq => Ok(Self::Bunq),
- api_models::enums::BankNames::Ing => Ok(Self::Ing),
- api_models::enums::BankNames::Knab => Ok(Self::Knab),
- api_models::enums::BankNames::Rabobank => Ok(Self::Rabobank),
- api_models::enums::BankNames::Regiobank => Ok(Self::Regiobank),
- api_models::enums::BankNames::SnsBank => Ok(Self::SnsBank),
- api_models::enums::BankNames::TriodosBank => Ok(Self::TriodosBank),
- api_models::enums::BankNames::VanLanschot => Ok(Self::VanLanschot),
+ common_enums::enums::BankNames::AbnAmro => Ok(Self::AbnAmro),
+ common_enums::enums::BankNames::AsnBank => Ok(Self::AsnBank),
+ common_enums::enums::BankNames::Bunq => Ok(Self::Bunq),
+ common_enums::enums::BankNames::Ing => Ok(Self::Ing),
+ common_enums::enums::BankNames::Knab => Ok(Self::Knab),
+ common_enums::enums::BankNames::Rabobank => Ok(Self::Rabobank),
+ common_enums::enums::BankNames::Regiobank => Ok(Self::Regiobank),
+ common_enums::enums::BankNames::SnsBank => Ok(Self::SnsBank),
+ common_enums::enums::BankNames::TriodosBank => Ok(Self::TriodosBank),
+ common_enums::enums::BankNames::VanLanschot => Ok(Self::VanLanschot),
_ => Err(errors::ConnectorError::FlowNotSupported {
flow: bank.to_string(),
connector: "Nexinets".to_string(),
@@ -580,11 +580,9 @@ fn get_payment_details_and_product(
)),
PaymentMethodData::Wallet(wallet) => Ok(get_wallet_details(wallet)?),
PaymentMethodData::BankRedirect(bank_redirect) => match bank_redirect {
- api_models::payments::BankRedirectData::Eps { .. } => Ok((None, NexinetsProduct::Eps)),
- api_models::payments::BankRedirectData::Giropay { .. } => {
- Ok((None, NexinetsProduct::Giropay))
- }
- api_models::payments::BankRedirectData::Ideal { bank_name, .. } => Ok((
+ domain::BankRedirectData::Eps { .. } => Ok((None, NexinetsProduct::Eps)),
+ domain::BankRedirectData::Giropay { .. } => Ok((None, NexinetsProduct::Giropay)),
+ domain::BankRedirectData::Ideal { bank_name, .. } => Ok((
Some(NexinetsPaymentDetails::BankRedirects(Box::new(
NexinetsBankRedirects {
bic: bank_name
@@ -594,22 +592,20 @@ fn get_payment_details_and_product(
))),
NexinetsProduct::Ideal,
)),
- api_models::payments::BankRedirectData::Sofort { .. } => {
- Ok((None, NexinetsProduct::Sofort))
- }
- api_models::payments::BankRedirectData::BancontactCard { .. }
- | api_models::payments::BankRedirectData::Blik { .. }
- | api_models::payments::BankRedirectData::Bizum { .. }
- | api_models::payments::BankRedirectData::Interac { .. }
- | api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { .. }
- | api_models::payments::BankRedirectData::OnlineBankingFinland { .. }
- | api_models::payments::BankRedirectData::OnlineBankingPoland { .. }
- | api_models::payments::BankRedirectData::OnlineBankingSlovakia { .. }
- | api_models::payments::BankRedirectData::OpenBankingUk { .. }
- | api_models::payments::BankRedirectData::Przelewy24 { .. }
- | api_models::payments::BankRedirectData::Trustly { .. }
- | api_models::payments::BankRedirectData::OnlineBankingFpx { .. }
- | api_models::payments::BankRedirectData::OnlineBankingThailand { .. } => {
+ domain::BankRedirectData::Sofort { .. } => Ok((None, NexinetsProduct::Sofort)),
+ domain::BankRedirectData::BancontactCard { .. }
+ | domain::BankRedirectData::Blik { .. }
+ | domain::BankRedirectData::Bizum { .. }
+ | domain::BankRedirectData::Interac { .. }
+ | domain::BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | domain::BankRedirectData::OnlineBankingFinland { .. }
+ | domain::BankRedirectData::OnlineBankingPoland { .. }
+ | domain::BankRedirectData::OnlineBankingSlovakia { .. }
+ | domain::BankRedirectData::OpenBankingUk { .. }
+ | domain::BankRedirectData::Przelewy24 { .. }
+ | domain::BankRedirectData::Trustly { .. }
+ | domain::BankRedirectData::OnlineBankingFpx { .. }
+ | domain::BankRedirectData::OnlineBankingThailand { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nexinets"),
))?
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index 69df6cd8b0f..08c3b8fbc9f 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -1,4 +1,3 @@
-use api_models::payments;
use common_utils::{
crypto::{self, GenerateDigest},
date_time,
@@ -470,156 +469,156 @@ impl From<domain::ApplePayWalletData> for NuveiPaymentsRequest {
}
}
-impl TryFrom<api_models::enums::BankNames> for NuveiBIC {
+impl TryFrom<common_enums::enums::BankNames> for NuveiBIC {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(bank: api_models::enums::BankNames) -> Result<Self, Self::Error> {
+ fn try_from(bank: common_enums::enums::BankNames) -> Result<Self, Self::Error> {
match bank {
- api_models::enums::BankNames::AbnAmro => Ok(Self::Abnamro),
- api_models::enums::BankNames::AsnBank => Ok(Self::ASNBank),
- api_models::enums::BankNames::Bunq => Ok(Self::Bunq),
- api_models::enums::BankNames::Ing => Ok(Self::Ing),
- api_models::enums::BankNames::Knab => Ok(Self::Knab),
- api_models::enums::BankNames::Rabobank => Ok(Self::Rabobank),
- api_models::enums::BankNames::SnsBank => Ok(Self::SNSBank),
- api_models::enums::BankNames::TriodosBank => Ok(Self::TriodosBank),
- api_models::enums::BankNames::VanLanschot => Ok(Self::VanLanschotBankiers),
- api_models::enums::BankNames::Moneyou => Ok(Self::Moneyou),
-
- api_models::enums::BankNames::AmericanExpress
- | api_models::enums::BankNames::AffinBank
- | api_models::enums::BankNames::AgroBank
- | api_models::enums::BankNames::AllianceBank
- | api_models::enums::BankNames::AmBank
- | api_models::enums::BankNames::BankOfAmerica
- | api_models::enums::BankNames::BankIslam
- | api_models::enums::BankNames::BankMuamalat
- | api_models::enums::BankNames::BankRakyat
- | api_models::enums::BankNames::BankSimpananNasional
- | api_models::enums::BankNames::Barclays
- | api_models::enums::BankNames::BlikPSP
- | api_models::enums::BankNames::CapitalOne
- | api_models::enums::BankNames::Chase
- | api_models::enums::BankNames::Citi
- | api_models::enums::BankNames::CimbBank
- | api_models::enums::BankNames::Discover
- | api_models::enums::BankNames::NavyFederalCreditUnion
- | api_models::enums::BankNames::PentagonFederalCreditUnion
- | api_models::enums::BankNames::SynchronyBank
- | api_models::enums::BankNames::WellsFargo
- | api_models::enums::BankNames::Handelsbanken
- | api_models::enums::BankNames::HongLeongBank
- | api_models::enums::BankNames::HsbcBank
- | api_models::enums::BankNames::KuwaitFinanceHouse
- | api_models::enums::BankNames::Regiobank
- | api_models::enums::BankNames::Revolut
- | api_models::enums::BankNames::ArzteUndApothekerBank
- | api_models::enums::BankNames::AustrianAnadiBankAg
- | api_models::enums::BankNames::BankAustria
- | api_models::enums::BankNames::Bank99Ag
- | api_models::enums::BankNames::BankhausCarlSpangler
- | api_models::enums::BankNames::BankhausSchelhammerUndSchatteraAg
- | api_models::enums::BankNames::BankMillennium
- | api_models::enums::BankNames::BankPEKAOSA
- | api_models::enums::BankNames::BawagPskAg
- | api_models::enums::BankNames::BksBankAg
- | api_models::enums::BankNames::BrullKallmusBankAg
- | api_models::enums::BankNames::BtvVierLanderBank
- | api_models::enums::BankNames::CapitalBankGraweGruppeAg
- | api_models::enums::BankNames::CeskaSporitelna
- | api_models::enums::BankNames::Dolomitenbank
- | api_models::enums::BankNames::EasybankAg
- | api_models::enums::BankNames::EPlatbyVUB
- | api_models::enums::BankNames::ErsteBankUndSparkassen
- | api_models::enums::BankNames::FrieslandBank
- | api_models::enums::BankNames::HypoAlpeadriabankInternationalAg
- | api_models::enums::BankNames::HypoNoeLbFurNiederosterreichUWien
- | api_models::enums::BankNames::HypoOberosterreichSalzburgSteiermark
- | api_models::enums::BankNames::HypoTirolBankAg
- | api_models::enums::BankNames::HypoVorarlbergBankAg
- | api_models::enums::BankNames::HypoBankBurgenlandAktiengesellschaft
- | api_models::enums::BankNames::KomercniBanka
- | api_models::enums::BankNames::MBank
- | api_models::enums::BankNames::MarchfelderBank
- | api_models::enums::BankNames::Maybank
- | api_models::enums::BankNames::OberbankAg
- | api_models::enums::BankNames::OsterreichischeArzteUndApothekerbank
- | api_models::enums::BankNames::OcbcBank
- | api_models::enums::BankNames::PayWithING
- | api_models::enums::BankNames::PlaceZIPKO
- | api_models::enums::BankNames::PlatnoscOnlineKartaPlatnicza
- | api_models::enums::BankNames::PosojilnicaBankEGen
- | api_models::enums::BankNames::PostovaBanka
- | api_models::enums::BankNames::PublicBank
- | api_models::enums::BankNames::RaiffeisenBankengruppeOsterreich
- | api_models::enums::BankNames::RhbBank
- | api_models::enums::BankNames::SchelhammerCapitalBankAg
- | api_models::enums::BankNames::StandardCharteredBank
- | api_models::enums::BankNames::SchoellerbankAg
- | api_models::enums::BankNames::SpardaBankWien
- | api_models::enums::BankNames::SporoPay
- | api_models::enums::BankNames::SantanderPrzelew24
- | api_models::enums::BankNames::TatraPay
- | api_models::enums::BankNames::Viamo
- | api_models::enums::BankNames::VolksbankGruppe
- | api_models::enums::BankNames::VolkskreditbankAg
- | api_models::enums::BankNames::VrBankBraunau
- | api_models::enums::BankNames::UobBank
- | api_models::enums::BankNames::PayWithAliorBank
- | api_models::enums::BankNames::BankiSpoldzielcze
- | api_models::enums::BankNames::PayWithInteligo
- | api_models::enums::BankNames::BNPParibasPoland
- | api_models::enums::BankNames::BankNowySA
- | api_models::enums::BankNames::CreditAgricole
- | api_models::enums::BankNames::PayWithBOS
- | api_models::enums::BankNames::PayWithCitiHandlowy
- | api_models::enums::BankNames::PayWithPlusBank
- | api_models::enums::BankNames::ToyotaBank
- | api_models::enums::BankNames::VeloBank
- | api_models::enums::BankNames::ETransferPocztowy24
- | api_models::enums::BankNames::PlusBank
- | api_models::enums::BankNames::EtransferPocztowy24
- | api_models::enums::BankNames::BankiSpbdzielcze
- | api_models::enums::BankNames::BankNowyBfgSa
- | api_models::enums::BankNames::GetinBank
- | api_models::enums::BankNames::Blik
- | api_models::enums::BankNames::NoblePay
- | api_models::enums::BankNames::IdeaBank
- | api_models::enums::BankNames::EnveloBank
- | api_models::enums::BankNames::NestPrzelew
- | api_models::enums::BankNames::MbankMtransfer
- | api_models::enums::BankNames::Inteligo
- | api_models::enums::BankNames::PbacZIpko
- | api_models::enums::BankNames::BnpParibas
- | api_models::enums::BankNames::BankPekaoSa
- | api_models::enums::BankNames::VolkswagenBank
- | api_models::enums::BankNames::AliorBank
- | api_models::enums::BankNames::Boz
- | api_models::enums::BankNames::BangkokBank
- | api_models::enums::BankNames::KrungsriBank
- | api_models::enums::BankNames::KrungThaiBank
- | api_models::enums::BankNames::TheSiamCommercialBank
- | api_models::enums::BankNames::KasikornBank
- | api_models::enums::BankNames::OpenBankSuccess
- | api_models::enums::BankNames::OpenBankFailure
- | api_models::enums::BankNames::OpenBankCancelled
- | api_models::enums::BankNames::Aib
- | api_models::enums::BankNames::BankOfScotland
- | api_models::enums::BankNames::DanskeBank
- | api_models::enums::BankNames::FirstDirect
- | api_models::enums::BankNames::FirstTrust
- | api_models::enums::BankNames::Halifax
- | api_models::enums::BankNames::Lloyds
- | api_models::enums::BankNames::Monzo
- | api_models::enums::BankNames::NatWest
- | api_models::enums::BankNames::NationwideBank
- | api_models::enums::BankNames::RoyalBankOfScotland
- | api_models::enums::BankNames::Starling
- | api_models::enums::BankNames::TsbBank
- | api_models::enums::BankNames::TescoBank
- | api_models::enums::BankNames::Yoursafe
- | api_models::enums::BankNames::N26
- | api_models::enums::BankNames::NationaleNederlanden
- | api_models::enums::BankNames::UlsterBank => {
+ common_enums::enums::BankNames::AbnAmro => Ok(Self::Abnamro),
+ common_enums::enums::BankNames::AsnBank => Ok(Self::ASNBank),
+ common_enums::enums::BankNames::Bunq => Ok(Self::Bunq),
+ common_enums::enums::BankNames::Ing => Ok(Self::Ing),
+ common_enums::enums::BankNames::Knab => Ok(Self::Knab),
+ common_enums::enums::BankNames::Rabobank => Ok(Self::Rabobank),
+ common_enums::enums::BankNames::SnsBank => Ok(Self::SNSBank),
+ common_enums::enums::BankNames::TriodosBank => Ok(Self::TriodosBank),
+ common_enums::enums::BankNames::VanLanschot => Ok(Self::VanLanschotBankiers),
+ common_enums::enums::BankNames::Moneyou => Ok(Self::Moneyou),
+
+ common_enums::enums::BankNames::AmericanExpress
+ | common_enums::enums::BankNames::AffinBank
+ | common_enums::enums::BankNames::AgroBank
+ | common_enums::enums::BankNames::AllianceBank
+ | common_enums::enums::BankNames::AmBank
+ | common_enums::enums::BankNames::BankOfAmerica
+ | common_enums::enums::BankNames::BankIslam
+ | common_enums::enums::BankNames::BankMuamalat
+ | common_enums::enums::BankNames::BankRakyat
+ | common_enums::enums::BankNames::BankSimpananNasional
+ | common_enums::enums::BankNames::Barclays
+ | common_enums::enums::BankNames::BlikPSP
+ | common_enums::enums::BankNames::CapitalOne
+ | common_enums::enums::BankNames::Chase
+ | common_enums::enums::BankNames::Citi
+ | common_enums::enums::BankNames::CimbBank
+ | common_enums::enums::BankNames::Discover
+ | common_enums::enums::BankNames::NavyFederalCreditUnion
+ | common_enums::enums::BankNames::PentagonFederalCreditUnion
+ | common_enums::enums::BankNames::SynchronyBank
+ | common_enums::enums::BankNames::WellsFargo
+ | common_enums::enums::BankNames::Handelsbanken
+ | common_enums::enums::BankNames::HongLeongBank
+ | common_enums::enums::BankNames::HsbcBank
+ | common_enums::enums::BankNames::KuwaitFinanceHouse
+ | common_enums::enums::BankNames::Regiobank
+ | common_enums::enums::BankNames::Revolut
+ | common_enums::enums::BankNames::ArzteUndApothekerBank
+ | common_enums::enums::BankNames::AustrianAnadiBankAg
+ | common_enums::enums::BankNames::BankAustria
+ | common_enums::enums::BankNames::Bank99Ag
+ | common_enums::enums::BankNames::BankhausCarlSpangler
+ | common_enums::enums::BankNames::BankhausSchelhammerUndSchatteraAg
+ | common_enums::enums::BankNames::BankMillennium
+ | common_enums::enums::BankNames::BankPEKAOSA
+ | common_enums::enums::BankNames::BawagPskAg
+ | common_enums::enums::BankNames::BksBankAg
+ | common_enums::enums::BankNames::BrullKallmusBankAg
+ | common_enums::enums::BankNames::BtvVierLanderBank
+ | common_enums::enums::BankNames::CapitalBankGraweGruppeAg
+ | common_enums::enums::BankNames::CeskaSporitelna
+ | common_enums::enums::BankNames::Dolomitenbank
+ | common_enums::enums::BankNames::EasybankAg
+ | common_enums::enums::BankNames::EPlatbyVUB
+ | common_enums::enums::BankNames::ErsteBankUndSparkassen
+ | common_enums::enums::BankNames::FrieslandBank
+ | common_enums::enums::BankNames::HypoAlpeadriabankInternationalAg
+ | common_enums::enums::BankNames::HypoNoeLbFurNiederosterreichUWien
+ | common_enums::enums::BankNames::HypoOberosterreichSalzburgSteiermark
+ | common_enums::enums::BankNames::HypoTirolBankAg
+ | common_enums::enums::BankNames::HypoVorarlbergBankAg
+ | common_enums::enums::BankNames::HypoBankBurgenlandAktiengesellschaft
+ | common_enums::enums::BankNames::KomercniBanka
+ | common_enums::enums::BankNames::MBank
+ | common_enums::enums::BankNames::MarchfelderBank
+ | common_enums::enums::BankNames::Maybank
+ | common_enums::enums::BankNames::OberbankAg
+ | common_enums::enums::BankNames::OsterreichischeArzteUndApothekerbank
+ | common_enums::enums::BankNames::OcbcBank
+ | common_enums::enums::BankNames::PayWithING
+ | common_enums::enums::BankNames::PlaceZIPKO
+ | common_enums::enums::BankNames::PlatnoscOnlineKartaPlatnicza
+ | common_enums::enums::BankNames::PosojilnicaBankEGen
+ | common_enums::enums::BankNames::PostovaBanka
+ | common_enums::enums::BankNames::PublicBank
+ | common_enums::enums::BankNames::RaiffeisenBankengruppeOsterreich
+ | common_enums::enums::BankNames::RhbBank
+ | common_enums::enums::BankNames::SchelhammerCapitalBankAg
+ | common_enums::enums::BankNames::StandardCharteredBank
+ | common_enums::enums::BankNames::SchoellerbankAg
+ | common_enums::enums::BankNames::SpardaBankWien
+ | common_enums::enums::BankNames::SporoPay
+ | common_enums::enums::BankNames::SantanderPrzelew24
+ | common_enums::enums::BankNames::TatraPay
+ | common_enums::enums::BankNames::Viamo
+ | common_enums::enums::BankNames::VolksbankGruppe
+ | common_enums::enums::BankNames::VolkskreditbankAg
+ | common_enums::enums::BankNames::VrBankBraunau
+ | common_enums::enums::BankNames::UobBank
+ | common_enums::enums::BankNames::PayWithAliorBank
+ | common_enums::enums::BankNames::BankiSpoldzielcze
+ | common_enums::enums::BankNames::PayWithInteligo
+ | common_enums::enums::BankNames::BNPParibasPoland
+ | common_enums::enums::BankNames::BankNowySA
+ | common_enums::enums::BankNames::CreditAgricole
+ | common_enums::enums::BankNames::PayWithBOS
+ | common_enums::enums::BankNames::PayWithCitiHandlowy
+ | common_enums::enums::BankNames::PayWithPlusBank
+ | common_enums::enums::BankNames::ToyotaBank
+ | common_enums::enums::BankNames::VeloBank
+ | common_enums::enums::BankNames::ETransferPocztowy24
+ | common_enums::enums::BankNames::PlusBank
+ | common_enums::enums::BankNames::EtransferPocztowy24
+ | common_enums::enums::BankNames::BankiSpbdzielcze
+ | common_enums::enums::BankNames::BankNowyBfgSa
+ | common_enums::enums::BankNames::GetinBank
+ | common_enums::enums::BankNames::Blik
+ | common_enums::enums::BankNames::NoblePay
+ | common_enums::enums::BankNames::IdeaBank
+ | common_enums::enums::BankNames::EnveloBank
+ | common_enums::enums::BankNames::NestPrzelew
+ | common_enums::enums::BankNames::MbankMtransfer
+ | common_enums::enums::BankNames::Inteligo
+ | common_enums::enums::BankNames::PbacZIpko
+ | common_enums::enums::BankNames::BnpParibas
+ | common_enums::enums::BankNames::BankPekaoSa
+ | common_enums::enums::BankNames::VolkswagenBank
+ | common_enums::enums::BankNames::AliorBank
+ | common_enums::enums::BankNames::Boz
+ | common_enums::enums::BankNames::BangkokBank
+ | common_enums::enums::BankNames::KrungsriBank
+ | common_enums::enums::BankNames::KrungThaiBank
+ | common_enums::enums::BankNames::TheSiamCommercialBank
+ | common_enums::enums::BankNames::KasikornBank
+ | common_enums::enums::BankNames::OpenBankSuccess
+ | common_enums::enums::BankNames::OpenBankFailure
+ | common_enums::enums::BankNames::OpenBankCancelled
+ | common_enums::enums::BankNames::Aib
+ | common_enums::enums::BankNames::BankOfScotland
+ | common_enums::enums::BankNames::DanskeBank
+ | common_enums::enums::BankNames::FirstDirect
+ | common_enums::enums::BankNames::FirstTrust
+ | common_enums::enums::BankNames::Halifax
+ | common_enums::enums::BankNames::Lloyds
+ | common_enums::enums::BankNames::Monzo
+ | common_enums::enums::BankNames::NatWest
+ | common_enums::enums::BankNames::NationwideBank
+ | common_enums::enums::BankNames::RoyalBankOfScotland
+ | common_enums::enums::BankNames::Starling
+ | common_enums::enums::BankNames::TsbBank
+ | common_enums::enums::BankNames::TescoBank
+ | common_enums::enums::BankNames::Yoursafe
+ | common_enums::enums::BankNames::N26
+ | common_enums::enums::BankNames::NationaleNederlanden
+ | common_enums::enums::BankNames::UlsterBank => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Nuvei"),
))?
@@ -631,7 +630,7 @@ impl TryFrom<api_models::enums::BankNames> for NuveiBIC {
impl<F>
ForeignTryFrom<(
AlternativePaymentMethodType,
- Option<payments::BankRedirectData>,
+ Option<domain::BankRedirectData>,
&types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
)> for NuveiPaymentsRequest
{
@@ -639,7 +638,7 @@ impl<F>
fn foreign_try_from(
data: (
AlternativePaymentMethodType,
- Option<payments::BankRedirectData>,
+ Option<domain::BankRedirectData>,
&types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
),
) -> Result<Self, Self::Error> {
@@ -675,7 +674,7 @@ impl<F>
}
(
AlternativePaymentMethodType::Ideal,
- Some(payments::BankRedirectData::Ideal { bank_name, .. }),
+ Some(domain::BankRedirectData::Ideal { bank_name, .. }),
) => {
let address = item.get_billing_address()?;
(
@@ -789,39 +788,39 @@ impl<F>
}
},
domain::PaymentMethodData::BankRedirect(redirect) => match redirect {
- payments::BankRedirectData::Eps { .. } => Self::foreign_try_from((
+ domain::BankRedirectData::Eps { .. } => Self::foreign_try_from((
AlternativePaymentMethodType::Eps,
Some(redirect),
item,
)),
- payments::BankRedirectData::Giropay { .. } => Self::foreign_try_from((
+ domain::BankRedirectData::Giropay { .. } => Self::foreign_try_from((
AlternativePaymentMethodType::Giropay,
Some(redirect),
item,
)),
- payments::BankRedirectData::Ideal { .. } => Self::foreign_try_from((
+ domain::BankRedirectData::Ideal { .. } => Self::foreign_try_from((
AlternativePaymentMethodType::Ideal,
Some(redirect),
item,
)),
- payments::BankRedirectData::Sofort { .. } => Self::foreign_try_from((
+ domain::BankRedirectData::Sofort { .. } => Self::foreign_try_from((
AlternativePaymentMethodType::Sofort,
Some(redirect),
item,
)),
- payments::BankRedirectData::BancontactCard { .. }
- | payments::BankRedirectData::Bizum {}
- | payments::BankRedirectData::Blik { .. }
- | payments::BankRedirectData::Interac { .. }
- | payments::BankRedirectData::OnlineBankingCzechRepublic { .. }
- | payments::BankRedirectData::OnlineBankingFinland { .. }
- | payments::BankRedirectData::OnlineBankingPoland { .. }
- | payments::BankRedirectData::OnlineBankingSlovakia { .. }
- | payments::BankRedirectData::Przelewy24 { .. }
- | payments::BankRedirectData::Trustly { .. }
- | payments::BankRedirectData::OnlineBankingFpx { .. }
- | payments::BankRedirectData::OnlineBankingThailand { .. }
- | payments::BankRedirectData::OpenBankingUk { .. } => {
+ domain::BankRedirectData::BancontactCard { .. }
+ | domain::BankRedirectData::Bizum {}
+ | domain::BankRedirectData::Blik { .. }
+ | domain::BankRedirectData::Interac { .. }
+ | domain::BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | domain::BankRedirectData::OnlineBankingFinland { .. }
+ | domain::BankRedirectData::OnlineBankingPoland { .. }
+ | domain::BankRedirectData::OnlineBankingSlovakia { .. }
+ | domain::BankRedirectData::Przelewy24 { .. }
+ | domain::BankRedirectData::Trustly { .. }
+ | domain::BankRedirectData::OnlineBankingFpx { .. }
+ | domain::BankRedirectData::OnlineBankingThailand { .. }
+ | domain::BankRedirectData::OpenBankingUk { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nuvei"),
)
diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs
index 0fb3f64ec05..64ff7db2a89 100644
--- a/crates/router/src/connector/paypal/transformers.rs
+++ b/crates/router/src/connector/paypal/transformers.rs
@@ -1,4 +1,4 @@
-use api_models::{enums, payments::BankRedirectData};
+use api_models::enums;
use base64::Engine;
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
@@ -280,10 +280,10 @@ fn get_address_info(
}
fn get_payment_source(
item: &types::PaymentsAuthorizeRouterData,
- bank_redirection_data: &BankRedirectData,
+ bank_redirection_data: &domain::BankRedirectData,
) -> Result<PaymentSourceItem, error_stack::Report<errors::ConnectorError>> {
match bank_redirection_data {
- BankRedirectData::Eps {
+ domain::BankRedirectData::Eps {
billing_details,
bank_name: _,
country,
@@ -308,7 +308,7 @@ fn get_payment_source(
user_action: Some(UserAction::PayNow),
},
})),
- BankRedirectData::Giropay {
+ domain::BankRedirectData::Giropay {
billing_details,
country,
..
@@ -333,7 +333,7 @@ fn get_payment_source(
user_action: Some(UserAction::PayNow),
},
})),
- BankRedirectData::Ideal {
+ domain::BankRedirectData::Ideal {
billing_details,
bank_name: _,
country,
@@ -358,7 +358,7 @@ fn get_payment_source(
user_action: Some(UserAction::PayNow),
},
})),
- BankRedirectData::Sofort {
+ domain::BankRedirectData::Sofort {
country,
preferred_language: _,
billing_details,
@@ -383,22 +383,24 @@ fn get_payment_source(
user_action: Some(UserAction::PayNow),
},
})),
- BankRedirectData::BancontactCard { .. }
- | BankRedirectData::Blik { .. }
- | BankRedirectData::Przelewy24 { .. } => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Paypal"),
- )
- .into()),
- BankRedirectData::Bizum {}
- | BankRedirectData::Interac { .. }
- | BankRedirectData::OnlineBankingCzechRepublic { .. }
- | BankRedirectData::OnlineBankingFinland { .. }
- | BankRedirectData::OnlineBankingPoland { .. }
- | BankRedirectData::OnlineBankingSlovakia { .. }
- | BankRedirectData::OpenBankingUk { .. }
- | BankRedirectData::Trustly { .. }
- | BankRedirectData::OnlineBankingFpx { .. }
- | BankRedirectData::OnlineBankingThailand { .. } => {
+ domain::BankRedirectData::BancontactCard { .. }
+ | domain::BankRedirectData::Blik { .. }
+ | domain::BankRedirectData::Przelewy24 { .. } => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Paypal"),
+ )
+ .into())
+ }
+ domain::BankRedirectData::Bizum {}
+ | domain::BankRedirectData::Interac { .. }
+ | domain::BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | domain::BankRedirectData::OnlineBankingFinland { .. }
+ | domain::BankRedirectData::OnlineBankingPoland { .. }
+ | domain::BankRedirectData::OnlineBankingSlovakia { .. }
+ | domain::BankRedirectData::OpenBankingUk { .. }
+ | domain::BankRedirectData::Trustly { .. }
+ | domain::BankRedirectData::OnlineBankingFpx { .. }
+ | domain::BankRedirectData::OnlineBankingThailand { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
))?
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs
index 924081da4a9..bb46a207df4 100644
--- a/crates/router/src/connector/shift4/transformers.rs
+++ b/crates/router/src/connector/shift4/transformers.rs
@@ -324,14 +324,14 @@ impl<T>
impl<T>
TryFrom<(
&types::RouterData<T, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
- &payments::BankRedirectData,
+ &domain::BankRedirectData,
)> for Shift4PaymentMethod
{
type Error = Error;
fn try_from(
(item, redirect_data): (
&types::RouterData<T, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
- &payments::BankRedirectData,
+ &domain::BankRedirectData,
),
) -> Result<Self, Self::Error> {
let flow = Flow::try_from(&item.request.router_return_url)?;
@@ -392,27 +392,27 @@ impl<T> TryFrom<&types::RouterData<T, types::CompleteAuthorizeData, types::Payme
}
}
-impl TryFrom<&payments::BankRedirectData> for PaymentMethodType {
+impl TryFrom<&domain::BankRedirectData> for PaymentMethodType {
type Error = Error;
- fn try_from(value: &payments::BankRedirectData) -> Result<Self, Self::Error> {
+ fn try_from(value: &domain::BankRedirectData) -> Result<Self, Self::Error> {
match value {
- payments::BankRedirectData::Eps { .. } => Ok(Self::Eps),
- payments::BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
- payments::BankRedirectData::Ideal { .. } => Ok(Self::Ideal),
- payments::BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
- payments::BankRedirectData::BancontactCard { .. }
- | payments::BankRedirectData::Blik { .. }
- | payments::BankRedirectData::Trustly { .. }
- | payments::BankRedirectData::Przelewy24 { .. }
- | payments::BankRedirectData::Bizum {}
- | payments::BankRedirectData::Interac { .. }
- | payments::BankRedirectData::OnlineBankingCzechRepublic { .. }
- | payments::BankRedirectData::OnlineBankingFinland { .. }
- | payments::BankRedirectData::OnlineBankingPoland { .. }
- | payments::BankRedirectData::OnlineBankingSlovakia { .. }
- | payments::BankRedirectData::OpenBankingUk { .. }
- | payments::BankRedirectData::OnlineBankingFpx { .. }
- | payments::BankRedirectData::OnlineBankingThailand { .. } => {
+ domain::BankRedirectData::Eps { .. } => Ok(Self::Eps),
+ domain::BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
+ domain::BankRedirectData::Ideal { .. } => Ok(Self::Ideal),
+ domain::BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
+ domain::BankRedirectData::BancontactCard { .. }
+ | domain::BankRedirectData::Blik { .. }
+ | domain::BankRedirectData::Trustly { .. }
+ | domain::BankRedirectData::Przelewy24 { .. }
+ | domain::BankRedirectData::Bizum {}
+ | domain::BankRedirectData::Interac { .. }
+ | domain::BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | domain::BankRedirectData::OnlineBankingFinland { .. }
+ | domain::BankRedirectData::OnlineBankingPoland { .. }
+ | domain::BankRedirectData::OnlineBankingSlovakia { .. }
+ | domain::BankRedirectData::OpenBankingUk { .. }
+ | domain::BankRedirectData::OnlineBankingFpx { .. }
+ | domain::BankRedirectData::OnlineBankingThailand { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 1f6c2bcad12..a73e1045cfc 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -814,84 +814,84 @@ impl From<WebhookEventStatus> for api_models::webhooks::IncomingWebhookEvent {
}
}
-impl TryFrom<&api_models::enums::BankNames> for StripeBankNames {
+impl TryFrom<&common_enums::enums::BankNames> for StripeBankNames {
type Error = errors::ConnectorError;
- fn try_from(bank: &api_models::enums::BankNames) -> Result<Self, Self::Error> {
+ fn try_from(bank: &common_enums::enums::BankNames) -> Result<Self, Self::Error> {
Ok(match bank {
- api_models::enums::BankNames::AbnAmro => Self::AbnAmro,
- api_models::enums::BankNames::ArzteUndApothekerBank => Self::ArzteUndApothekerBank,
- api_models::enums::BankNames::AsnBank => Self::AsnBank,
- api_models::enums::BankNames::AustrianAnadiBankAg => Self::AustrianAnadiBankAg,
- api_models::enums::BankNames::BankAustria => Self::BankAustria,
- api_models::enums::BankNames::BankhausCarlSpangler => Self::BankhausCarlSpangler,
- api_models::enums::BankNames::BankhausSchelhammerUndSchatteraAg => {
+ common_enums::enums::BankNames::AbnAmro => Self::AbnAmro,
+ common_enums::enums::BankNames::ArzteUndApothekerBank => Self::ArzteUndApothekerBank,
+ common_enums::enums::BankNames::AsnBank => Self::AsnBank,
+ common_enums::enums::BankNames::AustrianAnadiBankAg => Self::AustrianAnadiBankAg,
+ common_enums::enums::BankNames::BankAustria => Self::BankAustria,
+ common_enums::enums::BankNames::BankhausCarlSpangler => Self::BankhausCarlSpangler,
+ common_enums::enums::BankNames::BankhausSchelhammerUndSchatteraAg => {
Self::BankhausSchelhammerUndSchatteraAg
}
- api_models::enums::BankNames::BawagPskAg => Self::BawagPskAg,
- api_models::enums::BankNames::BksBankAg => Self::BksBankAg,
- api_models::enums::BankNames::BrullKallmusBankAg => Self::BrullKallmusBankAg,
- api_models::enums::BankNames::BtvVierLanderBank => Self::BtvVierLanderBank,
- api_models::enums::BankNames::Bunq => Self::Bunq,
- api_models::enums::BankNames::CapitalBankGraweGruppeAg => {
+ common_enums::enums::BankNames::BawagPskAg => Self::BawagPskAg,
+ common_enums::enums::BankNames::BksBankAg => Self::BksBankAg,
+ common_enums::enums::BankNames::BrullKallmusBankAg => Self::BrullKallmusBankAg,
+ common_enums::enums::BankNames::BtvVierLanderBank => Self::BtvVierLanderBank,
+ common_enums::enums::BankNames::Bunq => Self::Bunq,
+ common_enums::enums::BankNames::CapitalBankGraweGruppeAg => {
Self::CapitalBankGraweGruppeAg
}
- api_models::enums::BankNames::Citi => Self::CitiHandlowy,
- api_models::enums::BankNames::Dolomitenbank => Self::Dolomitenbank,
- api_models::enums::BankNames::EasybankAg => Self::EasybankAg,
- api_models::enums::BankNames::ErsteBankUndSparkassen => Self::ErsteBankUndSparkassen,
- api_models::enums::BankNames::Handelsbanken => Self::Handelsbanken,
- api_models::enums::BankNames::HypoAlpeadriabankInternationalAg => {
+ common_enums::enums::BankNames::Citi => Self::CitiHandlowy,
+ common_enums::enums::BankNames::Dolomitenbank => Self::Dolomitenbank,
+ common_enums::enums::BankNames::EasybankAg => Self::EasybankAg,
+ common_enums::enums::BankNames::ErsteBankUndSparkassen => Self::ErsteBankUndSparkassen,
+ common_enums::enums::BankNames::Handelsbanken => Self::Handelsbanken,
+ common_enums::enums::BankNames::HypoAlpeadriabankInternationalAg => {
Self::HypoAlpeadriabankInternationalAg
}
- api_models::enums::BankNames::HypoNoeLbFurNiederosterreichUWien => {
+ common_enums::enums::BankNames::HypoNoeLbFurNiederosterreichUWien => {
Self::HypoNoeLbFurNiederosterreichUWien
}
- api_models::enums::BankNames::HypoOberosterreichSalzburgSteiermark => {
+ common_enums::enums::BankNames::HypoOberosterreichSalzburgSteiermark => {
Self::HypoOberosterreichSalzburgSteiermark
}
- api_models::enums::BankNames::HypoTirolBankAg => Self::HypoTirolBankAg,
- api_models::enums::BankNames::HypoVorarlbergBankAg => Self::HypoVorarlbergBankAg,
- api_models::enums::BankNames::HypoBankBurgenlandAktiengesellschaft => {
+ common_enums::enums::BankNames::HypoTirolBankAg => Self::HypoTirolBankAg,
+ common_enums::enums::BankNames::HypoVorarlbergBankAg => Self::HypoVorarlbergBankAg,
+ common_enums::enums::BankNames::HypoBankBurgenlandAktiengesellschaft => {
Self::HypoBankBurgenlandAktiengesellschaft
}
- api_models::enums::BankNames::Ing => Self::Ing,
- api_models::enums::BankNames::Knab => Self::Knab,
- api_models::enums::BankNames::MarchfelderBank => Self::MarchfelderBank,
- api_models::enums::BankNames::OberbankAg => Self::OberbankAg,
- api_models::enums::BankNames::RaiffeisenBankengruppeOsterreich => {
+ common_enums::enums::BankNames::Ing => Self::Ing,
+ common_enums::enums::BankNames::Knab => Self::Knab,
+ common_enums::enums::BankNames::MarchfelderBank => Self::MarchfelderBank,
+ common_enums::enums::BankNames::OberbankAg => Self::OberbankAg,
+ common_enums::enums::BankNames::RaiffeisenBankengruppeOsterreich => {
Self::RaiffeisenBankengruppeOsterreich
}
- api_models::enums::BankNames::Rabobank => Self::Rabobank,
- api_models::enums::BankNames::Regiobank => Self::Regiobank,
- api_models::enums::BankNames::Revolut => Self::Revolut,
- api_models::enums::BankNames::SnsBank => Self::SnsBank,
- api_models::enums::BankNames::TriodosBank => Self::TriodosBank,
- api_models::enums::BankNames::VanLanschot => Self::VanLanschot,
- api_models::enums::BankNames::Moneyou => Self::Moneyou,
- api_models::enums::BankNames::SchoellerbankAg => Self::SchoellerbankAg,
- api_models::enums::BankNames::SpardaBankWien => Self::SpardaBankWien,
- api_models::enums::BankNames::VolksbankGruppe => Self::VolksbankGruppe,
- api_models::enums::BankNames::VolkskreditbankAg => Self::VolkskreditbankAg,
- api_models::enums::BankNames::VrBankBraunau => Self::VrBankBraunau,
- api_models::enums::BankNames::PlusBank => Self::PlusBank,
- api_models::enums::BankNames::EtransferPocztowy24 => Self::EtransferPocztowy24,
- api_models::enums::BankNames::BankiSpbdzielcze => Self::BankiSpbdzielcze,
- api_models::enums::BankNames::BankNowyBfgSa => Self::BankNowyBfgSa,
- api_models::enums::BankNames::GetinBank => Self::GetinBank,
- api_models::enums::BankNames::Blik => Self::Blik,
- api_models::enums::BankNames::NoblePay => Self::NoblePay,
- api_models::enums::BankNames::IdeaBank => Self::IdeaBank,
- api_models::enums::BankNames::EnveloBank => Self::EnveloBank,
- api_models::enums::BankNames::NestPrzelew => Self::NestPrzelew,
- api_models::enums::BankNames::MbankMtransfer => Self::MbankMtransfer,
- api_models::enums::BankNames::Inteligo => Self::Inteligo,
- api_models::enums::BankNames::PbacZIpko => Self::PbacZIpko,
- api_models::enums::BankNames::BnpParibas => Self::BnpParibas,
- api_models::enums::BankNames::BankPekaoSa => Self::BankPekaoSa,
- api_models::enums::BankNames::VolkswagenBank => Self::VolkswagenBank,
- api_models::enums::BankNames::AliorBank => Self::AliorBank,
- api_models::enums::BankNames::Boz => Self::Boz,
+ common_enums::enums::BankNames::Rabobank => Self::Rabobank,
+ common_enums::enums::BankNames::Regiobank => Self::Regiobank,
+ common_enums::enums::BankNames::Revolut => Self::Revolut,
+ common_enums::enums::BankNames::SnsBank => Self::SnsBank,
+ common_enums::enums::BankNames::TriodosBank => Self::TriodosBank,
+ common_enums::enums::BankNames::VanLanschot => Self::VanLanschot,
+ common_enums::enums::BankNames::Moneyou => Self::Moneyou,
+ common_enums::enums::BankNames::SchoellerbankAg => Self::SchoellerbankAg,
+ common_enums::enums::BankNames::SpardaBankWien => Self::SpardaBankWien,
+ common_enums::enums::BankNames::VolksbankGruppe => Self::VolksbankGruppe,
+ common_enums::enums::BankNames::VolkskreditbankAg => Self::VolkskreditbankAg,
+ common_enums::enums::BankNames::VrBankBraunau => Self::VrBankBraunau,
+ common_enums::enums::BankNames::PlusBank => Self::PlusBank,
+ common_enums::enums::BankNames::EtransferPocztowy24 => Self::EtransferPocztowy24,
+ common_enums::enums::BankNames::BankiSpbdzielcze => Self::BankiSpbdzielcze,
+ common_enums::enums::BankNames::BankNowyBfgSa => Self::BankNowyBfgSa,
+ common_enums::enums::BankNames::GetinBank => Self::GetinBank,
+ common_enums::enums::BankNames::Blik => Self::Blik,
+ common_enums::enums::BankNames::NoblePay => Self::NoblePay,
+ common_enums::enums::BankNames::IdeaBank => Self::IdeaBank,
+ common_enums::enums::BankNames::EnveloBank => Self::EnveloBank,
+ common_enums::enums::BankNames::NestPrzelew => Self::NestPrzelew,
+ common_enums::enums::BankNames::MbankMtransfer => Self::MbankMtransfer,
+ common_enums::enums::BankNames::Inteligo => Self::Inteligo,
+ common_enums::enums::BankNames::PbacZIpko => Self::PbacZIpko,
+ common_enums::enums::BankNames::BnpParibas => Self::BnpParibas,
+ common_enums::enums::BankNames::BankPekaoSa => Self::BankPekaoSa,
+ common_enums::enums::BankNames::VolkswagenBank => Self::VolkswagenBank,
+ common_enums::enums::BankNames::AliorBank => Self::AliorBank,
+ common_enums::enums::BankNames::Boz => Self::Boz,
_ => Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("stripe"),
@@ -953,31 +953,31 @@ impl TryFrom<&domain::payments::PayLaterData> for StripePaymentMethodType {
}
}
-impl TryFrom<&payments::BankRedirectData> for StripePaymentMethodType {
+impl TryFrom<&domain::BankRedirectData> for StripePaymentMethodType {
type Error = errors::ConnectorError;
- fn try_from(bank_redirect_data: &payments::BankRedirectData) -> Result<Self, Self::Error> {
+ fn try_from(bank_redirect_data: &domain::BankRedirectData) -> Result<Self, Self::Error> {
match bank_redirect_data {
- payments::BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
- payments::BankRedirectData::Ideal { .. } => Ok(Self::Ideal),
- payments::BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
- payments::BankRedirectData::BancontactCard { .. } => Ok(Self::Bancontact),
- payments::BankRedirectData::Przelewy24 { .. } => Ok(Self::Przelewy24),
- payments::BankRedirectData::Eps { .. } => Ok(Self::Eps),
- payments::BankRedirectData::Blik { .. } => Ok(Self::Blik),
- payments::BankRedirectData::OnlineBankingFpx { .. } => {
+ domain::BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
+ domain::BankRedirectData::Ideal { .. } => Ok(Self::Ideal),
+ domain::BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
+ domain::BankRedirectData::BancontactCard { .. } => Ok(Self::Bancontact),
+ domain::BankRedirectData::Przelewy24 { .. } => Ok(Self::Przelewy24),
+ domain::BankRedirectData::Eps { .. } => Ok(Self::Eps),
+ domain::BankRedirectData::Blik { .. } => Ok(Self::Blik),
+ domain::BankRedirectData::OnlineBankingFpx { .. } => {
Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("stripe"),
))
}
- payments::BankRedirectData::Bizum {}
- | payments::BankRedirectData::Interac { .. }
- | payments::BankRedirectData::OnlineBankingCzechRepublic { .. }
- | payments::BankRedirectData::OnlineBankingFinland { .. }
- | payments::BankRedirectData::OnlineBankingPoland { .. }
- | payments::BankRedirectData::OnlineBankingSlovakia { .. }
- | payments::BankRedirectData::OnlineBankingThailand { .. }
- | payments::BankRedirectData::OpenBankingUk { .. }
- | payments::BankRedirectData::Trustly { .. } => {
+ domain::BankRedirectData::Bizum {}
+ | domain::BankRedirectData::Interac { .. }
+ | domain::BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | domain::BankRedirectData::OnlineBankingFinland { .. }
+ | domain::BankRedirectData::OnlineBankingPoland { .. }
+ | domain::BankRedirectData::OnlineBankingSlovakia { .. }
+ | domain::BankRedirectData::OnlineBankingThailand { .. }
+ | domain::BankRedirectData::OpenBankingUk { .. }
+ | domain::BankRedirectData::Trustly { .. } => {
Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("stripe"),
))
@@ -1108,17 +1108,17 @@ impl From<&payments::BankDebitBilling> for StripeBillingAddress {
}
}
-impl TryFrom<(&payments::BankRedirectData, Option<bool>)> for StripeBillingAddress {
+impl TryFrom<(&domain::BankRedirectData, Option<bool>)> for StripeBillingAddress {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(bank_redirection_data, is_customer_initiated_mandate_payment): (
- &payments::BankRedirectData,
+ &domain::BankRedirectData,
Option<bool>,
),
) -> Result<Self, Self::Error> {
match bank_redirection_data {
- payments::BankRedirectData::Eps {
+ domain::BankRedirectData::Eps {
billing_details, ..
} => Ok({
let billing_data = billing_details.clone().ok_or(
@@ -1133,7 +1133,7 @@ impl TryFrom<(&payments::BankRedirectData, Option<bool>)> for StripeBillingAddre
..Self::default()
}
}),
- payments::BankRedirectData::Giropay {
+ domain::BankRedirectData::Giropay {
billing_details, ..
} => Ok(Self {
name: Some(
@@ -1146,19 +1146,19 @@ impl TryFrom<(&payments::BankRedirectData, Option<bool>)> for StripeBillingAddre
),
..Self::default()
}),
- payments::BankRedirectData::Ideal {
+ domain::BankRedirectData::Ideal {
billing_details, ..
} => Ok(get_stripe_sepa_dd_mandate_billing_details(
billing_details,
is_customer_initiated_mandate_payment,
)?),
- payments::BankRedirectData::Przelewy24 {
+ domain::BankRedirectData::Przelewy24 {
billing_details, ..
} => Ok(Self {
email: billing_details.email.clone(),
..Self::default()
}),
- payments::BankRedirectData::BancontactCard {
+ domain::BankRedirectData::BancontactCard {
billing_details, ..
} => {
let billing_details = billing_details.as_ref().ok_or(
@@ -1188,24 +1188,24 @@ impl TryFrom<(&payments::BankRedirectData, Option<bool>)> for StripeBillingAddre
..Self::default()
})
}
- payments::BankRedirectData::Sofort {
+ domain::BankRedirectData::Sofort {
billing_details, ..
} => Ok(get_stripe_sepa_dd_mandate_billing_details(
billing_details,
is_customer_initiated_mandate_payment,
)?),
- payments::BankRedirectData::Bizum {}
- | payments::BankRedirectData::Blik { .. }
- | payments::BankRedirectData::Interac { .. }
- | payments::BankRedirectData::OnlineBankingCzechRepublic { .. }
- | payments::BankRedirectData::OnlineBankingFinland { .. }
- | payments::BankRedirectData::OnlineBankingPoland { .. }
- | payments::BankRedirectData::OnlineBankingSlovakia { .. }
- | payments::BankRedirectData::Trustly { .. }
- | payments::BankRedirectData::OnlineBankingFpx { .. }
- | payments::BankRedirectData::OnlineBankingThailand { .. }
- | payments::BankRedirectData::OpenBankingUk { .. } => Ok(Self::default()),
+ domain::BankRedirectData::Bizum {}
+ | domain::BankRedirectData::Blik { .. }
+ | domain::BankRedirectData::Interac { .. }
+ | domain::BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | domain::BankRedirectData::OnlineBankingFinland { .. }
+ | domain::BankRedirectData::OnlineBankingPoland { .. }
+ | domain::BankRedirectData::OnlineBankingSlovakia { .. }
+ | domain::BankRedirectData::Trustly { .. }
+ | domain::BankRedirectData::OnlineBankingFpx { .. }
+ | domain::BankRedirectData::OnlineBankingThailand { .. }
+ | domain::BankRedirectData::OpenBankingUk { .. } => Ok(Self::default()),
}
}
}
@@ -1608,17 +1608,17 @@ impl TryFrom<(&domain::WalletData, Option<types::PaymentMethodToken>)> for Strip
}
}
-impl TryFrom<&payments::BankRedirectData> for StripePaymentMethodData {
+impl TryFrom<&domain::BankRedirectData> for StripePaymentMethodData {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(bank_redirect_data: &payments::BankRedirectData) -> Result<Self, Self::Error> {
+ fn try_from(bank_redirect_data: &domain::BankRedirectData) -> Result<Self, Self::Error> {
let payment_method_data_type = StripePaymentMethodType::try_from(bank_redirect_data)?;
match bank_redirect_data {
- payments::BankRedirectData::BancontactCard { .. } => Ok(Self::BankRedirect(
+ domain::BankRedirectData::BancontactCard { .. } => Ok(Self::BankRedirect(
StripeBankRedirectData::StripeBancontactCard(Box::new(StripeBancontactCard {
payment_method_data_type,
})),
)),
- payments::BankRedirectData::Blik { blik_code } => Ok(Self::BankRedirect(
+ domain::BankRedirectData::Blik { blik_code } => Ok(Self::BankRedirect(
StripeBankRedirectData::StripeBlik(Box::new(StripeBlik {
payment_method_data_type,
code: Secret::new(blik_code.clone().ok_or(
@@ -1628,7 +1628,7 @@ impl TryFrom<&payments::BankRedirectData> for StripePaymentMethodData {
)?),
})),
)),
- payments::BankRedirectData::Eps { bank_name, .. } => Ok(Self::BankRedirect(
+ domain::BankRedirectData::Eps { bank_name, .. } => Ok(Self::BankRedirect(
StripeBankRedirectData::StripeEps(Box::new(StripeEps {
payment_method_data_type,
bank_name: bank_name
@@ -1636,12 +1636,12 @@ impl TryFrom<&payments::BankRedirectData> for StripePaymentMethodData {
.transpose()?,
})),
)),
- payments::BankRedirectData::Giropay { .. } => Ok(Self::BankRedirect(
+ domain::BankRedirectData::Giropay { .. } => Ok(Self::BankRedirect(
StripeBankRedirectData::StripeGiropay(Box::new(StripeGiropay {
payment_method_data_type,
})),
)),
- payments::BankRedirectData::Ideal { bank_name, .. } => {
+ domain::BankRedirectData::Ideal { bank_name, .. } => {
let bank_name = bank_name
.map(|bank_name| StripeBankNames::try_from(&bank_name))
.transpose()?;
@@ -1652,7 +1652,7 @@ impl TryFrom<&payments::BankRedirectData> for StripePaymentMethodData {
}),
)))
}
- payments::BankRedirectData::Przelewy24 { bank_name, .. } => {
+ domain::BankRedirectData::Przelewy24 { bank_name, .. } => {
let bank_name = bank_name
.map(|bank_name| StripeBankNames::try_from(&bank_name))
.transpose()?;
@@ -1663,7 +1663,7 @@ impl TryFrom<&payments::BankRedirectData> for StripePaymentMethodData {
})),
))
}
- payments::BankRedirectData::Sofort {
+ domain::BankRedirectData::Sofort {
country,
preferred_language,
..
@@ -1676,21 +1676,21 @@ impl TryFrom<&payments::BankRedirectData> for StripePaymentMethodData {
preferred_language: preferred_language.clone(),
}),
))),
- payments::BankRedirectData::OnlineBankingFpx { .. } => {
+ domain::BankRedirectData::OnlineBankingFpx { .. } => {
Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("stripe"),
)
.into())
}
- payments::BankRedirectData::Bizum {}
- | payments::BankRedirectData::Interac { .. }
- | payments::BankRedirectData::OnlineBankingCzechRepublic { .. }
- | payments::BankRedirectData::OnlineBankingFinland { .. }
- | payments::BankRedirectData::OnlineBankingPoland { .. }
- | payments::BankRedirectData::OnlineBankingSlovakia { .. }
- | payments::BankRedirectData::OnlineBankingThailand { .. }
- | payments::BankRedirectData::OpenBankingUk { .. }
- | payments::BankRedirectData::Trustly { .. } => {
+ domain::BankRedirectData::Bizum {}
+ | domain::BankRedirectData::Interac { .. }
+ | domain::BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | domain::BankRedirectData::OnlineBankingFinland { .. }
+ | domain::BankRedirectData::OnlineBankingPoland { .. }
+ | domain::BankRedirectData::OnlineBankingSlovakia { .. }
+ | domain::BankRedirectData::OnlineBankingThailand { .. }
+ | domain::BankRedirectData::OpenBankingUk { .. }
+ | domain::BankRedirectData::Trustly { .. } => {
Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("stripe"),
)
@@ -3843,7 +3843,7 @@ pub struct Evidence {
// Mandates for bank redirects - ideal and sofort happens through sepa direct debit in stripe
fn get_stripe_sepa_dd_mandate_billing_details(
- billing_details: &Option<payments::BankRedirectBilling>,
+ billing_details: &Option<domain::BankRedirectBilling>,
is_customer_initiated_mandate_payment: Option<bool>,
) -> Result<StripeBillingAddress, errors::ConnectorError> {
let billing_name = billing_details
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs
index e7e9a759d57..79396f12c69 100644
--- a/crates/router/src/connector/trustpay/transformers.rs
+++ b/crates/router/src/connector/trustpay/transformers.rs
@@ -1,6 +1,5 @@
use std::collections::HashMap;
-use api_models::payments::BankRedirectData;
use common_utils::{
errors::CustomResult,
pii::{self, Email},
@@ -229,27 +228,27 @@ pub struct TrustpayMandatoryParams {
pub billing_first_name: Secret<String>,
}
-impl TryFrom<&BankRedirectData> for TrustpayPaymentMethod {
+impl TryFrom<&domain::BankRedirectData> for TrustpayPaymentMethod {
type Error = Error;
- fn try_from(value: &BankRedirectData) -> Result<Self, Self::Error> {
+ fn try_from(value: &domain::BankRedirectData) -> Result<Self, Self::Error> {
match value {
- api_models::payments::BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
- api_models::payments::BankRedirectData::Eps { .. } => Ok(Self::Eps),
- api_models::payments::BankRedirectData::Ideal { .. } => Ok(Self::IDeal),
- api_models::payments::BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
- api_models::payments::BankRedirectData::Blik { .. } => Ok(Self::Blik),
- api_models::payments::BankRedirectData::BancontactCard { .. }
- | api_models::payments::BankRedirectData::Bizum {}
- | api_models::payments::BankRedirectData::Interac { .. }
- | api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { .. }
- | api_models::payments::BankRedirectData::OnlineBankingFinland { .. }
- | api_models::payments::BankRedirectData::OnlineBankingPoland { .. }
- | api_models::payments::BankRedirectData::OnlineBankingSlovakia { .. }
- | api_models::payments::BankRedirectData::OpenBankingUk { .. }
- | api_models::payments::BankRedirectData::Przelewy24 { .. }
- | api_models::payments::BankRedirectData::Trustly { .. }
- | api_models::payments::BankRedirectData::OnlineBankingFpx { .. }
- | api_models::payments::BankRedirectData::OnlineBankingThailand { .. } => {
+ domain::BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
+ domain::BankRedirectData::Eps { .. } => Ok(Self::Eps),
+ domain::BankRedirectData::Ideal { .. } => Ok(Self::IDeal),
+ domain::BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
+ domain::BankRedirectData::Blik { .. } => Ok(Self::Blik),
+ domain::BankRedirectData::BancontactCard { .. }
+ | domain::BankRedirectData::Bizum {}
+ | domain::BankRedirectData::Interac { .. }
+ | domain::BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | domain::BankRedirectData::OnlineBankingFinland { .. }
+ | domain::BankRedirectData::OnlineBankingPoland { .. }
+ | domain::BankRedirectData::OnlineBankingSlovakia { .. }
+ | domain::BankRedirectData::OpenBankingUk { .. }
+ | domain::BankRedirectData::Przelewy24 { .. }
+ | domain::BankRedirectData::Trustly { .. }
+ | domain::BankRedirectData::OnlineBankingFpx { .. }
+ | domain::BankRedirectData::OnlineBankingThailand { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("trustpay"),
)
@@ -358,7 +357,7 @@ fn get_debtor_info(
fn get_bank_redirection_request_data(
item: &types::PaymentsAuthorizeRouterData,
- bank_redirection_data: &BankRedirectData,
+ bank_redirection_data: &domain::BankRedirectData,
params: TrustpayMandatoryParams,
amount: String,
auth: TrustpayAuthType,
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 645d850ebe7..b0c0fe8e68f 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -1235,7 +1235,7 @@ pub trait BankRedirectBillingData {
fn get_billing_name(&self) -> Result<Secret<String>, Error>;
}
-impl BankRedirectBillingData for payments::BankRedirectBilling {
+impl BankRedirectBillingData for domain::BankRedirectBilling {
fn get_billing_name(&self) -> Result<Secret<String>, Error> {
self.billing_name
.clone()
diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs
index 47c29767d82..8c64398bd5f 100644
--- a/crates/router/src/connector/volt/transformers.rs
+++ b/crates/router/src/connector/volt/transformers.rs
@@ -88,7 +88,7 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
domain::PaymentMethodData::BankRedirect(ref bank_redirect) => match bank_redirect {
- api_models::payments::BankRedirectData::OpenBankingUk { .. } => {
+ domain::BankRedirectData::OpenBankingUk { .. } => {
let amount = item.amount;
let currency_code = item.router_data.request.currency;
let merchant_internal_reference =
@@ -118,22 +118,22 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme
transaction_type,
})
}
- api_models::payments::BankRedirectData::BancontactCard { .. }
- | api_models::payments::BankRedirectData::Bizum {}
- | api_models::payments::BankRedirectData::Blik { .. }
- | api_models::payments::BankRedirectData::Eps { .. }
- | api_models::payments::BankRedirectData::Giropay { .. }
- | api_models::payments::BankRedirectData::Ideal { .. }
- | api_models::payments::BankRedirectData::Interac { .. }
- | api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { .. }
- | api_models::payments::BankRedirectData::OnlineBankingFinland { .. }
- | api_models::payments::BankRedirectData::OnlineBankingPoland { .. }
- | api_models::payments::BankRedirectData::OnlineBankingSlovakia { .. }
- | api_models::payments::BankRedirectData::Przelewy24 { .. }
- | api_models::payments::BankRedirectData::Sofort { .. }
- | api_models::payments::BankRedirectData::Trustly { .. }
- | api_models::payments::BankRedirectData::OnlineBankingFpx { .. }
- | api_models::payments::BankRedirectData::OnlineBankingThailand { .. } => {
+ domain::BankRedirectData::BancontactCard { .. }
+ | domain::BankRedirectData::Bizum {}
+ | domain::BankRedirectData::Blik { .. }
+ | domain::BankRedirectData::Eps { .. }
+ | domain::BankRedirectData::Giropay { .. }
+ | domain::BankRedirectData::Ideal { .. }
+ | domain::BankRedirectData::Interac { .. }
+ | domain::BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | domain::BankRedirectData::OnlineBankingFinland { .. }
+ | domain::BankRedirectData::OnlineBankingPoland { .. }
+ | domain::BankRedirectData::OnlineBankingSlovakia { .. }
+ | domain::BankRedirectData::Przelewy24 { .. }
+ | domain::BankRedirectData::Sofort { .. }
+ | domain::BankRedirectData::Trustly { .. }
+ | domain::BankRedirectData::OnlineBankingFpx { .. }
+ | domain::BankRedirectData::OnlineBankingThailand { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Volt"),
)
diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs
index 9a8297dd325..490c4994045 100644
--- a/crates/router/src/connector/worldline/transformers.rs
+++ b/crates/router/src/connector/worldline/transformers.rs
@@ -317,20 +317,20 @@ impl TryFrom<utils::CardIssuer> for Gateway {
}
}
-impl TryFrom<&api_models::enums::BankNames> for WorldlineBic {
+impl TryFrom<&common_enums::enums::BankNames> for WorldlineBic {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(bank: &api_models::enums::BankNames) -> Result<Self, Self::Error> {
+ fn try_from(bank: &common_enums::enums::BankNames) -> Result<Self, Self::Error> {
match bank {
- api_models::enums::BankNames::AbnAmro => Ok(Self::Abnamro),
- api_models::enums::BankNames::AsnBank => Ok(Self::Asn),
- api_models::enums::BankNames::Ing => Ok(Self::Ing),
- api_models::enums::BankNames::Knab => Ok(Self::Knab),
- api_models::enums::BankNames::Rabobank => Ok(Self::Rabobank),
- api_models::enums::BankNames::Regiobank => Ok(Self::Regiobank),
- api_models::enums::BankNames::SnsBank => Ok(Self::Sns),
- api_models::enums::BankNames::TriodosBank => Ok(Self::Triodos),
- api_models::enums::BankNames::VanLanschot => Ok(Self::Vanlanschot),
- api_models::enums::BankNames::FrieslandBank => Ok(Self::Friesland),
+ common_enums::enums::BankNames::AbnAmro => Ok(Self::Abnamro),
+ common_enums::enums::BankNames::AsnBank => Ok(Self::Asn),
+ common_enums::enums::BankNames::Ing => Ok(Self::Ing),
+ common_enums::enums::BankNames::Knab => Ok(Self::Knab),
+ common_enums::enums::BankNames::Rabobank => Ok(Self::Rabobank),
+ common_enums::enums::BankNames::Regiobank => Ok(Self::Regiobank),
+ common_enums::enums::BankNames::SnsBank => Ok(Self::Sns),
+ common_enums::enums::BankNames::TriodosBank => Ok(Self::Triodos),
+ common_enums::enums::BankNames::VanLanschot => Ok(Self::Vanlanschot),
+ common_enums::enums::BankNames::FrieslandBank => Ok(Self::Friesland),
_ => Err(errors::ConnectorError::FlowNotSupported {
flow: bank.to_string(),
connector: "Worldline".to_string(),
@@ -374,12 +374,12 @@ fn make_card_request(
fn make_bank_redirect_request(
req: &PaymentsAuthorizeData,
- bank_redirect: &payments::BankRedirectData,
+ bank_redirect: &domain::BankRedirectData,
) -> Result<RedirectPaymentMethod, error_stack::Report<errors::ConnectorError>> {
let return_url = req.router_return_url.clone();
let redirection_data = RedirectionData { return_url };
let (payment_method_specific_data, payment_product_id) = match bank_redirect {
- payments::BankRedirectData::Giropay {
+ domain::BankRedirectData::Giropay {
billing_details,
bank_account_iban,
..
@@ -399,7 +399,7 @@ fn make_bank_redirect_request(
},
816,
),
- payments::BankRedirectData::Ideal { bank_name, .. } => (
+ domain::BankRedirectData::Ideal { bank_name, .. } => (
{
PaymentMethodSpecificData::PaymentProduct809SpecificInput(Box::new(Ideal {
issuer_id: bank_name
@@ -409,21 +409,21 @@ fn make_bank_redirect_request(
},
809,
),
- payments::BankRedirectData::BancontactCard { .. }
- | payments::BankRedirectData::Bizum {}
- | payments::BankRedirectData::Blik { .. }
- | payments::BankRedirectData::Eps { .. }
- | payments::BankRedirectData::Interac { .. }
- | payments::BankRedirectData::OnlineBankingCzechRepublic { .. }
- | payments::BankRedirectData::OnlineBankingFinland { .. }
- | payments::BankRedirectData::OnlineBankingPoland { .. }
- | payments::BankRedirectData::OnlineBankingSlovakia { .. }
- | payments::BankRedirectData::OpenBankingUk { .. }
- | payments::BankRedirectData::Przelewy24 { .. }
- | payments::BankRedirectData::Sofort { .. }
- | payments::BankRedirectData::Trustly { .. }
- | payments::BankRedirectData::OnlineBankingFpx { .. }
- | payments::BankRedirectData::OnlineBankingThailand { .. } => {
+ domain::BankRedirectData::BancontactCard { .. }
+ | domain::BankRedirectData::Bizum {}
+ | domain::BankRedirectData::Blik { .. }
+ | domain::BankRedirectData::Eps { .. }
+ | domain::BankRedirectData::Interac { .. }
+ | domain::BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | domain::BankRedirectData::OnlineBankingFinland { .. }
+ | domain::BankRedirectData::OnlineBankingPoland { .. }
+ | domain::BankRedirectData::OnlineBankingSlovakia { .. }
+ | domain::BankRedirectData::OpenBankingUk { .. }
+ | domain::BankRedirectData::Przelewy24 { .. }
+ | domain::BankRedirectData::Sofort { .. }
+ | domain::BankRedirectData::Trustly { .. }
+ | domain::BankRedirectData::OnlineBankingFpx { .. }
+ | domain::BankRedirectData::OnlineBankingThailand { .. } => {
return Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("worldline"),
)
diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs
index 2c86ae3e21b..eb658528452 100644
--- a/crates/router/src/connector/zen/transformers.rs
+++ b/crates/router/src/connector/zen/transformers.rs
@@ -724,27 +724,27 @@ impl TryFrom<&ZenRouterData<&types::PaymentsAuthorizeRouterData>> for ZenPayment
}
}
-impl TryFrom<&api_models::payments::BankRedirectData> for ZenPaymentsRequest {
+impl TryFrom<&domain::BankRedirectData> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(value: &api_models::payments::BankRedirectData) -> Result<Self, Self::Error> {
+ fn try_from(value: &domain::BankRedirectData) -> Result<Self, Self::Error> {
match value {
- api_models::payments::BankRedirectData::Ideal { .. }
- | api_models::payments::BankRedirectData::Sofort { .. }
- | api_models::payments::BankRedirectData::BancontactCard { .. }
- | api_models::payments::BankRedirectData::Blik { .. }
- | api_models::payments::BankRedirectData::Trustly { .. }
- | api_models::payments::BankRedirectData::Eps { .. }
- | api_models::payments::BankRedirectData::Giropay { .. }
- | api_models::payments::BankRedirectData::Przelewy24 { .. }
- | api_models::payments::BankRedirectData::Bizum {}
- | api_models::payments::BankRedirectData::Interac { .. }
- | api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { .. }
- | api_models::payments::BankRedirectData::OnlineBankingFinland { .. }
- | api_models::payments::BankRedirectData::OnlineBankingPoland { .. }
- | api_models::payments::BankRedirectData::OnlineBankingSlovakia { .. }
- | api_models::payments::BankRedirectData::OpenBankingUk { .. }
- | api_models::payments::BankRedirectData::OnlineBankingFpx { .. }
- | api_models::payments::BankRedirectData::OnlineBankingThailand { .. } => {
+ domain::BankRedirectData::Ideal { .. }
+ | domain::BankRedirectData::Sofort { .. }
+ | domain::BankRedirectData::BancontactCard { .. }
+ | domain::BankRedirectData::Blik { .. }
+ | domain::BankRedirectData::Trustly { .. }
+ | domain::BankRedirectData::Eps { .. }
+ | domain::BankRedirectData::Giropay { .. }
+ | domain::BankRedirectData::Przelewy24 { .. }
+ | domain::BankRedirectData::Bizum {}
+ | domain::BankRedirectData::Interac { .. }
+ | domain::BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | domain::BankRedirectData::OnlineBankingFinland { .. }
+ | domain::BankRedirectData::OnlineBankingPoland { .. }
+ | domain::BankRedirectData::OnlineBankingSlovakia { .. }
+ | domain::BankRedirectData::OpenBankingUk { .. }
+ | domain::BankRedirectData::OnlineBankingFpx { .. }
+ | domain::BankRedirectData::OnlineBankingThailand { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
)
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index d94864c75b5..fc933ea28d7 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -1127,10 +1127,11 @@ pub async fn mock_delete_card<'a>(
//------------------------------------------------------------------------------
pub fn get_banks(
state: &routes::AppState,
- pm_type: api_enums::PaymentMethodType,
+ pm_type: common_enums::enums::PaymentMethodType,
connectors: Vec<String>,
) -> Result<Vec<BankCodeResponse>, errors::ApiErrorResponse> {
- let mut bank_names_hm: HashMap<String, HashSet<api_enums::BankNames>> = HashMap::new();
+ let mut bank_names_hm: HashMap<String, HashSet<common_enums::enums::BankNames>> =
+ HashMap::new();
if matches!(
pm_type,
@@ -1296,7 +1297,7 @@ pub async fn list_payment_methods(
Some(api::MandateTransactionType::RecurringMandateTransaction)
} else if pa.mandate_details.is_some()
|| setup_future_usage
- .map(|future_usage| future_usage == api_enums::FutureUsage::OffSession)
+ .map(|future_usage| future_usage == common_enums::enums::FutureUsage::OffSession)
.unwrap_or(false)
{
Some(api::MandateTransactionType::NewMandateTransaction)
diff --git a/crates/router/src/types/domain/payments.rs b/crates/router/src/types/domain/payments.rs
index 8674a57cf3a..b8285fbdc9a 100644
--- a/crates/router/src/types/domain/payments.rs
+++ b/crates/router/src/types/domain/payments.rs
@@ -11,7 +11,7 @@ pub enum PaymentMethodData {
CardRedirect(CardRedirectData),
Wallet(WalletData),
PayLater(PayLaterData),
- BankRedirect(api_models::payments::BankRedirectData),
+ BankRedirect(BankRedirectData),
BankDebit(api_models::payments::BankDebitData),
BankTransfer(Box<api_models::payments::BankTransferData>),
Crypto(api_models::payments::CryptoData),
@@ -243,7 +243,7 @@ pub struct ApplepayPaymentMethod {
pub pm_type: String,
}
-#[derive(Debug, Clone, Eq, PartialEq)]
+#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
pub enum BankRedirectData {
BancontactCard {
@@ -313,7 +313,7 @@ pub enum BankRedirectData {
},
}
-#[derive(Debug, Clone, Eq, PartialEq)]
+#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct BankRedirectBilling {
pub billing_name: Option<Secret<String>>,
pub email: Option<Email>,
@@ -335,7 +335,7 @@ impl From<api_models::payments::PaymentMethodData> for PaymentMethodData {
Self::PayLater(From::from(pay_later_data))
}
api_models::payments::PaymentMethodData::BankRedirect(bank_redirect_data) => {
- Self::BankRedirect(bank_redirect_data)
+ Self::BankRedirect(From::from(bank_redirect_data))
}
api_models::payments::PaymentMethodData::BankDebit(bank_debit_data) => {
Self::BankDebit(bank_debit_data)
@@ -545,3 +545,109 @@ impl From<api_models::payments::PayLaterData> for PayLaterData {
}
}
}
+
+impl From<api_models::payments::BankRedirectData> for BankRedirectData {
+ fn from(value: api_models::payments::BankRedirectData) -> Self {
+ match value {
+ api_models::payments::BankRedirectData::BancontactCard {
+ card_number,
+ card_exp_month,
+ card_exp_year,
+ card_holder_name,
+ billing_details,
+ } => Self::BancontactCard {
+ card_number,
+ card_exp_month,
+ card_exp_year,
+ card_holder_name,
+ billing_details: billing_details.map(BankRedirectBilling::from),
+ },
+ api_models::payments::BankRedirectData::Bizum {} => Self::Bizum {},
+ api_models::payments::BankRedirectData::Blik { blik_code } => Self::Blik { blik_code },
+ api_models::payments::BankRedirectData::Eps {
+ billing_details,
+ bank_name,
+ country,
+ } => Self::Eps {
+ billing_details: billing_details.map(BankRedirectBilling::from),
+ bank_name,
+ country,
+ },
+ api_models::payments::BankRedirectData::Giropay {
+ billing_details,
+ bank_account_bic,
+ bank_account_iban,
+ country,
+ } => Self::Giropay {
+ billing_details: billing_details.map(BankRedirectBilling::from),
+ bank_account_bic,
+ bank_account_iban,
+ country,
+ },
+ api_models::payments::BankRedirectData::Ideal {
+ billing_details,
+ bank_name,
+ country,
+ } => Self::Ideal {
+ billing_details: billing_details.map(BankRedirectBilling::from),
+ bank_name,
+ country,
+ },
+ api_models::payments::BankRedirectData::Interac { country, email } => {
+ Self::Interac { country, email }
+ }
+ api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { issuer } => {
+ Self::OnlineBankingCzechRepublic { issuer }
+ }
+ api_models::payments::BankRedirectData::OnlineBankingFinland { email } => {
+ Self::OnlineBankingFinland { email }
+ }
+ api_models::payments::BankRedirectData::OnlineBankingPoland { issuer } => {
+ Self::OnlineBankingPoland { issuer }
+ }
+ api_models::payments::BankRedirectData::OnlineBankingSlovakia { issuer } => {
+ Self::OnlineBankingSlovakia { issuer }
+ }
+ api_models::payments::BankRedirectData::OpenBankingUk { issuer, country } => {
+ Self::OpenBankingUk { issuer, country }
+ }
+ api_models::payments::BankRedirectData::Przelewy24 {
+ bank_name,
+ billing_details,
+ } => Self::Przelewy24 {
+ bank_name,
+ billing_details: BankRedirectBilling {
+ billing_name: billing_details.billing_name,
+ email: billing_details.email,
+ },
+ },
+ api_models::payments::BankRedirectData::Sofort {
+ billing_details,
+ country,
+ preferred_language,
+ } => Self::Sofort {
+ billing_details: billing_details.map(BankRedirectBilling::from),
+ country,
+ preferred_language,
+ },
+ api_models::payments::BankRedirectData::Trustly { country } => {
+ Self::Trustly { country }
+ }
+ api_models::payments::BankRedirectData::OnlineBankingFpx { issuer } => {
+ Self::OnlineBankingFpx { issuer }
+ }
+ api_models::payments::BankRedirectData::OnlineBankingThailand { issuer } => {
+ Self::OnlineBankingThailand { issuer }
+ }
+ }
+ }
+}
+
+impl From<api_models::payments::BankRedirectBilling> for BankRedirectBilling {
+ fn from(billing: api_models::payments::BankRedirectBilling) -> Self {
+ Self {
+ billing_name: billing.billing_name,
+ email: billing.email,
+ }
+ }
+}
|
refactor
|
add BankRedirect payment method data to new domain type to be used in connector module (#4175)
|
ffc79674e44d9b50bddbf4f4ac4aad0895c655db
|
2024-07-09 05:47:36
|
github-actions
|
chore(version): 2024.07.09.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 53cd35842da..d4aae8fed31 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,22 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 2024.07.09.0
+
+### Features
+
+- **core:** Addition of shipping address details in payment intent ([#5112](https://github.com/juspay/hyperswitch/pull/5112)) ([`2d31d38`](https://github.com/juspay/hyperswitch/commit/2d31d38c1e35be99e9b0297b197bab81fa5f5030))
+- **router:** Add integrity check for refund refund sync and capture flow with stripe as connector ([#5187](https://github.com/juspay/hyperswitch/pull/5187)) ([`adc760f`](https://github.com/juspay/hyperswitch/commit/adc760f0a6c75b5a51d9955f5e507776e7a88d1a))
+- Add `hsdev` binary to run migrations ([#4877](https://github.com/juspay/hyperswitch/pull/4877)) ([`f64b522`](https://github.com/juspay/hyperswitch/commit/f64b522154cf4d3702ad39babc75c7ba940f8217))
+
+### Bug Fixes
+
+- **connector:** Remove mandatory payment_method_type check in MIT ([#5246](https://github.com/juspay/hyperswitch/pull/5246)) ([`19744ce`](https://github.com/juspay/hyperswitch/commit/19744cec1042f8b7c5cc496c3b4d201604aca204))
+
+**Full Changelog:** [`2024.07.08.1...2024.07.09.0`](https://github.com/juspay/hyperswitch/compare/2024.07.08.1...2024.07.09.0)
+
+- - -
+
## 2024.07.08.1
### Bug Fixes
|
chore
|
2024.07.09.0
|
f81416e4df6fa430fd7f6eb910b55464cd72f3f0
|
2024-08-09 14:45:15
|
Prasunna Soppa
|
refactor(core): Use hyperswitch_domain_models within the Payments Core instead of api_models (#5511)
| false
|
diff --git a/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
index bfa2da851f8..8499aecaed7 100644
--- a/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
@@ -196,7 +196,8 @@ impl TryFrom<BamboraRouterData<&types::PaymentsAuthorizeRouterData>> for Bambora
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
- | PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented(
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("bambora"),
)
.into()),
diff --git a/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
index 0ae59d4526e..b2cbd570b4f 100644
--- a/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
@@ -198,7 +198,8 @@ impl TryFrom<&FiservRouterData<&types::PaymentsAuthorizeRouterData>> for FiservP
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
- | PaymentMethodData::CardToken(_) => {
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiserv"),
))
diff --git a/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs b/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs
index 3aed97a2cbc..90380d02321 100644
--- a/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs
@@ -180,7 +180,8 @@ impl TryFrom<&SetupMandateRouterData> for HelcimVerifyRequest {
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
- | PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented(
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
crate::utils::get_unimplemented_payment_method_error_message("Helcim"),
))?,
}
@@ -273,7 +274,8 @@ impl TryFrom<&HelcimRouterData<&PaymentsAuthorizeRouterData>> for HelcimPayments
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
- | PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented(
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
crate::utils::get_unimplemented_payment_method_error_message("Helcim"),
))?,
}
diff --git a/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
index 8c767e848da..f7b2016a370 100644
--- a/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
@@ -117,7 +117,8 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::OpenBanking(_)
- | PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented(
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Stax"),
))?,
}
@@ -267,7 +268,8 @@ impl TryFrom<&types::TokenizationRouterData> for StaxTokenRequest {
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::OpenBanking(_)
- | PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented(
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Stax"),
))?,
}
diff --git a/crates/hyperswitch_domain_models/src/api.rs b/crates/hyperswitch_domain_models/src/api.rs
index d62516234ea..b013d2b7902 100644
--- a/crates/hyperswitch_domain_models/src/api.rs
+++ b/crates/hyperswitch_domain_models/src/api.rs
@@ -5,6 +5,8 @@ use common_utils::{
impl_api_event_type,
};
+use super::payment_method_data::PaymentMethodData;
+
#[derive(Debug, Eq, PartialEq)]
pub enum ApplicationResponse<R> {
Json(R),
@@ -33,7 +35,7 @@ impl_api_event_type!(Miscellaneous, (PaymentLinkFormData, GenericLinkFormData));
#[derive(Debug, Eq, PartialEq)]
pub struct RedirectionFormData {
pub redirect_form: crate::router_response_types::RedirectForm,
- pub payment_method_data: Option<api_models::payments::PaymentMethodData>,
+ pub payment_method_data: Option<PaymentMethodData>,
pub amount: String,
pub currency: String,
}
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index a440ba944f1..5bff7b489ca 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -1,4 +1,9 @@
-use common_utils::pii::{self, Email};
+use api_models::payments::ExtendedCardInfo;
+use common_enums::enums as api_enums;
+use common_utils::{
+ id_type,
+ pii::{self, Email},
+};
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::Date;
@@ -23,6 +28,7 @@ pub enum PaymentMethodData {
GiftCard(Box<GiftCardData>),
CardToken(CardToken),
OpenBanking(OpenBankingData),
+ NetworkToken(NetworkTokenData),
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -34,7 +40,7 @@ pub enum ApplePayFlow {
impl PaymentMethodData {
pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> {
match self {
- Self::Card(_) => Some(common_enums::PaymentMethod::Card),
+ Self::Card(_) | Self::NetworkToken(_) => Some(common_enums::PaymentMethod::Card),
Self::CardRedirect(_) => Some(common_enums::PaymentMethod::CardRedirect),
Self::Wallet(_) => Some(common_enums::PaymentMethod::Wallet),
Self::PayLater(_) => Some(common_enums::PaymentMethod::PayLater),
@@ -468,6 +474,20 @@ pub struct SepaAndBacsBillingDetails {
pub name: Secret<String>,
}
+#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
+pub struct NetworkTokenData {
+ pub token_number: cards::CardNumber,
+ pub token_exp_month: Secret<String>,
+ pub token_exp_year: Secret<String>,
+ pub token_cryptogram: Secret<String>,
+ pub card_issuer: Option<String>,
+ pub card_network: Option<common_enums::CardNetwork>,
+ pub card_type: Option<String>,
+ pub card_issuing_country: Option<String>,
+ pub bank_code: Option<String>,
+ pub nick_name: Option<Secret<String>>,
+}
+
impl From<api_models::payments::PaymentMethodData> for PaymentMethodData {
fn from(api_model_payment_method_data: api_models::payments::PaymentMethodData) -> Self {
match api_model_payment_method_data {
@@ -952,3 +972,259 @@ impl From<api_models::payments::OpenBankingData> for OpenBankingData {
}
}
}
+
+#[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>,
+}
+
+#[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>,
+}
+
+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::MomoRedirect(_) => api_enums::PaymentMethodType::Momo,
+ Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay,
+ Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay,
+ Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash,
+ 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::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay,
+ Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay,
+ Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal,
+ 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,
+ }
+ }
+}
+
+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::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,
+ }
+ }
+}
+
+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::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,
+ }
+ }
+}
+
+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,
+ }
+ }
+}
+
+impl GetPaymentMethodType for OpenBankingData {
+ fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
+ match self {
+ Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS,
+ }
+ }
+}
+
+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,
+ }
+ }
+}
diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs
index 175138add75..933b4326350 100644
--- a/crates/router/src/connector/aci/transformers.rs
+++ b/crates/router/src/connector/aci/transformers.rs
@@ -448,7 +448,8 @@ impl TryFrom<&AciRouterData<&types::PaymentsAuthorizeRouterData>> for AciPayment
| domain::PaymentMethodData::Upi(_)
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Aci"),
))?
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index b1f14e8305b..71c5bb438d9 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -1556,7 +1556,8 @@ impl<'a> TryFrom<&AdyenRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::RealTimePayment(_)
| domain::PaymentMethodData::Upi(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Adyen"),
))?
@@ -2558,7 +2559,8 @@ impl<'a>
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotSupported {
message: "Network tokenization for payment method".to_string(),
connector: "Adyen",
diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs
index 9fab84559b5..4d84f64534e 100644
--- a/crates/router/src/connector/airwallex/transformers.rs
+++ b/crates/router/src/connector/airwallex/transformers.rs
@@ -205,7 +205,8 @@ impl TryFrom<&AirwallexRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("airwallex"),
))
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index 33570a782fd..14f61d1ded7 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -343,7 +343,8 @@ impl TryFrom<&types::SetupMandateRouterData> for CreateCustomerProfileRequest {
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
))?
@@ -522,7 +523,8 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message(
"authorizedotnet",
@@ -581,7 +583,8 @@ impl
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
))?
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs
index 34244bbb819..46a522c7378 100644
--- a/crates/router/src/connector/bankofamerica/transformers.rs
+++ b/crates/router/src/connector/bankofamerica/transformers.rs
@@ -322,7 +322,8 @@ impl TryFrom<&types::SetupMandateRouterData> for BankOfAmericaPaymentsRequest {
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("BankOfAmerica"),
))?
@@ -1073,7 +1074,8 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message(
"Bank of America",
diff --git a/crates/router/src/connector/billwerk/transformers.rs b/crates/router/src/connector/billwerk/transformers.rs
index e91184c878c..c6f2be9dbfc 100644
--- a/crates/router/src/connector/billwerk/transformers.rs
+++ b/crates/router/src/connector/billwerk/transformers.rs
@@ -103,7 +103,8 @@ impl TryFrom<&types::TokenizationRouterData> for BillwerkTokenRequest {
| domain::payments::PaymentMethodData::Voucher(_)
| domain::payments::PaymentMethodData::GiftCard(_)
| domain::payments::PaymentMethodData::OpenBanking(_)
- | domain::payments::PaymentMethodData::CardToken(_) => {
+ | domain::payments::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("billwerk"),
)
diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs
index dc67c1961be..6ebcdf0e765 100644
--- a/crates/router/src/connector/bluesnap/transformers.rs
+++ b/crates/router/src/connector/bluesnap/transformers.rs
@@ -228,7 +228,8 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
"Selected payment method via Token flow through bluesnap".to_string(),
)
@@ -393,7 +394,8 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for Blues
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("bluesnap"),
))
diff --git a/crates/router/src/connector/boku/transformers.rs b/crates/router/src/connector/boku/transformers.rs
index eeb914fd846..5fd6b0e6a2e 100644
--- a/crates/router/src/connector/boku/transformers.rs
+++ b/crates/router/src/connector/boku/transformers.rs
@@ -111,7 +111,8 @@ impl TryFrom<&BokuRouterData<&types::PaymentsAuthorizeRouterData>> for BokuPayme
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("boku"),
))?
diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs
index e5f97dc3333..22982ceb213 100644
--- a/crates/router/src/connector/braintree/transformers.rs
+++ b/crates/router/src/connector/braintree/transformers.rs
@@ -309,7 +309,8 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("braintree"),
)
@@ -1098,7 +1099,8 @@ impl TryFrom<&types::TokenizationRouterData> for BraintreeTokenRequest {
| domain::PaymentMethodData::Upi(_)
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("braintree"),
)
@@ -1702,7 +1704,8 @@ fn get_braintree_redirect_form(
| domain::PaymentMethodData::Upi(_)
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::CardToken(_) => Err(
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => Err(
errors::ConnectorError::NotImplemented("given payment method".to_owned()),
)?,
},
diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs
index be48d2a864f..223256155cf 100644
--- a/crates/router/src/connector/checkout/transformers.rs
+++ b/crates/router/src/connector/checkout/transformers.rs
@@ -133,7 +133,8 @@ impl TryFrom<&types::TokenizationRouterData> for TokenRequest {
| domain::PaymentMethodData::CardRedirect(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
)
@@ -370,7 +371,8 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme
| domain::PaymentMethodData::CardRedirect(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
))
diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs
index c15afd7fd44..cd22890ca52 100644
--- a/crates/router/src/connector/cryptopay/transformers.rs
+++ b/crates/router/src/connector/cryptopay/transformers.rs
@@ -79,7 +79,8 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("CryptoPay"),
))
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index c68f0e6069f..67f88e24ab3 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -215,7 +215,8 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest {
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
))?
@@ -1400,7 +1401,8 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
)
@@ -1507,7 +1509,8 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
)
@@ -2220,7 +2223,8 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsPreProcessingRouterData>>
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
))
@@ -2330,7 +2334,8 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
)
diff --git a/crates/router/src/connector/datatrans/transformers.rs b/crates/router/src/connector/datatrans/transformers.rs
index 96c7bcd8b2c..afc9288b656 100644
--- a/crates/router/src/connector/datatrans/transformers.rs
+++ b/crates/router/src/connector/datatrans/transformers.rs
@@ -188,7 +188,8 @@ impl TryFrom<&DatatransRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
connector_utils::get_unimplemented_payment_method_error_message("Datatrans"),
))?
diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs
index ca18d12a088..a613cdb2054 100644
--- a/crates/router/src/connector/dlocal/transformers.rs
+++ b/crates/router/src/connector/dlocal/transformers.rs
@@ -167,7 +167,8 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
crate::connector::utils::get_unimplemented_payment_method_error_message(
"Dlocal",
diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs
index 0533d71ffeb..b039282b719 100644
--- a/crates/router/src/connector/forte/transformers.rs
+++ b/crates/router/src/connector/forte/transformers.rs
@@ -116,7 +116,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FortePaymentsRequest {
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Forte"),
))?
diff --git a/crates/router/src/connector/globepay/transformers.rs b/crates/router/src/connector/globepay/transformers.rs
index 8974c9f94b9..df89d3deb9f 100644
--- a/crates/router/src/connector/globepay/transformers.rs
+++ b/crates/router/src/connector/globepay/transformers.rs
@@ -74,7 +74,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for GlobepayPaymentsRequest {
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("globepay"),
))?
diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs
index fb27f5138a9..572e4efa33f 100644
--- a/crates/router/src/connector/gocardless/transformers.rs
+++ b/crates/router/src/connector/gocardless/transformers.rs
@@ -247,7 +247,8 @@ impl TryFrom<&types::TokenizationRouterData> for CustomerBankAccount {
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Gocardless"),
)
@@ -417,7 +418,8 @@ impl TryFrom<&types::SetupMandateRouterData> for GocardlessMandateRequest {
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
"Setup Mandate flow for selected payment method through Gocardless".to_string(),
))
diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs
index 845e079e136..f6b8c266ce2 100644
--- a/crates/router/src/connector/iatapay/transformers.rs
+++ b/crates/router/src/connector/iatapay/transformers.rs
@@ -205,7 +205,8 @@ impl
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::OpenBanking(_) => {
+ | domain::PaymentMethodData::OpenBanking(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("iatapay"),
))?
diff --git a/crates/router/src/connector/itaubank/transformers.rs b/crates/router/src/connector/itaubank/transformers.rs
index 5c53cfbf160..9af0a25dd86 100644
--- a/crates/router/src/connector/itaubank/transformers.rs
+++ b/crates/router/src/connector/itaubank/transformers.rs
@@ -119,7 +119,8 @@ impl TryFrom<&ItaubankRouterData<&types::PaymentsAuthorizeRouterData>> for Itaub
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::OpenBanking(_) => {
+ | domain::PaymentMethodData::OpenBanking(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
"Selected payment method through itaubank".to_string(),
)
diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs
index fbfb8b71974..0e6fab80584 100644
--- a/crates/router/src/connector/klarna.rs
+++ b/crates/router/src/connector/klarna.rs
@@ -652,7 +652,8 @@ impl
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(report!(errors::ConnectorError::NotImplemented(
connector_utils::get_unimplemented_payment_method_error_message(
req.connector.as_str(),
diff --git a/crates/router/src/connector/mifinity/transformers.rs b/crates/router/src/connector/mifinity/transformers.rs
index 7fd34b93698..0af3826c877 100644
--- a/crates/router/src/connector/mifinity/transformers.rs
+++ b/crates/router/src/connector/mifinity/transformers.rs
@@ -195,7 +195,8 @@ impl TryFrom<&MifinityRouterData<&types::PaymentsAuthorizeRouterData>> for Mifin
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Mifinity"),
)
diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs
index ac0a04de182..0fd483a421d 100644
--- a/crates/router/src/connector/multisafepay/transformers.rs
+++ b/crates/router/src/connector/multisafepay/transformers.rs
@@ -607,7 +607,8 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?
@@ -788,7 +789,8 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::OpenBanking(_) => {
+ | domain::PaymentMethodData::OpenBanking(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?
diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs
index 7e32ae5ebed..43cb4cecec8 100644
--- a/crates/router/src/connector/nexinets/transformers.rs
+++ b/crates/router/src/connector/nexinets/transformers.rs
@@ -626,7 +626,8 @@ fn get_payment_details_and_product(
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
- | PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented(
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nexinets"),
))?,
}
diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs
index e0858e16a4a..069a51ae52e 100644
--- a/crates/router/src/connector/nmi/transformers.rs
+++ b/crates/router/src/connector/nmi/transformers.rs
@@ -585,7 +585,8 @@ impl
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nmi"),
)
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs
index 8336cbf1318..b7df6829da4 100644
--- a/crates/router/src/connector/noon/transformers.rs
+++ b/crates/router/src/connector/noon/transformers.rs
@@ -353,7 +353,8 @@ impl TryFrom<&NoonRouterData<&types::PaymentsAuthorizeRouterData>> for NoonPayme
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
conn_utils::get_unimplemented_payment_method_error_message("Noon"),
))
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index 1aa34517357..e6711640826 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -996,7 +996,8 @@ where
| domain::PaymentMethodData::CardRedirect(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nuvei"),
)
@@ -1199,6 +1200,7 @@ impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, Secret<String>)>
| Some(domain::PaymentMethodData::Upi(..))
| Some(domain::PaymentMethodData::OpenBanking(_))
| Some(domain::PaymentMethodData::CardToken(..))
+ | Some(domain::PaymentMethodData::NetworkToken(..))
| None => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nuvei"),
)),
diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs
index 5771b45100b..dcb4e201e8b 100644
--- a/crates/router/src/connector/opayo/transformers.rs
+++ b/crates/router/src/connector/opayo/transformers.rs
@@ -57,7 +57,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpayoPaymentsRequest {
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Opayo"),
)
diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs
index 8da3e7502be..0bb10c9845a 100644
--- a/crates/router/src/connector/payeezy/transformers.rs
+++ b/crates/router/src/connector/payeezy/transformers.rs
@@ -261,9 +261,12 @@ fn get_payment_method_data(
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Payeezy"),
- ))?,
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Payeezy"),
+ ))?
+ }
}
}
diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs
index 2ec35b7a7de..c12e478b08e 100644
--- a/crates/router/src/connector/payme/transformers.rs
+++ b/crates/router/src/connector/payme/transformers.rs
@@ -430,7 +430,8 @@ impl TryFrom<&PaymentMethodData> for SalePaymentMethod {
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::OpenBanking(_)
- | PaymentMethodData::CardToken(_) => {
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into())
}
}
@@ -675,7 +676,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayRequest {
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
- | PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented(
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("payme"),
))?,
}
@@ -736,6 +738,7 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest {
| Some(PaymentMethodData::GiftCard(_))
| Some(PaymentMethodData::OpenBanking(_))
| Some(PaymentMethodData::CardToken(_))
+ | Some(PaymentMethodData::NetworkToken(_))
| None => {
Err(errors::ConnectorError::NotImplemented("Tokenize Flow".to_string()).into())
}
@@ -775,7 +778,8 @@ impl TryFrom<&types::TokenizationRouterData> for CaptureBuyerRequest {
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
- | PaymentMethodData::CardToken(_) => {
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented("Tokenize Flow".to_string()).into())
}
}
diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs
index fb70581cd97..24b2f2b88e9 100644
--- a/crates/router/src/connector/paypal/transformers.rs
+++ b/crates/router/src/connector/paypal/transformers.rs
@@ -552,7 +552,8 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP
| domain::PaymentMethodData::Crypto(_)
| domain::PaymentMethodData::Upi(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
)
diff --git a/crates/router/src/connector/placetopay/transformers.rs b/crates/router/src/connector/placetopay/transformers.rs
index 50c897653da..919fe25bdd8 100644
--- a/crates/router/src/connector/placetopay/transformers.rs
+++ b/crates/router/src/connector/placetopay/transformers.rs
@@ -142,7 +142,8 @@ impl TryFrom<&PlacetopayRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Placetopay"),
)
diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs
index fedaabb5e75..97c2994b4c7 100644
--- a/crates/router/src/connector/powertranz/transformers.rs
+++ b/crates/router/src/connector/powertranz/transformers.rs
@@ -117,7 +117,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotSupported {
message: utils::SELECTED_PAYMENT_METHOD.to_string(),
connector: "powertranz",
diff --git a/crates/router/src/connector/razorpay/transformers.rs b/crates/router/src/connector/razorpay/transformers.rs
index 8cf32891886..69d6bdce384 100644
--- a/crates/router/src/connector/razorpay/transformers.rs
+++ b/crates/router/src/connector/razorpay/transformers.rs
@@ -399,7 +399,8 @@ impl
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into())
}
}?;
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs
index f384d8d296d..13c0395cf9f 100644
--- a/crates/router/src/connector/shift4/transformers.rs
+++ b/crates/router/src/connector/shift4/transformers.rs
@@ -248,7 +248,8 @@ where
| domain::PaymentMethodData::RealTimePayment(_)
| domain::PaymentMethodData::Upi(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
@@ -472,6 +473,7 @@ impl<T> TryFrom<&types::RouterData<T, types::CompleteAuthorizeData, types::Payme
| Some(domain::PaymentMethodData::Upi(_))
| Some(domain::PaymentMethodData::OpenBanking(_))
| Some(domain::PaymentMethodData::CardToken(_))
+ | Some(domain::PaymentMethodData::NetworkToken(_))
| None => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs
index 67be82bb2d9..db7058f3384 100644
--- a/crates/router/src/connector/square/transformers.rs
+++ b/crates/router/src/connector/square/transformers.rs
@@ -175,7 +175,8 @@ impl TryFrom<&types::TokenizationRouterData> for SquareTokenRequest {
| domain::PaymentMethodData::Upi(_)
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Square"),
))?
@@ -292,7 +293,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest {
| domain::PaymentMethodData::Upi(_)
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Square"),
))?
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 90ddc9f0b90..6b26818c292 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -1334,10 +1334,13 @@ fn create_stripe_payment_method(
| domain::PaymentMethodData::RealTimePayment(_)
| domain::PaymentMethodData::MandatePayment
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented(
- connector_util::get_unimplemented_payment_method_error_message("stripe"),
- )
- .into()),
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ connector_util::get_unimplemented_payment_method_error_message("stripe"),
+ )
+ .into())
+ }
}
}
@@ -1711,7 +1714,8 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent
| domain::payments::PaymentMethodData::Voucher(_)
| domain::payments::PaymentMethodData::GiftCard(_)
| domain::payments::PaymentMethodData::OpenBanking(_)
- | domain::payments::PaymentMethodData::CardToken(_) => {
+ | domain::payments::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotSupported {
message: "Network tokenization for payment method".to_string(),
connector: "Stripe",
@@ -3299,6 +3303,7 @@ impl
| Some(domain::PaymentMethodData::Voucher(..))
| Some(domain::PaymentMethodData::OpenBanking(..))
| Some(domain::PaymentMethodData::CardToken(..))
+ | Some(domain::PaymentMethodData::NetworkToken(..))
| None => Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("stripe"),
)
@@ -3752,7 +3757,8 @@ impl
| domain::PaymentMethodData::CardRedirect(_)
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("stripe"),
))?
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs
index 85539e253b7..d05db4d28ab 100644
--- a/crates/router/src/connector/trustpay/transformers.rs
+++ b/crates/router/src/connector/trustpay/transformers.rs
@@ -434,7 +434,8 @@ impl TryFrom<&TrustpayRouterData<&types::PaymentsAuthorizeRouterData>> for Trust
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("trustpay"),
)
diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs
index 53561d93a92..347a95151d5 100644
--- a/crates/router/src/connector/tsys/transformers.rs
+++ b/crates/router/src/connector/tsys/transformers.rs
@@ -77,7 +77,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for TsysPaymentsRequest {
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("tsys"),
))?
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index d61d78d37ff..d5c01503ed8 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -2677,12 +2677,14 @@ pub enum PaymentMethodDataType {
PromptPay,
VietQr,
OpenBanking,
+ NetworkToken,
}
impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType {
fn from(pm_data: domain::payments::PaymentMethodData) -> Self {
match pm_data {
domain::payments::PaymentMethodData::Card(_) => Self::Card,
+ domain::payments::PaymentMethodData::NetworkToken(_) => Self::NetworkToken,
domain::payments::PaymentMethodData::CardRedirect(card_redirect_data) => {
match card_redirect_data {
domain::CardRedirectData::Knet {} => Self::Knet,
diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs
index fcc95cd0d4b..451c70279cc 100644
--- a/crates/router/src/connector/volt/transformers.rs
+++ b/crates/router/src/connector/volt/transformers.rs
@@ -141,7 +141,8 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Volt"),
)
diff --git a/crates/router/src/connector/wellsfargo/transformers.rs b/crates/router/src/connector/wellsfargo/transformers.rs
index 93ed04288af..44d0332daeb 100644
--- a/crates/router/src/connector/wellsfargo/transformers.rs
+++ b/crates/router/src/connector/wellsfargo/transformers.rs
@@ -205,7 +205,8 @@ impl TryFrom<&types::SetupMandateRouterData> for WellsfargoZeroMandateRequest {
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Wellsfargo"),
))?
@@ -1280,7 +1281,8 @@ impl TryFrom<&WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Wellsfargo"),
)
diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs
index 11d9da7785a..e0278dc4ccb 100644
--- a/crates/router/src/connector/worldline/transformers.rs
+++ b/crates/router/src/connector/worldline/transformers.rs
@@ -250,7 +250,8 @@ impl
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("worldline"),
))?
diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs
index cab949789b9..de82e11548c 100644
--- a/crates/router/src/connector/worldpay/transformers.rs
+++ b/crates/router/src/connector/worldpay/transformers.rs
@@ -109,10 +109,13 @@ fn fetch_payment_instrument(
| domain::PaymentMethodData::CardRedirect(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("worldpay"),
- )
- .into()),
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("worldpay"),
+ )
+ .into())
+ }
}
}
diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs
index 2562277ee9b..d2e8ce40283 100644
--- a/crates/router/src/connector/zen/transformers.rs
+++ b/crates/router/src/connector/zen/transformers.rs
@@ -695,7 +695,8 @@ impl TryFrom<&ZenRouterData<&types::PaymentsAuthorizeRouterData>> for ZenPayment
| domain::PaymentMethodData::RealTimePayment(_)
| domain::PaymentMethodData::Upi(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ | domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
))?
diff --git a/crates/router/src/connector/zsl/transformers.rs b/crates/router/src/connector/zsl/transformers.rs
index 19a79ab48a3..60aed55b1f4 100644
--- a/crates/router/src/connector/zsl/transformers.rs
+++ b/crates/router/src/connector/zsl/transformers.rs
@@ -182,6 +182,7 @@ impl TryFrom<&ZslRouterData<&types::PaymentsAuthorizeRouterData>> for ZslPayment
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_)
| domain::PaymentMethodData::OpenBanking(_) => {
Err(errors::ConnectorError::NotImplemented(
connector_utils::get_unimplemented_payment_method_error_message(
diff --git a/crates/router/src/core/authentication.rs b/crates/router/src/core/authentication.rs
index 2e292d16090..450a1986b27 100644
--- a/crates/router/src/core/authentication.rs
+++ b/crates/router/src/core/authentication.rs
@@ -22,7 +22,7 @@ pub async fn perform_authentication(
state: &SessionState,
merchant_id: common_utils::id_type::MerchantId,
authentication_connector: String,
- payment_method_data: payments::PaymentMethodData,
+ payment_method_data: domain::PaymentMethodData,
payment_method: common_enums::PaymentMethod,
billing_address: payments::Address,
shipping_address: Option<payments::Address>,
diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rs
index 5ca3d05f129..02d64e449a6 100644
--- a/crates/router/src/core/authentication/transformers.rs
+++ b/crates/router/src/core/authentication/transformers.rs
@@ -28,7 +28,7 @@ const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_AUTHENTICATION_FLOW: &str =
pub fn construct_authentication_router_data(
merchant_id: common_utils::id_type::MerchantId,
authentication_connector: String,
- payment_method_data: payments::PaymentMethodData,
+ payment_method_data: domain::PaymentMethodData,
payment_method: PaymentMethod,
billing_address: payments::Address,
shipping_address: Option<payments::Address>,
@@ -47,7 +47,7 @@ pub fn construct_authentication_router_data(
three_ds_requestor_url: String,
) -> RouterResult<types::authentication::ConnectorAuthenticationRouterData> {
let router_request = types::authentication::ConnectorAuthenticationRequestData {
- payment_method_data: From::from(payment_method_data),
+ payment_method_data,
billing_address,
shipping_address,
browser_details,
diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rs
index 8edd75d3df7..555be16a1c6 100644
--- a/crates/router/src/core/blocklist/utils.rs
+++ b/crates/router/src/core/blocklist/utils.rs
@@ -304,7 +304,7 @@ where
let merchant_fingerprint_secret = get_merchant_fingerprint_secret(state, merchant_id).await?;
// Hashed Fingerprint to check whether or not this payment should be blocked.
- let card_number_fingerprint = if let Some(api_models::payments::PaymentMethodData::Card(card)) =
+ let card_number_fingerprint = if let Some(domain::PaymentMethodData::Card(card)) =
payment_data.payment_method_data.as_ref()
{
generate_fingerprint(
@@ -332,9 +332,7 @@ where
.payment_method_data
.as_ref()
.and_then(|pm_data| match pm_data {
- api_models::payments::PaymentMethodData::Card(card) => {
- Some(card.card_number.get_card_isin())
- }
+ domain::PaymentMethodData::Card(card) => Some(card.card_number.get_card_isin()),
_ => None,
});
@@ -344,7 +342,7 @@ where
.payment_method_data
.as_ref()
.and_then(|pm_data| match pm_data {
- api_models::payments::PaymentMethodData::Card(card) => {
+ domain::PaymentMethodData::Card(card) => {
Some(card.card_number.get_extended_card_bin())
}
_ => None,
@@ -446,14 +444,12 @@ where
pub async fn generate_payment_fingerprint(
state: &SessionState,
merchant_id: common_utils::id_type::MerchantId,
- payment_method_data: Option<crate::types::api::PaymentMethodData>,
+ payment_method_data: Option<domain::PaymentMethodData>,
) -> CustomResult<Option<String>, errors::ApiErrorResponse> {
let merchant_fingerprint_secret = get_merchant_fingerprint_secret(state, &merchant_id).await?;
Ok(
- if let Some(api_models::payments::PaymentMethodData::Card(card)) =
- payment_method_data.as_ref()
- {
+ if let Some(domain::PaymentMethodData::Card(card)) = payment_method_data.as_ref() {
generate_fingerprint(
state,
StrongSecret::new(card.card_number.get_card_no()),
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 09b36946b77..a33fe5bb06a 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -9,9 +9,9 @@ pub mod vault;
use std::{borrow::Cow, collections::HashSet};
pub use api_models::enums::Connector;
+use api_models::payment_methods;
#[cfg(feature = "payouts")]
pub use api_models::{enums::PayoutConnectors, payouts as payout_types};
-use api_models::{payment_methods, payments::CardToken};
use common_utils::{ext_traits::Encode, id_type::CustomerId};
use diesel_models::{
enums, GenericLinkNew, PaymentMethodCollectLink, PaymentMethodCollectLinkData,
@@ -35,10 +35,7 @@ use crate::{
},
routes::{app::StorageInterface, SessionState},
services,
- types::{
- api::{self, payments},
- domain, storage,
- },
+ types::{domain, storage},
};
const PAYMENT_METHOD_STATUS_UPDATE_TASK: &str = "PAYMENT_METHOD_STATUS_UPDATE";
@@ -46,15 +43,15 @@ const PAYMENT_METHOD_STATUS_TAG: &str = "PAYMENT_METHOD_STATUS";
#[instrument(skip_all)]
pub async fn retrieve_payment_method(
- pm_data: &Option<payments::PaymentMethodData>,
+ pm_data: &Option<domain::PaymentMethodData>,
state: &SessionState,
payment_intent: &PaymentIntent,
payment_attempt: &PaymentAttempt,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::BusinessProfile>,
-) -> RouterResult<(Option<payments::PaymentMethodData>, Option<String>)> {
+) -> RouterResult<(Option<domain::PaymentMethodData>, Option<String>)> {
match pm_data {
- pm_opt @ Some(pm @ api::PaymentMethodData::Card(_)) => {
+ pm_opt @ Some(pm @ domain::PaymentMethodData::Card(_)) => {
let payment_token = helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
@@ -68,17 +65,17 @@ pub async fn retrieve_payment_method(
Ok((pm_opt.to_owned(), payment_token))
}
- pm @ Some(api::PaymentMethodData::PayLater(_)) => Ok((pm.to_owned(), None)),
- pm @ Some(api::PaymentMethodData::Crypto(_)) => Ok((pm.to_owned(), None)),
- pm @ Some(api::PaymentMethodData::BankDebit(_)) => Ok((pm.to_owned(), None)),
- pm @ Some(api::PaymentMethodData::Upi(_)) => Ok((pm.to_owned(), None)),
- pm @ Some(api::PaymentMethodData::Voucher(_)) => Ok((pm.to_owned(), None)),
- pm @ Some(api::PaymentMethodData::Reward) => Ok((pm.to_owned(), None)),
- pm @ Some(api::PaymentMethodData::RealTimePayment(_)) => Ok((pm.to_owned(), None)),
- pm @ Some(api::PaymentMethodData::CardRedirect(_)) => Ok((pm.to_owned(), None)),
- pm @ Some(api::PaymentMethodData::GiftCard(_)) => Ok((pm.to_owned(), None)),
- pm @ Some(api::PaymentMethodData::OpenBanking(_)) => Ok((pm.to_owned(), None)),
- pm_opt @ Some(pm @ api::PaymentMethodData::BankTransfer(_)) => {
+ pm @ Some(domain::PaymentMethodData::PayLater(_)) => Ok((pm.to_owned(), None)),
+ pm @ Some(domain::PaymentMethodData::Crypto(_)) => Ok((pm.to_owned(), None)),
+ pm @ Some(domain::PaymentMethodData::BankDebit(_)) => Ok((pm.to_owned(), None)),
+ pm @ Some(domain::PaymentMethodData::Upi(_)) => Ok((pm.to_owned(), None)),
+ pm @ Some(domain::PaymentMethodData::Voucher(_)) => Ok((pm.to_owned(), None)),
+ pm @ Some(domain::PaymentMethodData::Reward) => Ok((pm.to_owned(), None)),
+ pm @ Some(domain::PaymentMethodData::RealTimePayment(_)) => Ok((pm.to_owned(), None)),
+ pm @ Some(domain::PaymentMethodData::CardRedirect(_)) => Ok((pm.to_owned(), None)),
+ pm @ Some(domain::PaymentMethodData::GiftCard(_)) => Ok((pm.to_owned(), None)),
+ pm @ Some(domain::PaymentMethodData::OpenBanking(_)) => Ok((pm.to_owned(), None)),
+ pm_opt @ Some(pm @ domain::PaymentMethodData::BankTransfer(_)) => {
let payment_token = helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
@@ -92,7 +89,7 @@ pub async fn retrieve_payment_method(
Ok((pm_opt.to_owned(), payment_token))
}
- pm_opt @ Some(pm @ api::PaymentMethodData::Wallet(_)) => {
+ pm_opt @ Some(pm @ domain::PaymentMethodData::Wallet(_)) => {
let payment_token = helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
@@ -106,7 +103,7 @@ pub async fn retrieve_payment_method(
Ok((pm_opt.to_owned(), payment_token))
}
- pm_opt @ Some(pm @ api::PaymentMethodData::BankRedirect(_)) => {
+ pm_opt @ Some(pm @ domain::PaymentMethodData::BankRedirect(_)) => {
let payment_token = helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
@@ -434,7 +431,7 @@ pub async fn retrieve_payment_method_with_token(
merchant_key_store: &domain::MerchantKeyStore,
token_data: &storage::PaymentTokenData,
payment_intent: &PaymentIntent,
- card_token_data: Option<&CardToken>,
+ card_token_data: Option<&domain::CardToken>,
customer: &Option<domain::Customer>,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> RouterResult<storage::PaymentMethodDataWithId> {
diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs
index 4e17ec6abd3..918522e7a9e 100644
--- a/crates/router/src/core/payment_methods/vault.rs
+++ b/crates/router/src/core/payment_methods/vault.rs
@@ -47,20 +47,16 @@ pub trait Vaultable: Sized {
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError>;
}
-impl Vaultable for api::Card {
+impl Vaultable for domain::Card {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
- let value1 = api::TokenizedCardValue1 {
+ let value1 = domain::TokenizedCardValue1 {
card_number: self.card_number.peek().clone(),
exp_year: self.card_exp_year.peek().clone(),
exp_month: self.card_exp_month.peek().clone(),
- name_on_card: self
- .card_holder_name
- .as_ref()
- .map(|name| name.peek().clone()),
- nickname: None,
+ nickname: self.nick_name.as_ref().map(|name| name.peek().clone()),
card_last_four: None,
card_token: None,
};
@@ -75,7 +71,7 @@ impl Vaultable for api::Card {
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
- let value2 = api::TokenizedCardValue2 {
+ let value2 = domain::TokenizedCardValue2 {
card_security_code: Some(self.card_cvc.peek().clone()),
card_fingerprint: None,
external_id: None,
@@ -93,12 +89,12 @@ impl Vaultable for api::Card {
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
- let value1: api::TokenizedCardValue1 = value1
+ let value1: domain::TokenizedCardValue1 = value1
.parse_struct("TokenizedCardValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into card value1")?;
- let value2: api::TokenizedCardValue2 = value2
+ let value2: domain::TokenizedCardValue2 = value2
.parse_struct("TokenizedCardValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into card value2")?;
@@ -109,7 +105,6 @@ impl Vaultable for api::Card {
.attach_printable("Invalid card number format from the mock locker")?,
card_exp_month: value1.exp_month.into(),
card_exp_year: value1.exp_year.into(),
- card_holder_name: value1.name_on_card.map(masking::Secret::new),
card_cvc: value2.card_security_code.unwrap_or_default().into(),
card_issuer: None,
card_network: None,
@@ -128,12 +123,12 @@ impl Vaultable for api::Card {
}
}
-impl Vaultable for api_models::payments::BankTransferData {
+impl Vaultable for domain::BankTransferData {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
- let value1 = api_models::payment_methods::TokenizedBankTransferValue1 {
+ let value1 = domain::TokenizedBankTransferValue1 {
data: self.to_owned(),
};
@@ -147,7 +142,7 @@ impl Vaultable for api_models::payments::BankTransferData {
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
- let value2 = api_models::payment_methods::TokenizedBankTransferValue2 { customer_id };
+ let value2 = domain::TokenizedBankTransferValue2 { customer_id };
value2
.encode_to_string_of_json()
@@ -159,12 +154,12 @@ impl Vaultable for api_models::payments::BankTransferData {
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
- let value1: api_models::payment_methods::TokenizedBankTransferValue1 = value1
+ let value1: domain::TokenizedBankTransferValue1 = value1
.parse_struct("TokenizedBankTransferValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into bank transfer data")?;
- let value2: api_models::payment_methods::TokenizedBankTransferValue2 = value2
+ let value2: domain::TokenizedBankTransferValue2 = value2
.parse_struct("TokenizedBankTransferValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into supplementary bank transfer data")?;
@@ -180,12 +175,12 @@ impl Vaultable for api_models::payments::BankTransferData {
}
}
-impl Vaultable for api::WalletData {
+impl Vaultable for domain::WalletData {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
- let value1 = api::TokenizedWalletValue1 {
+ let value1 = domain::TokenizedWalletValue1 {
data: self.to_owned(),
};
@@ -199,7 +194,7 @@ impl Vaultable for api::WalletData {
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
- let value2 = api::TokenizedWalletValue2 { customer_id };
+ let value2 = domain::TokenizedWalletValue2 { customer_id };
value2
.encode_to_string_of_json()
@@ -211,12 +206,12 @@ impl Vaultable for api::WalletData {
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
- let value1: api::TokenizedWalletValue1 = value1
+ let value1: domain::TokenizedWalletValue1 = value1
.parse_struct("TokenizedWalletValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into wallet data value1")?;
- let value2: api::TokenizedWalletValue2 = value2
+ let value2: domain::TokenizedWalletValue2 = value2
.parse_struct("TokenizedWalletValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into wallet data value2")?;
@@ -232,12 +227,12 @@ impl Vaultable for api::WalletData {
}
}
-impl Vaultable for api_models::payments::BankRedirectData {
+impl Vaultable for domain::BankRedirectData {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
- let value1 = api_models::payment_methods::TokenizedBankRedirectValue1 {
+ let value1 = domain::TokenizedBankRedirectValue1 {
data: self.to_owned(),
};
@@ -251,7 +246,7 @@ impl Vaultable for api_models::payments::BankRedirectData {
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
- let value2 = api_models::payment_methods::TokenizedBankRedirectValue2 { customer_id };
+ let value2 = domain::TokenizedBankRedirectValue2 { customer_id };
value2
.encode_to_string_of_json()
@@ -263,12 +258,12 @@ impl Vaultable for api_models::payments::BankRedirectData {
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
- let value1: api_models::payment_methods::TokenizedBankRedirectValue1 = value1
+ let value1: domain::TokenizedBankRedirectValue1 = value1
.parse_struct("TokenizedBankRedirectValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into bank redirect data")?;
- let value2: api_models::payment_methods::TokenizedBankRedirectValue2 = value2
+ let value2: domain::TokenizedBankRedirectValue2 = value2
.parse_struct("TokenizedBankRedirectValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into supplementary bank redirect data")?;
@@ -293,7 +288,7 @@ pub enum VaultPaymentMethod {
BankRedirect(String),
}
-impl Vaultable for api::PaymentMethodData {
+impl Vaultable for domain::PaymentMethodData {
fn get_value1(
&self,
customer_id: Option<id_type::CustomerId>,
@@ -356,11 +351,11 @@ impl Vaultable for api::PaymentMethodData {
match (value1, value2) {
(VaultPaymentMethod::Card(mvalue1), VaultPaymentMethod::Card(mvalue2)) => {
- let (card, supp_data) = api::Card::from_values(mvalue1, mvalue2)?;
+ let (card, supp_data) = domain::Card::from_values(mvalue1, mvalue2)?;
Ok((Self::Card(card), supp_data))
}
(VaultPaymentMethod::Wallet(mvalue1), VaultPaymentMethod::Wallet(mvalue2)) => {
- let (wallet, supp_data) = api::WalletData::from_values(mvalue1, mvalue2)?;
+ let (wallet, supp_data) = domain::WalletData::from_values(mvalue1, mvalue2)?;
Ok((Self::Wallet(wallet), supp_data))
}
(
@@ -368,7 +363,7 @@ impl Vaultable for api::PaymentMethodData {
VaultPaymentMethod::BankTransfer(mvalue2),
) => {
let (bank_transfer, supp_data) =
- api_models::payments::BankTransferData::from_values(mvalue1, mvalue2)?;
+ domain::BankTransferData::from_values(mvalue1, mvalue2)?;
Ok((Self::BankTransfer(Box::new(bank_transfer)), supp_data))
}
(
@@ -376,7 +371,7 @@ impl Vaultable for api::PaymentMethodData {
VaultPaymentMethod::BankRedirect(mvalue2),
) => {
let (bank_redirect, supp_data) =
- api_models::payments::BankRedirectData::from_values(mvalue1, mvalue2)?;
+ domain::BankRedirectData::from_values(mvalue1, mvalue2)?;
Ok((Self::BankRedirect(bank_redirect), supp_data))
}
@@ -821,11 +816,11 @@ impl Vault {
state: &routes::SessionState,
lookup_key: &str,
merchant_key_store: &domain::MerchantKeyStore,
- ) -> RouterResult<(Option<api::PaymentMethodData>, SupplementaryVaultData)> {
+ ) -> RouterResult<(Option<domain::PaymentMethodData>, SupplementaryVaultData)> {
let de_tokenize =
get_tokenized_data(state, lookup_key, true, merchant_key_store.key.get_inner()).await?;
let (payment_method, customer_id) =
- api::PaymentMethodData::from_values(de_tokenize.value1, de_tokenize.value2)
+ domain::PaymentMethodData::from_values(de_tokenize.value1, de_tokenize.value2)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error parsing Payment Method from Values")?;
@@ -836,7 +831,7 @@ impl Vault {
pub async fn store_payment_method_data_in_locker(
state: &routes::SessionState,
token_id: Option<String>,
- payment_method: &api::PaymentMethodData,
+ payment_method: &domain::PaymentMethodData,
customer_id: Option<id_type::CustomerId>,
pm: enums::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index cc324fa5291..00cc4839b42 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1575,24 +1575,18 @@ where
payment_processing_details,
) => {
let apple_pay_data = match payment_data.payment_method_data.clone() {
- Some(payment_method_data) => {
- let domain_data = domain::PaymentMethodData::from(payment_method_data);
- match domain_data {
- domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(
- wallet_data,
- )) => Some(
- ApplePayData::token_json(domain::WalletData::ApplePay(wallet_data))
- .change_context(errors::ApiErrorResponse::InternalServerError)?
- .decrypt(
- &payment_processing_details.payment_processing_certificate,
- &payment_processing_details.payment_processing_certificate_key,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?,
- ),
- _ => None,
- }
- }
+ Some(domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(
+ wallet_data,
+ ))) => Some(
+ ApplePayData::token_json(domain::WalletData::ApplePay(wallet_data))
+ .change_context(errors::ApiErrorResponse::InternalServerError)?
+ .decrypt(
+ &payment_processing_details.payment_processing_certificate,
+ &payment_processing_details.payment_processing_certificate_key,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)?,
+ ),
_ => None,
};
@@ -2068,9 +2062,9 @@ where
}
//TODO: For ACH transfers, if preprocessing_step is not required for connectors encountered in future, add the check
let router_data_and_should_continue_payment = match payment_data.payment_method_data.clone() {
- Some(api_models::payments::PaymentMethodData::BankTransfer(data)) => match data.deref() {
- api_models::payments::BankTransferData::AchBankTransfer { .. }
- | api_models::payments::BankTransferData::MultibancoBankTransfer { .. }
+ Some(domain::PaymentMethodData::BankTransfer(data)) => match data.deref() {
+ domain::BankTransferData::AchBankTransfer { .. }
+ | domain::BankTransferData::MultibancoBankTransfer { .. }
if connector.connector_name == router_types::Connector::Stripe =>
{
if payment_data.payment_attempt.preprocessing_step_id.is_none() {
@@ -2084,7 +2078,7 @@ where
}
_ => (router_data, should_continue_payment),
},
- Some(api_models::payments::PaymentMethodData::Wallet(_)) => {
+ Some(domain::PaymentMethodData::Wallet(_)) => {
if is_preprocessing_required_for_wallets(connector.connector_name.to_string()) {
(
router_data.preprocessing_steps(state, connector).await?,
@@ -2094,7 +2088,7 @@ where
(router_data, should_continue_payment)
}
}
- Some(api_models::payments::PaymentMethodData::Card(_)) => {
+ Some(domain::PaymentMethodData::Card(_)) => {
if connector.connector_name == router_types::Connector::Payme
&& !matches!(format!("{operation:?}").as_str(), "CompleteAuthorize")
{
@@ -2143,7 +2137,7 @@ where
(router_data, should_continue_payment)
}
}
- Some(api_models::payments::PaymentMethodData::GiftCard(_)) => {
+ Some(domain::PaymentMethodData::GiftCard(_)) => {
if connector.connector_name == router_types::Connector::Adyen {
router_data = router_data.preprocessing_steps(state, connector).await?;
@@ -2154,7 +2148,7 @@ where
(router_data, should_continue_payment)
}
}
- Some(api_models::payments::PaymentMethodData::BankDebit(_)) => {
+ Some(domain::PaymentMethodData::BankDebit(_)) => {
if connector.connector_name == router_types::Connector::Gocardless {
router_data = router_data.preprocessing_steps(state, connector).await?;
let is_error_in_response = router_data.response.is_err();
@@ -2217,9 +2211,9 @@ where
.await?;
match payment_data.payment_method_data.clone() {
- Some(api_models::payments::PaymentMethodData::OpenBanking(
- api_models::payments::OpenBankingData::OpenBankingPIS { .. },
- )) => {
+ Some(domain::PaymentMethodData::OpenBanking(domain::OpenBankingData::OpenBankingPIS {
+ ..
+ })) => {
if connector.connector_name == router_types::Connector::Plaid {
router_data = router_data.postprocessing_steps(state, connector).await?;
let token = if let Ok(ref res) = router_data.response {
@@ -2706,7 +2700,7 @@ where
pub token_data: Option<storage::PaymentTokenData>,
pub confirm: Option<bool>,
pub force_sync: Option<bool>,
- pub payment_method_data: Option<api::PaymentMethodData>,
+ pub payment_method_data: Option<domain::PaymentMethodData>,
pub payment_method_info: Option<storage::PaymentMethod>,
pub refunds: Vec<storage::Refund>,
pub disputes: Vec<storage::Dispute>,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index d3ca7d04286..1fe84121d5b 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -4,7 +4,7 @@ use std::{borrow::Cow, str::FromStr};
use api_models::customers::CustomerRequestWithEmail;
use api_models::{
mandates::RecurringDetails,
- payments::{AddressDetailsWithPhone, CardToken, GetPaymentMethodType, RequestSurchargeDetails},
+ payments::{AddressDetailsWithPhone, RequestSurchargeDetails},
};
use base64::Engine;
use common_enums::ConnectorType;
@@ -25,6 +25,7 @@ use futures::future::Either;
use hyperswitch_domain_models::payments::payment_intent::CustomerData;
use hyperswitch_domain_models::{
mandates::MandateData,
+ payment_method_data::GetPaymentMethodType,
payments::{payment_attempt::PaymentAttempt, PaymentIntent},
router_data::KlarnaSdkResponse,
};
@@ -1776,8 +1777,8 @@ pub async fn retrieve_payment_method_with_temporary_token(
token: &str,
payment_intent: &PaymentIntent,
merchant_key_store: &domain::MerchantKeyStore,
- card_token_data: Option<&CardToken>,
-) -> RouterResult<Option<(api::PaymentMethodData, enums::PaymentMethod)>> {
+ card_token_data: Option<&domain::CardToken>,
+) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> {
let (pm, supplementary_data) =
vault::Vault::get_payment_method_data_from_locker(state, token, merchant_key_store)
.await
@@ -1795,31 +1796,18 @@ pub async fn retrieve_payment_method_with_temporary_token(
)?;
Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(match pm {
- Some(api::PaymentMethodData::Card(card)) => {
+ Some(domain::PaymentMethodData::Card(card)) => {
let mut updated_card = card.clone();
let mut is_card_updated = false;
// The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked
// from payment_method_data.card_token object
- let name_on_card = if let Some(name) = card.card_holder_name.clone() {
- if name.clone().expose().is_empty() {
- card_token_data
- .and_then(|token_data| {
- is_card_updated = true;
- token_data.card_holder_name.clone()
- })
- .or(Some(name))
- } else {
- card.card_holder_name.clone()
- }
- } else {
- card_token_data.and_then(|token_data| {
- is_card_updated = true;
- token_data.card_holder_name.clone()
- })
- };
+ let name_on_card = card_token_data.and_then(|token_data| {
+ is_card_updated = true;
+ token_data.card_holder_name.clone()
+ });
- updated_card.card_holder_name = name_on_card;
+ updated_card.nick_name = name_on_card;
if let Some(token_data) = card_token_data {
if let Some(cvc) = token_data.card_cvc.clone() {
@@ -1829,7 +1817,7 @@ pub async fn retrieve_payment_method_with_temporary_token(
}
if is_card_updated {
- let updated_pm = api::PaymentMethodData::Card(updated_card);
+ let updated_pm = domain::PaymentMethodData::Card(updated_card);
vault::Vault::store_payment_method_data_in_locker(
state,
Some(token.to_owned()),
@@ -1843,21 +1831,21 @@ pub async fn retrieve_payment_method_with_temporary_token(
Some((updated_pm, enums::PaymentMethod::Card))
} else {
Some((
- api::PaymentMethodData::Card(card),
+ domain::PaymentMethodData::Card(card),
enums::PaymentMethod::Card,
))
}
}
- Some(the_pm @ api::PaymentMethodData::Wallet(_)) => {
+ Some(the_pm @ domain::PaymentMethodData::Wallet(_)) => {
Some((the_pm, enums::PaymentMethod::Wallet))
}
- Some(the_pm @ api::PaymentMethodData::BankTransfer(_)) => {
+ Some(the_pm @ domain::PaymentMethodData::BankTransfer(_)) => {
Some((the_pm, enums::PaymentMethod::BankTransfer))
}
- Some(the_pm @ api::PaymentMethodData::BankRedirect(_)) => {
+ Some(the_pm @ domain::PaymentMethodData::BankRedirect(_)) => {
Some((the_pm, enums::PaymentMethod::BankRedirect))
}
@@ -1873,10 +1861,10 @@ pub async fn retrieve_card_with_permanent_token(
locker_id: &str,
_payment_method_id: &str,
payment_intent: &PaymentIntent,
- card_token_data: Option<&CardToken>,
+ card_token_data: Option<&domain::CardToken>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
-) -> RouterResult<api::PaymentMethodData> {
+) -> RouterResult<domain::PaymentMethodData> {
let customer_id = payment_intent
.customer_id
.as_ref()
@@ -1930,7 +1918,7 @@ pub async fn retrieve_card_with_permanent_token(
bank_code: None,
};
- Ok(api::PaymentMethodData::Card(api_card))
+ Ok(domain::PaymentMethodData::Card(api_card.into()))
}
pub async fn retrieve_payment_method_from_db_with_token_data(
@@ -2028,19 +2016,19 @@ pub async fn make_pm_data<'a, F: Clone, R>(
business_profile: Option<&domain::BusinessProfile>,
) -> RouterResult<(
BoxedOperation<'a, F, R>,
- Option<api::PaymentMethodData>,
+ Option<domain::PaymentMethodData>,
Option<String>,
)> {
- let request = &payment_data.payment_method_data.clone();
+ let request = payment_data.payment_method_data.clone();
let mut card_token_data = payment_data
.payment_method_data
.clone()
.and_then(|pmd| match pmd {
- api_models::payments::PaymentMethodData::CardToken(token_data) => Some(token_data),
+ domain::PaymentMethodData::CardToken(token_data) => Some(token_data),
_ => None,
})
- .or(Some(CardToken::default()));
+ .or(Some(domain::CardToken::default()));
if let Some(cvc) = payment_data.card_cvc.clone() {
if let Some(token_data) = card_token_data.as_mut() {
@@ -2068,7 +2056,7 @@ pub async fn make_pm_data<'a, F: Clone, R>(
}
// TODO: Handle case where payment method and token both are present in request properly.
- let (payment_method, pm_id) = match (request, payment_data.token_data.as_ref()) {
+ let (payment_method, pm_id) = match (&request, payment_data.token_data.as_ref()) {
(_, Some(hyperswitch_token)) => {
let pm_data = payment_methods::retrieve_payment_method_with_token(
state,
@@ -2099,7 +2087,7 @@ pub async fn make_pm_data<'a, F: Clone, R>(
(Some(_), _) => {
let (payment_method_data, payment_token) = payment_methods::retrieve_payment_method(
- request,
+ &request,
state,
&payment_data.payment_intent,
&payment_data.payment_attempt,
@@ -2120,7 +2108,7 @@ pub async fn make_pm_data<'a, F: Clone, R>(
pub async fn store_in_vault_and_generate_ppmt(
state: &SessionState,
- payment_method_data: &api_models::payments::PaymentMethodData,
+ payment_method_data: &domain::PaymentMethodData,
payment_intent: &PaymentIntent,
payment_attempt: &PaymentAttempt,
payment_method: enums::PaymentMethod,
@@ -2165,7 +2153,7 @@ pub async fn store_payment_method_data_in_vault(
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
payment_method: enums::PaymentMethod,
- payment_method_data: &api::PaymentMethodData,
+ payment_method_data: &domain::PaymentMethodData,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::BusinessProfile>,
) -> RouterResult<Option<String>> {
@@ -3908,12 +3896,13 @@ mod test {
#[instrument(skip_all)]
pub async fn get_additional_payment_data(
- pm_data: &api_models::payments::PaymentMethodData,
+ pm_data: &domain::PaymentMethodData,
db: &dyn StorageInterface,
profile_id: &str,
-) -> api_models::payments::AdditionalPaymentData {
+) -> Option<api_models::payments::AdditionalPaymentData> {
match pm_data {
- api_models::payments::PaymentMethodData::Card(card_data) => {
+ domain::PaymentMethodData::Card(card_data) => {
+ //todo!
let card_isin = Some(card_data.card_number.get_card_isin());
let enable_extended_bin =db
.find_config_by_key_unwrap_or(
@@ -3934,7 +3923,7 @@ pub async fn get_additional_payment_data(
&& card_data.card_issuing_country.is_some()
&& card_data.bank_code.is_some()
{
- api_models::payments::AdditionalPaymentData::Card(Box::new(
+ Some(api_models::payments::AdditionalPaymentData::Card(Box::new(
api_models::payments::AdditionalCardInfo {
card_issuer: card_data.card_issuer.to_owned(),
card_network: card_data.card_network.clone(),
@@ -3943,7 +3932,7 @@ pub async fn get_additional_payment_data(
bank_code: card_data.bank_code.to_owned(),
card_exp_month: Some(card_data.card_exp_month.clone()),
card_exp_year: Some(card_data.card_exp_year.clone()),
- card_holder_name: card_data.card_holder_name.clone(),
+ card_holder_name: card_data.nick_name.clone(), //todo!
last4: last4.clone(),
card_isin: card_isin.clone(),
card_extended_bin: card_extended_bin.clone(),
@@ -3951,7 +3940,7 @@ pub async fn get_additional_payment_data(
payment_checks: None,
authentication_data: None,
},
- ))
+ )))
} else {
let card_info = card_isin
.clone()
@@ -3976,14 +3965,14 @@ pub async fn get_additional_payment_data(
card_extended_bin: card_extended_bin.clone(),
card_exp_month: Some(card_data.card_exp_month.clone()),
card_exp_year: Some(card_data.card_exp_year.clone()),
- card_holder_name: card_data.card_holder_name.clone(),
+ card_holder_name: card_data.nick_name.clone(), //todo!
// These are filled after calling the processor / connector
payment_checks: None,
authentication_data: None,
},
))
});
- card_info.unwrap_or_else(|| {
+ Some(card_info.unwrap_or_else(|| {
api_models::payments::AdditionalPaymentData::Card(Box::new(
api_models::payments::AdditionalCardInfo {
card_issuer: None,
@@ -3996,77 +3985,82 @@ pub async fn get_additional_payment_data(
card_extended_bin,
card_exp_month: Some(card_data.card_exp_month.clone()),
card_exp_year: Some(card_data.card_exp_year.clone()),
- card_holder_name: card_data.card_holder_name.clone(),
+ card_holder_name: card_data.nick_name.clone(), //todo!
// These are filled after calling the processor / connector
payment_checks: None,
authentication_data: None,
},
))
- })
+ }))
}
}
- api_models::payments::PaymentMethodData::BankRedirect(bank_redirect_data) => {
- match bank_redirect_data {
- api_models::payments::BankRedirectData::Eps { bank_name, .. } => {
- api_models::payments::AdditionalPaymentData::BankRedirect {
- bank_name: bank_name.to_owned(),
- }
- }
- api_models::payments::BankRedirectData::Ideal { bank_name, .. } => {
- api_models::payments::AdditionalPaymentData::BankRedirect {
- bank_name: bank_name.to_owned(),
- }
- }
- _ => api_models::payments::AdditionalPaymentData::BankRedirect { bank_name: None },
+ domain::PaymentMethodData::BankRedirect(bank_redirect_data) => match bank_redirect_data {
+ domain::BankRedirectData::Eps { bank_name, .. } => {
+ Some(api_models::payments::AdditionalPaymentData::BankRedirect {
+ bank_name: bank_name.to_owned(),
+ })
}
- }
- api_models::payments::PaymentMethodData::Wallet(wallet) => match wallet {
- api_models::payments::WalletData::ApplePay(apple_pay_wallet_data) => {
- api_models::payments::AdditionalPaymentData::Wallet {
- apple_pay: Some(apple_pay_wallet_data.payment_method.to_owned()),
- }
+ domain::BankRedirectData::Ideal { bank_name, .. } => {
+ Some(api_models::payments::AdditionalPaymentData::BankRedirect {
+ bank_name: bank_name.to_owned(),
+ })
+ }
+ _ => {
+ Some(api_models::payments::AdditionalPaymentData::BankRedirect { bank_name: None })
+ }
+ },
+ domain::PaymentMethodData::Wallet(wallet) => match wallet {
+ domain::WalletData::ApplePay(apple_pay_wallet_data) => {
+ Some(api_models::payments::AdditionalPaymentData::Wallet {
+ apple_pay: Some(api_models::payments::ApplepayPaymentMethod {
+ display_name: apple_pay_wallet_data.payment_method.display_name.clone(),
+ network: apple_pay_wallet_data.payment_method.network.clone(),
+ pm_type: apple_pay_wallet_data.payment_method.pm_type.clone(),
+ }),
+ })
}
- _ => api_models::payments::AdditionalPaymentData::Wallet { apple_pay: None },
+ _ => Some(api_models::payments::AdditionalPaymentData::Wallet { apple_pay: None }),
},
- api_models::payments::PaymentMethodData::PayLater(_) => {
- api_models::payments::AdditionalPaymentData::PayLater { klarna_sdk: None }
+ domain::PaymentMethodData::PayLater(_) => {
+ Some(api_models::payments::AdditionalPaymentData::PayLater { klarna_sdk: None })
}
- api_models::payments::PaymentMethodData::BankTransfer(_) => {
- api_models::payments::AdditionalPaymentData::BankTransfer {}
+ domain::PaymentMethodData::BankTransfer(_) => {
+ Some(api_models::payments::AdditionalPaymentData::BankTransfer {})
}
- api_models::payments::PaymentMethodData::Crypto(_) => {
- api_models::payments::AdditionalPaymentData::Crypto {}
+ domain::PaymentMethodData::Crypto(_) => {
+ Some(api_models::payments::AdditionalPaymentData::Crypto {})
}
- api_models::payments::PaymentMethodData::BankDebit(_) => {
- api_models::payments::AdditionalPaymentData::BankDebit {}
+ domain::PaymentMethodData::BankDebit(_) => {
+ Some(api_models::payments::AdditionalPaymentData::BankDebit {})
}
- api_models::payments::PaymentMethodData::MandatePayment => {
- api_models::payments::AdditionalPaymentData::MandatePayment {}
+ domain::PaymentMethodData::MandatePayment => {
+ Some(api_models::payments::AdditionalPaymentData::MandatePayment {})
}
- api_models::payments::PaymentMethodData::Reward => {
- api_models::payments::AdditionalPaymentData::Reward {}
+ domain::PaymentMethodData::Reward => {
+ Some(api_models::payments::AdditionalPaymentData::Reward {})
}
- api_models::payments::PaymentMethodData::RealTimePayment(_) => {
- api_models::payments::AdditionalPaymentData::RealTimePayment {}
+ domain::PaymentMethodData::RealTimePayment(_) => {
+ Some(api_models::payments::AdditionalPaymentData::RealTimePayment {})
}
- api_models::payments::PaymentMethodData::Upi(_) => {
- api_models::payments::AdditionalPaymentData::Upi {}
+ domain::PaymentMethodData::Upi(_) => {
+ Some(api_models::payments::AdditionalPaymentData::Upi {})
}
- api_models::payments::PaymentMethodData::CardRedirect(_) => {
- api_models::payments::AdditionalPaymentData::CardRedirect {}
+ domain::PaymentMethodData::CardRedirect(_) => {
+ Some(api_models::payments::AdditionalPaymentData::CardRedirect {})
}
- api_models::payments::PaymentMethodData::Voucher(_) => {
- api_models::payments::AdditionalPaymentData::Voucher {}
+ domain::PaymentMethodData::Voucher(_) => {
+ Some(api_models::payments::AdditionalPaymentData::Voucher {})
}
- api_models::payments::PaymentMethodData::GiftCard(_) => {
- api_models::payments::AdditionalPaymentData::GiftCard {}
+ domain::PaymentMethodData::GiftCard(_) => {
+ Some(api_models::payments::AdditionalPaymentData::GiftCard {})
}
- api_models::payments::PaymentMethodData::CardToken(_) => {
- api_models::payments::AdditionalPaymentData::CardToken {}
+ domain::PaymentMethodData::CardToken(_) => {
+ Some(api_models::payments::AdditionalPaymentData::CardToken {})
}
- api_models::payments::PaymentMethodData::OpenBanking(_) => {
- api_models::payments::AdditionalPaymentData::OpenBanking {}
+ domain::PaymentMethodData::OpenBanking(_) => {
+ Some(api_models::payments::AdditionalPaymentData::OpenBanking {})
}
+ domain::PaymentMethodData::NetworkToken(_) => None,
}
}
@@ -4554,14 +4548,14 @@ impl ApplePayData {
}
pub fn get_key_params_for_surcharge_details(
- payment_method_data: &api_models::payments::PaymentMethodData,
+ payment_method_data: &domain::PaymentMethodData,
) -> Option<(
common_enums::PaymentMethod,
common_enums::PaymentMethodType,
Option<common_enums::CardNetwork>,
)> {
match payment_method_data {
- api_models::payments::PaymentMethodData::Card(card) => {
+ domain::PaymentMethodData::Card(card) => {
// surcharge generated will always be same for credit as well as debit
// since surcharge conditions cannot be defined on card_type
Some((
@@ -4570,69 +4564,70 @@ pub fn get_key_params_for_surcharge_details(
card.card_network.clone(),
))
}
- api_models::payments::PaymentMethodData::CardRedirect(card_redirect_data) => Some((
+ domain::PaymentMethodData::CardRedirect(card_redirect_data) => Some((
common_enums::PaymentMethod::CardRedirect,
card_redirect_data.get_payment_method_type(),
None,
)),
- api_models::payments::PaymentMethodData::Wallet(wallet) => Some((
+ domain::PaymentMethodData::Wallet(wallet) => Some((
common_enums::PaymentMethod::Wallet,
wallet.get_payment_method_type(),
None,
)),
- api_models::payments::PaymentMethodData::PayLater(pay_later) => Some((
+ domain::PaymentMethodData::PayLater(pay_later) => Some((
common_enums::PaymentMethod::PayLater,
pay_later.get_payment_method_type(),
None,
)),
- api_models::payments::PaymentMethodData::BankRedirect(bank_redirect) => Some((
+ domain::PaymentMethodData::BankRedirect(bank_redirect) => Some((
common_enums::PaymentMethod::BankRedirect,
bank_redirect.get_payment_method_type(),
None,
)),
- api_models::payments::PaymentMethodData::BankDebit(bank_debit) => Some((
+ domain::PaymentMethodData::BankDebit(bank_debit) => Some((
common_enums::PaymentMethod::BankDebit,
bank_debit.get_payment_method_type(),
None,
)),
- api_models::payments::PaymentMethodData::BankTransfer(bank_transfer) => Some((
+ domain::PaymentMethodData::BankTransfer(bank_transfer) => Some((
common_enums::PaymentMethod::BankTransfer,
bank_transfer.get_payment_method_type(),
None,
)),
- api_models::payments::PaymentMethodData::Crypto(crypto) => Some((
+ domain::PaymentMethodData::Crypto(crypto) => Some((
common_enums::PaymentMethod::Crypto,
crypto.get_payment_method_type(),
None,
)),
- api_models::payments::PaymentMethodData::MandatePayment => None,
- api_models::payments::PaymentMethodData::Reward => None,
- api_models::payments::PaymentMethodData::RealTimePayment(real_time_payment) => Some((
+ domain::PaymentMethodData::MandatePayment => None,
+ domain::PaymentMethodData::Reward => None,
+ domain::PaymentMethodData::RealTimePayment(real_time_payment) => Some((
common_enums::PaymentMethod::RealTimePayment,
real_time_payment.get_payment_method_type(),
None,
)),
- api_models::payments::PaymentMethodData::Upi(upi_data) => Some((
+ domain::PaymentMethodData::Upi(upi_data) => Some((
common_enums::PaymentMethod::Upi,
upi_data.get_payment_method_type(),
None,
)),
- api_models::payments::PaymentMethodData::Voucher(voucher) => Some((
+ domain::PaymentMethodData::Voucher(voucher) => Some((
common_enums::PaymentMethod::Voucher,
voucher.get_payment_method_type(),
None,
)),
- api_models::payments::PaymentMethodData::GiftCard(gift_card) => Some((
+ domain::PaymentMethodData::GiftCard(gift_card) => Some((
common_enums::PaymentMethod::GiftCard,
gift_card.get_payment_method_type(),
None,
)),
- api_models::payments::PaymentMethodData::OpenBanking(ob_data) => Some((
+ domain::PaymentMethodData::OpenBanking(ob_data) => Some((
common_enums::PaymentMethod::OpenBanking,
ob_data.get_payment_method_type(),
None,
)),
- api_models::payments::PaymentMethodData::CardToken(_) => None,
+ domain::PaymentMethodData::CardToken(_) => None,
+ domain::PaymentMethodData::NetworkToken(_) => None,
}
}
@@ -4853,7 +4848,7 @@ pub async fn get_payment_method_details_from_payment_token(
payment_intent: &PaymentIntent,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
-) -> RouterResult<Option<(api::PaymentMethodData, enums::PaymentMethod)>> {
+) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> {
let hyperswitch_token = if let Some(token) = payment_attempt.payment_token.clone() {
let redis_conn = state
.store
@@ -5028,7 +5023,7 @@ pub async fn get_payment_external_authentication_flow_during_confirm<F: Clone>(
connector_supports_separate_authn.is_some()
);
let card_number = payment_data.payment_method_data.as_ref().and_then(|pmd| {
- if let api_models::payments::PaymentMethodData::Card(card) = pmd {
+ if let domain::PaymentMethodData::Card(card) = pmd {
Some(card.card_number.clone())
} else {
None
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index cd932fd54a8..4f1d5822315 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -134,7 +134,7 @@ pub trait Domain<F: Clone, R>: Send + Sync {
business_profile: Option<&domain::BusinessProfile>,
) -> RouterResult<(
BoxedOperation<'a, F, R>,
- Option<api::PaymentMethodData>,
+ Option<domain::PaymentMethodData>,
Option<String>,
)>;
@@ -194,7 +194,7 @@ pub trait Domain<F: Clone, R>: Send + Sync {
_state: &SessionState,
_payment_id: &str,
_business_profile: &domain::BusinessProfile,
- _payment_method_data: &Option<api::PaymentMethodData>,
+ _payment_method_data: &Option<domain::PaymentMethodData>,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
@@ -306,7 +306,7 @@ where
_business_profile: Option<&domain::BusinessProfile>,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsRetrieveRequest>,
- Option<api::PaymentMethodData>,
+ Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
@@ -369,7 +369,7 @@ where
_business_profile: Option<&domain::BusinessProfile>,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsCaptureRequest>,
- Option<api::PaymentMethodData>,
+ Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
@@ -444,7 +444,7 @@ where
_business_profile: Option<&domain::BusinessProfile>,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsCancelRequest>,
- Option<api::PaymentMethodData>,
+ Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
@@ -508,7 +508,7 @@ where
_business_profile: Option<&domain::BusinessProfile>,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsRejectRequest>,
- Option<api::PaymentMethodData>,
+ Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
index 598c2216fb3..8d4e6f7a5f2 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -316,7 +316,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co
payment_method_data: request
.payment_method_data
.as_ref()
- .and_then(|pmd| pmd.payment_method_data.clone()),
+ .and_then(|pmd| pmd.payment_method_data.clone().map(Into::into)),
payment_method_info,
force_sync: None,
refunds: vec![],
@@ -401,7 +401,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for CompleteAuthorize {
business_profile: Option<&domain::BusinessProfile>,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsRequest>,
- Option<api::PaymentMethodData>,
+ Option<domain::PaymentMethodData>,
Option<String>,
)> {
let (op, payment_method_data, pm_id) = helpers::make_pm_data(
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 28533047214..f56009c8e28 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -4,7 +4,7 @@ use api_models::{
admin::ExtendedCardInfoConfig,
enums::FrmSuggestion,
payment_methods::PaymentMethodsData,
- payments::{AdditionalPaymentData, ExtendedCardInfo},
+ payments::{AdditionalPaymentData, ExtendedCardInfo, GetAddressFromPaymentMethodData},
};
use async_trait::async_trait;
use common_utils::{
@@ -469,9 +469,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
let additional_pm_data_fut = tokio::spawn(
async move {
Ok(n_request_payment_method_data
- .async_map(|payment_method_data| async move {
+ .async_and_then(|payment_method_data| async move {
helpers::get_additional_payment_data(
- &payment_method_data,
+ &payment_method_data.into(),
store.as_ref(),
profile_id.as_ref(),
)
@@ -640,6 +640,24 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
.as_ref()
.map(|payment_method_billing| payment_method_billing.address_id.clone());
+ let address = PaymentAddress::new(
+ shipping_address.as_ref().map(From::from),
+ billing_address.as_ref().map(From::from),
+ payment_method_billing.as_ref().map(From::from),
+ business_profile.use_billing_as_payment_method_billing,
+ );
+
+ let payment_method_data_billing = request
+ .payment_method_data
+ .as_ref()
+ .and_then(|pmd| pmd.payment_method_data.as_ref())
+ .and_then(|payment_method_data_billing| {
+ payment_method_data_billing.get_billing_address()
+ });
+
+ let unified_address =
+ address.unify_with_payment_method_data_billing(payment_method_data_billing);
+
// If processor_payment_token is passed in request then populating the same in PaymentData
let mandate_id = request
.recurring_details
@@ -677,15 +695,10 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
setup_mandate,
customer_acceptance: customer_acceptance.map(From::from),
token,
- address: PaymentAddress::new(
- shipping_address.as_ref().map(From::from),
- billing_address.as_ref().map(From::from),
- payment_method_billing.as_ref().map(From::from),
- business_profile.use_billing_as_payment_method_billing,
- ),
+ address: unified_address,
token_data,
confirm: request.confirm,
- payment_method_data: payment_method_data_after_card_bin_call,
+ payment_method_data: payment_method_data_after_card_bin_call.map(Into::into),
payment_method_info,
force_sync: None,
refunds: vec![],
@@ -762,7 +775,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm {
business_profile: Option<&domain::BusinessProfile>,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsRequest>,
- Option<api::PaymentMethodData>,
+ Option<domain::PaymentMethodData>,
Option<String>,
)> {
let (op, payment_method_data, pm_id) = helpers::make_pm_data(
@@ -946,9 +959,9 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm {
state: &SessionState,
payment_id: &str,
business_profile: &domain::BusinessProfile,
- payment_method_data: &Option<api::PaymentMethodData>,
+ payment_method_data: &Option<domain::PaymentMethodData>,
) -> CustomResult<(), errors::ApiErrorResponse> {
- if let (Some(true), Some(api::PaymentMethodData::Card(card)), Some(merchant_config)) = (
+ if let (Some(true), Some(domain::PaymentMethodData::Card(card)), Some(merchant_config)) = (
business_profile.is_extended_card_info_enabled,
payment_method_data,
business_profile.extended_card_info_config.clone(),
@@ -1102,6 +1115,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
+
let payment_experience = payment_data.payment_attempt.payment_experience;
let additional_pm_data = payment_data
.payment_method_data
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 72266e647e9..97bc0a80c48 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -2,6 +2,7 @@ use std::marker::PhantomData;
use api_models::{
enums::FrmSuggestion, mandates::RecurringDetails, payment_methods::PaymentMethodsData,
+ payments::GetAddressFromPaymentMethodData,
};
use async_trait::async_trait;
use common_utils::{
@@ -482,6 +483,24 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
let amount = payment_attempt.get_total_amount().into();
+ let address = PaymentAddress::new(
+ shipping_address.as_ref().map(From::from),
+ billing_address.as_ref().map(From::from),
+ payment_method_billing_address.as_ref().map(From::from),
+ business_profile.use_billing_as_payment_method_billing,
+ );
+
+ let payment_method_data_billing = request
+ .payment_method_data
+ .as_ref()
+ .and_then(|pmd| pmd.payment_method_data.as_ref())
+ .and_then(|payment_method_data_billing| {
+ payment_method_data_billing.get_billing_address()
+ });
+
+ let unified_address =
+ address.unify_with_payment_method_data_billing(payment_method_data_billing);
+
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
@@ -494,15 +513,10 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
setup_mandate,
customer_acceptance,
token,
- address: PaymentAddress::new(
- shipping_address.as_ref().map(From::from),
- billing_address.as_ref().map(From::from),
- payment_method_billing_address.as_ref().map(From::from),
- business_profile.use_billing_as_payment_method_billing,
- ),
+ address: unified_address,
token_data: None,
confirm: request.confirm,
- payment_method_data: payment_method_data_after_card_bin_call,
+ payment_method_data: payment_method_data_after_card_bin_call.map(Into::into),
payment_method_info,
refunds: vec![],
disputes: vec![],
@@ -579,7 +593,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentCreate {
business_profile: Option<&domain::BusinessProfile>,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsRequest>,
- Option<api::PaymentMethodData>,
+ Option<domain::PaymentMethodData>,
Option<String>,
)> {
helpers::make_pm_data(
@@ -891,11 +905,11 @@ impl PaymentCreate {
.payment_method_data
.as_ref()
.and_then(|payment_method_data_request| {
- payment_method_data_request.payment_method_data.as_ref()
+ payment_method_data_request.payment_method_data.clone()
})
- .async_map(|payment_method_data| async {
+ .async_and_then(|payment_method_data| async {
helpers::get_additional_payment_data(
- payment_method_data,
+ &payment_method_data.into(),
&*state.store,
&profile_id,
)
@@ -907,7 +921,7 @@ impl PaymentCreate {
// If recurring payment is made using payment_method_id, then fetch payment_method_data from retrieved payment_method object
additional_pm_data = payment_method_info
.as_ref()
- .async_map(|pm_info| async {
+ .async_and_then(|pm_info| async {
crypto_operation::<serde_json::Value, masking::WithType>(
&state.into(),
type_name!(PaymentMethod),
@@ -937,10 +951,9 @@ impl PaymentCreate {
})
})
.await
- .flatten()
.map(|card| {
api_models::payments::AdditionalPaymentData::Card(Box::new(card.into()))
- })
+ });
};
let additional_pm_data_value = additional_pm_data
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index cae11d7afd8..8d6597efdd6 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -332,7 +332,7 @@ where
_business_profile: Option<&domain::BusinessProfile>,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsSessionRequest>,
- Option<api::PaymentMethodData>,
+ Option<domain::PaymentMethodData>,
Option<String>,
)> {
//No payment method data for this operation
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index c500336efda..ae9397aa8ec 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -304,7 +304,7 @@ where
business_profile: Option<&domain::BusinessProfile>,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsStartRequest>,
- Option<api::PaymentMethodData>,
+ Option<domain::PaymentMethodData>,
Option<String>,
)> {
if payment_data
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index 84abf71d07a..587bdc8ef00 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -92,7 +92,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus {
_business_profile: Option<&domain::BusinessProfile>,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsRequest>,
- Option<api::PaymentMethodData>,
+ Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 104c43f79f4..b2ad13ee0d8 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -451,7 +451,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
payment_method_data: request
.payment_method_data
.as_ref()
- .and_then(|pmd| pmd.payment_method_data.clone()),
+ .and_then(|pmd| pmd.payment_method_data.clone().map(Into::into)),
payment_method_info,
force_sync: None,
refunds: vec![],
@@ -528,7 +528,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentUpdate {
business_profile: Option<&domain::BusinessProfile>,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsRequest>,
- Option<api::PaymentMethodData>,
+ Option<domain::PaymentMethodData>,
Option<String>,
)> {
helpers::make_pm_data(
diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
index f027b7e0a9e..31883042eca 100644
--- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
+++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
@@ -322,7 +322,7 @@ impl<F: Clone + Send> Domain<F, PaymentsIncrementalAuthorizationRequest>
_business_profile: Option<&domain::BusinessProfile>,
) -> RouterResult<(
BoxedOperation<'a, F, PaymentsIncrementalAuthorizationRequest>,
- Option<api::PaymentMethodData>,
+ Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index 455fa4cea52..a989e30d8ea 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -195,7 +195,7 @@ where
.payment_method_data
.as_ref()
.and_then(|pm_data| match pm_data {
- api::PaymentMethodData::Card(card) => card.card_network.clone(),
+ domain::PaymentMethodData::Card(card) => card.card_network.clone(),
_ => None,
}),
@@ -207,7 +207,7 @@ where
.payment_method_data
.as_ref()
.and_then(|pm_data| match pm_data {
- api::PaymentMethodData::Card(card) => {
+ domain::PaymentMethodData::Card(card) => {
Some(card.card_number.peek().chars().take(6).collect())
}
_ => None,
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 404eb4bae76..298106cfc76 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -1,8 +1,8 @@
use std::{fmt::Debug, marker::PhantomData, str::FromStr};
use api_models::payments::{
- Address, CustomerDetailsResponse, FrmMessage, GetAddressFromPaymentMethodData,
- PaymentChargeRequest, PaymentChargeResponse, RequestSurchargeDetails,
+ Address, CustomerDetailsResponse, FrmMessage, PaymentChargeRequest, PaymentChargeResponse,
+ RequestSurchargeDetails,
};
#[cfg(feature = "payouts")]
use api_models::payouts::PayoutAttemptResponse;
@@ -137,11 +137,6 @@ where
Some(merchant_connector_account),
);
- let payment_method_data_billing = payment_data
- .payment_method_data
- .as_ref()
- .and_then(|payment_method_data| payment_method_data.get_billing_address());
-
router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_account.get_id().clone(),
@@ -154,9 +149,7 @@ where
connector_auth_type: auth_type,
description: payment_data.payment_intent.description.clone(),
return_url: payment_data.payment_intent.return_url.clone(),
- address: payment_data
- .address
- .unify_with_payment_method_data_billing(payment_method_data_billing),
+ address: payment_data.address.clone(),
auth_type: payment_data
.payment_attempt
.authentication_type
@@ -584,7 +577,7 @@ where
services::ApplicationResponse::Form(Box::new(services::RedirectionFormData {
redirect_form: form,
- payment_method_data: payment_data.payment_method_data,
+ payment_method_data: payment_data.payment_method_data.map(Into::into),
amount,
currency: currency.to_string(),
}))
@@ -1350,7 +1343,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz
// payment_method_data is not required during recurring mandate payment, in such case keep default PaymentMethodData as MandatePayment
let payment_method_data = payment_data.payment_method_data.or_else(|| {
if payment_data.mandate_id.is_some() {
- Some(api_models::payments::PaymentMethodData::MandatePayment)
+ Some(domain::PaymentMethodData::MandatePayment)
} else {
None
}
@@ -1392,9 +1385,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz
.clone();
Ok(Self {
- payment_method_data: From::from(
- payment_method_data.get_required_value("payment_method_data")?,
- ),
+ payment_method_data: (payment_method_data.get_required_value("payment_method_data")?),
setup_future_usage: payment_data.payment_intent.setup_future_usage,
mandate_id: payment_data.mandate_id.clone(),
off_session: payment_data.mandate_id.as_ref().map(|_| true),
@@ -1748,11 +1739,9 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ
confirm: true,
amount: Some(amount.get_amount_as_i64()), //need to change once we move to connector module
minor_amount: Some(amount),
- payment_method_data: From::from(
- payment_data
- .payment_method_data
- .get_required_value("payment_method_data")?,
- ),
+ payment_method_data: (payment_data
+ .payment_method_data
+ .get_required_value("payment_method_data")?),
statement_descriptor_suffix: payment_data.payment_intent.statement_descriptor_suffix,
setup_future_usage: payment_data.payment_intent.setup_future_usage,
off_session: payment_data.mandate_id.as_ref().map(|_| true),
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index fae690732e0..64c1918c5e5 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -3,7 +3,6 @@ use std::{collections::HashMap, str::FromStr};
use api_models::{
enums,
payment_methods::{self, BankAccountAccessCreds},
- payments::{AddressDetails, BankDebitBilling, BankDebitData, PaymentMethodData},
};
use common_enums::{enums::MerchantStorageScheme, PaymentMethodType};
use hex;
@@ -49,7 +48,6 @@ use crate::{
storage,
transformers::ForeignTryFrom,
},
- utils::ext_traits::OptionExt,
};
pub async fn create_link_token(
@@ -723,8 +721,8 @@ pub async fn retrieve_payment_method_from_auth_service(
key_store: &domain::MerchantKeyStore,
auth_token: &payment_methods::BankAccountTokenData,
payment_intent: &PaymentIntent,
- customer: &Option<domain::Customer>,
-) -> RouterResult<Option<(PaymentMethodData, enums::PaymentMethod)>> {
+ _customer: &Option<domain::Customer>,
+) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> {
let db = state.store.as_ref();
let connector = PaymentAuthConnectorData::get_connector_by_name(
@@ -814,84 +812,25 @@ pub async fn retrieve_payment_method_from_auth_service(
.ok();
}
- let address = oss_helpers::get_address_by_id(
- state,
- payment_intent.billing_address_id.clone(),
- key_store,
- &payment_intent.payment_id,
- merchant_account.get_id(),
- merchant_account.storage_scheme,
- )
- .await?;
-
- let name = address
- .as_ref()
- .and_then(|addr| addr.first_name.clone().map(|name| name.into_inner()))
- .ok_or(ApiErrorResponse::GenericNotFoundError {
- message: "billing_first_name not found".to_string(),
- })
- .attach_printable("billing_first_name not found")?;
-
- let address_details = address.clone().map(|addr| {
- let line1 = addr.line1.map(|line1| line1.into_inner());
- let line2 = addr.line2.map(|line2| line2.into_inner());
- let line3 = addr.line3.map(|line3| line3.into_inner());
- let zip = addr.zip.map(|zip| zip.into_inner());
- let state = addr.state.map(|state| state.into_inner());
- let first_name = addr.first_name.map(|first_name| first_name.into_inner());
- let last_name = addr.last_name.map(|last_name| last_name.into_inner());
-
- AddressDetails {
- city: addr.city,
- country: addr.country,
- line1,
- line2,
- line3,
- zip,
- state,
- first_name,
- last_name,
- }
- });
-
- let email = customer
- .as_ref()
- .and_then(|customer| customer.email.clone())
- .map(common_utils::pii::Email::from)
- .get_required_value("email")?;
-
- let billing_details = BankDebitBilling {
- name: Some(name),
- email: Some(email),
- address: address_details,
- };
-
let payment_method_data = match &bank_account.account_details {
pm_auth_types::PaymentMethodTypeDetails::Ach(ach) => {
- PaymentMethodData::BankDebit(BankDebitData::AchBankDebit {
- billing_details: Some(billing_details),
+ domain::PaymentMethodData::BankDebit(domain::BankDebitData::AchBankDebit {
account_number: ach.account_number.clone(),
routing_number: ach.routing_number.clone(),
- card_holder_name: None,
- bank_account_holder_name: None,
bank_name: None,
bank_type,
bank_holder_type: None,
})
}
pm_auth_types::PaymentMethodTypeDetails::Bacs(bacs) => {
- PaymentMethodData::BankDebit(BankDebitData::BacsBankDebit {
- billing_details: Some(billing_details),
+ domain::PaymentMethodData::BankDebit(domain::BankDebitData::BacsBankDebit {
account_number: bacs.account_number.clone(),
sort_code: bacs.sort_code.clone(),
- bank_account_holder_name: None,
})
}
pm_auth_types::PaymentMethodTypeDetails::Sepa(sepa) => {
- PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit {
- billing_details: Some(billing_details),
+ domain::PaymentMethodData::BankDebit(domain::BankDebitData::SepaBankDebit {
iban: sepa.iban.clone(),
- bank_account_holder_name: None,
})
}
};
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 3049a49c601..c715594e8d5 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -33,6 +33,7 @@ pub use hyperswitch_domain_models::{
GenericLinks, PaymentLinkAction, PaymentLinkFormData, PaymentLinkStatusData,
RedirectionFormData,
},
+ payment_method_data::PaymentMethodData,
router_response_types::RedirectForm,
};
pub use hyperswitch_interfaces::{
@@ -1251,7 +1252,7 @@ impl Authenticate for api_models::payments::PaymentsRejectRequest {}
pub fn build_redirection_form(
form: &RedirectForm,
- payment_method_data: Option<api_models::payments::PaymentMethodData>,
+ payment_method_data: Option<PaymentMethodData>,
amount: String,
currency: String,
config: Settings,
@@ -1326,17 +1327,16 @@ pub fn build_redirection_form(
RedirectForm::BlueSnap {
payment_fields_token,
} => {
- let card_details =
- if let Some(api::PaymentMethodData::Card(ccard)) = payment_method_data {
- format!(
- "var saveCardDirectly={{cvv: \"{}\",amount: {},currency: \"{}\"}};",
- ccard.card_cvc.peek(),
- amount,
- currency
- )
- } else {
- "".to_string()
- };
+ let card_details = if let Some(PaymentMethodData::Card(ccard)) = payment_method_data {
+ format!(
+ "var saveCardDirectly={{cvv: \"{}\",amount: {},currency: \"{}\"}};",
+ ccard.card_cvc.peek(),
+ amount,
+ currency
+ )
+ } else {
+ "".to_string()
+ };
let bluesnap_sdk_url = config.connectors.bluesnap.secondary_base_url;
maud::html! {
(maud::DOCTYPE)
diff --git a/crates/router/src/types/domain/payments.rs b/crates/router/src/types/domain/payments.rs
index 1d3275985f6..1cf36bc4428 100644
--- a/crates/router/src/types/domain/payments.rs
+++ b/crates/router/src/types/domain/payments.rs
@@ -6,6 +6,8 @@ pub use hyperswitch_domain_models::payment_method_data::{
GooglePayThirdPartySdkData, GooglePayWalletData, GpayTokenizationData, IndomaretVoucherData,
KakaoPayRedirection, MbWayRedirection, MifinityData, OpenBankingData, PayLaterData,
PaymentMethodData, RealTimePaymentData, SamsungPayWalletData, SepaAndBacsBillingDetails,
- SwishQrData, TouchNGoRedirection, UpiCollectData, UpiData, UpiIntentData, VoucherData,
- WalletData, WeChatPayQr,
+ SwishQrData, TokenizedBankRedirectValue1, TokenizedBankRedirectValue2,
+ TokenizedBankTransferValue1, TokenizedBankTransferValue2, TokenizedCardValue1,
+ TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2, TouchNGoRedirection,
+ UpiCollectData, UpiData, UpiIntentData, VoucherData, WalletData, WeChatPayQr,
};
diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs
index 05e3e566c07..31b039ab454 100644
--- a/crates/router/src/types/storage/payment_method.rs
+++ b/crates/router/src/types/storage/payment_method.rs
@@ -10,7 +10,7 @@ pub use diesel_models::payment_method::{
TokenizeCoreWorkflow,
};
-use crate::types::api::{self, payments};
+use crate::types::{api, domain};
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
@@ -29,7 +29,7 @@ pub struct CardTokenData {
#[derive(Debug, Clone, serde::Serialize, Default, serde::Deserialize)]
pub struct PaymentMethodDataWithId {
pub payment_method: Option<enums::PaymentMethod>,
- pub payment_method_data: Option<payments::PaymentMethodData>,
+ pub payment_method_data: Option<domain::PaymentMethodData>,
pub payment_method_id: Option<String>,
}
|
refactor
|
Use hyperswitch_domain_models within the Payments Core instead of api_models (#5511)
|
d5cbc1d46c79ada41d2cc7bef5ce6411a67e1136
|
2025-02-06 14:57:37
|
Pa1NarK
|
ci(cypress): fix nmi and paypal (#7173)
| false
|
diff --git a/.github/workflows/cypress-tests-runner.yml b/.github/workflows/cypress-tests-runner.yml
index 67efcdb0ea3..dbef78355de 100644
--- a/.github/workflows/cypress-tests-runner.yml
+++ b/.github/workflows/cypress-tests-runner.yml
@@ -13,7 +13,7 @@ concurrency:
env:
CARGO_INCREMENTAL: 0
CARGO_NET_RETRY: 10
- PAYMENTS_CONNECTORS: "cybersource"
+ PAYMENTS_CONNECTORS: "cybersource stripe"
PAYOUTS_CONNECTORS: "wise"
RUST_BACKTRACE: short
RUSTUP_MAX_RETRIES: 10
diff --git a/cypress-tests/cypress/e2e/configs/Payment/Utils.js b/cypress-tests/cypress/e2e/configs/Payment/Utils.js
index 5a9baa32d73..b3de4db78d4 100644
--- a/cypress-tests/cypress/e2e/configs/Payment/Utils.js
+++ b/cypress-tests/cypress/e2e/configs/Payment/Utils.js
@@ -4,7 +4,7 @@ import { connectorDetails as adyenConnectorDetails } from "./Adyen.js";
import { connectorDetails as bankOfAmericaConnectorDetails } from "./BankOfAmerica.js";
import { connectorDetails as bluesnapConnectorDetails } from "./Bluesnap.js";
import { connectorDetails as checkoutConnectorDetails } from "./Checkout.js";
-import { connectorDetails as CommonConnectorDetails } from "./Commons.js";
+import { connectorDetails as commonConnectorDetails } from "./Commons.js";
import { updateDefaultStatusCode } from "./Modifiers.js";
import { connectorDetails as cybersourceConnectorDetails } from "./Cybersource.js";
import { connectorDetails as datatransConnectorDetails } from "./Datatrans.js";
@@ -32,7 +32,7 @@ const connectorDetails = {
bankofamerica: bankOfAmericaConnectorDetails,
bluesnap: bluesnapConnectorDetails,
checkout: checkoutConnectorDetails,
- commons: CommonConnectorDetails,
+ commons: commonConnectorDetails,
cybersource: cybersourceConnectorDetails,
deutschebank: deutschebankConnectorDetails,
fiservemea: fiservemeaConnectorDetails,
@@ -307,3 +307,26 @@ export function updateBusinessProfile(
profilePrefix
);
}
+
+export const CONNECTOR_LISTS = {
+ // Exclusion lists (skip these connectors)
+ EXCLUDE: {
+ CONNECTOR_AGNOSTIC_NTID: ["paypal"],
+ // Add more exclusion lists
+ },
+
+ // Inclusion lists (only run for these connectors)
+ INCLUDE: {
+ MANDATES_USING_NTID_PROXY: ["cybersource"],
+ // Add more inclusion lists
+ },
+};
+
+// Helper functions
+export const shouldExcludeConnector = (connectorId, list) => {
+ return list.includes(connectorId);
+};
+
+export const shouldIncludeConnector = (connectorId, list) => {
+ return !list.includes(connectorId);
+};
diff --git a/cypress-tests/cypress/e2e/spec/Payment/00020-MandatesUsingNTIDProxy.cy.js b/cypress-tests/cypress/e2e/spec/Payment/00020-MandatesUsingNTIDProxy.cy.js
index 1554436abfb..67697cac6c1 100644
--- a/cypress-tests/cypress/e2e/spec/Payment/00020-MandatesUsingNTIDProxy.cy.js
+++ b/cypress-tests/cypress/e2e/spec/Payment/00020-MandatesUsingNTIDProxy.cy.js
@@ -6,11 +6,31 @@ let globalState;
let connector;
describe("Card - Mandates using Network Transaction Id flow test", () => {
- before("seed global state", () => {
- cy.task("getGlobalState").then((state) => {
- globalState = new State(state);
- connector = globalState.get("connectorId");
- });
+ before(function () {
+ // Changed to regular function instead of arrow function
+ let skip = false;
+
+ cy.task("getGlobalState")
+ .then((state) => {
+ globalState = new State(state);
+ connector = globalState.get("connectorId");
+
+ // Skip the test if the connector is not in the inclusion list
+ // This is done because only cybersource is known to support at present
+ if (
+ utils.shouldIncludeConnector(
+ connector,
+ utils.CONNECTOR_LISTS.INCLUDE.MANDATES_USING_NTID_PROXY
+ )
+ ) {
+ skip = true;
+ }
+ })
+ .then(() => {
+ if (skip) {
+ this.skip();
+ }
+ });
});
afterEach("flush global state", () => {
@@ -20,12 +40,6 @@ describe("Card - Mandates using Network Transaction Id flow test", () => {
context(
"Card - NoThreeDS Create and Confirm Automatic MIT payment flow test",
() => {
- beforeEach(function () {
- if (connector !== "cybersource") {
- this.skip();
- }
- });
-
it("Confirm No 3DS MIT", () => {
const data = getConnectorDetails(globalState.get("connectorId"))[
"card_pm"
@@ -46,12 +60,6 @@ describe("Card - Mandates using Network Transaction Id flow test", () => {
context(
"Card - NoThreeDS Create and Confirm Manual MIT payment flow test",
() => {
- beforeEach(function () {
- if (connector !== "cybersource") {
- this.skip();
- }
- });
-
it("Confirm No 3DS MIT", () => {
const data = getConnectorDetails(globalState.get("connectorId"))[
"card_pm"
@@ -72,12 +80,6 @@ describe("Card - Mandates using Network Transaction Id flow test", () => {
context(
"Card - NoThreeDS Create and Confirm Automatic multiple MITs payment flow test",
() => {
- beforeEach(function () {
- if (connector !== "cybersource") {
- this.skip();
- }
- });
-
it("Confirm No 3DS MIT", () => {
const data = getConnectorDetails(globalState.get("connectorId"))[
"card_pm"
@@ -114,12 +116,6 @@ describe("Card - Mandates using Network Transaction Id flow test", () => {
() => {
let shouldContinue = true;
- beforeEach(function () {
- if (connector !== "cybersource") {
- this.skip();
- }
- });
-
it("Confirm No 3DS MIT 1", () => {
const data = getConnectorDetails(globalState.get("connectorId"))[
"card_pm"
@@ -177,12 +173,6 @@ describe("Card - Mandates using Network Transaction Id flow test", () => {
context(
"Card - ThreeDS Create and Confirm Automatic multiple MITs payment flow test",
() => {
- beforeEach(function () {
- if (connector !== "cybersource") {
- this.skip();
- }
- });
-
it("Confirm No 3DS MIT", () => {
const data = getConnectorDetails(globalState.get("connectorId"))[
"card_pm"
@@ -217,12 +207,6 @@ describe("Card - Mandates using Network Transaction Id flow test", () => {
context(
"Card - ThreeDS Create and Confirm Manual multiple MITs payment flow",
() => {
- beforeEach(function () {
- if (connector !== "cybersource") {
- this.skip();
- }
- });
-
it("Confirm No 3DS MIT", () => {
const data = getConnectorDetails(globalState.get("connectorId"))[
"card_pm"
diff --git a/cypress-tests/cypress/e2e/spec/Payment/00022-Variations.cy.js b/cypress-tests/cypress/e2e/spec/Payment/00022-Variations.cy.js
index f1499dc93bd..5a1f765cf62 100644
--- a/cypress-tests/cypress/e2e/spec/Payment/00022-Variations.cy.js
+++ b/cypress-tests/cypress/e2e/spec/Payment/00022-Variations.cy.js
@@ -222,6 +222,14 @@ describe("Corner cases", () => {
if (shouldContinue) shouldContinue = utils.should_continue_further(data);
});
+ it("Retrieve payment", () => {
+ const data = getConnectorDetails(globalState.get("connectorId"))[
+ "card_pm"
+ ]["No3DSManualCapture"];
+
+ cy.retrievePaymentCallTest(globalState, data);
+ });
+
it("Capture call", () => {
const data = getConnectorDetails(globalState.get("commons"))["card_pm"][
"CaptureGreaterAmount"
diff --git a/cypress-tests/cypress/e2e/spec/Payment/00024-ConnectorAgnosticNTID.cy.js b/cypress-tests/cypress/e2e/spec/Payment/00024-ConnectorAgnosticNTID.cy.js
index 4db0ad99900..308a8c036ca 100644
--- a/cypress-tests/cypress/e2e/spec/Payment/00024-ConnectorAgnosticNTID.cy.js
+++ b/cypress-tests/cypress/e2e/spec/Payment/00024-ConnectorAgnosticNTID.cy.js
@@ -4,6 +4,7 @@ import { payment_methods_enabled } from "../../configs/Payment/Commons";
import getConnectorDetails, * as utils from "../../configs/Payment/Utils";
let globalState;
+let connector;
/*
Flow:
@@ -32,10 +33,30 @@ Flow:
*/
describe("Connector Agnostic Tests", () => {
- before("seed global state", () => {
- cy.task("getGlobalState").then((state) => {
- globalState = new State(state);
- });
+ before(function () {
+ // Changed to regular function instead of arrow function
+ let skip = false;
+
+ cy.task("getGlobalState")
+ .then((state) => {
+ globalState = new State(state);
+ connector = globalState.get("connectorId");
+
+ // Skip running test against a connector that is added in the exclude list
+ if (
+ utils.shouldExcludeConnector(
+ connector,
+ utils.CONNECTOR_LISTS.EXCLUDE.CONNECTOR_AGNOSTIC_NTID
+ )
+ ) {
+ skip = true;
+ }
+ })
+ .then(() => {
+ if (skip) {
+ this.skip();
+ }
+ });
});
after("flush global state", () => {
|
ci
|
fix nmi and paypal (#7173)
|
f48d6c4a2ba53a12b81eb491bd1cadc2b2be6a09
|
2023-07-13 12:30:56
|
Kritik Modi
|
fix(compatibility): fix AddressDetails in the customers flow (#1654)
| false
|
diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs
index 1c28617d745..d8c864746a8 100644
--- a/crates/api_models/src/customers.rs
+++ b/crates/api_models/src/customers.rs
@@ -3,6 +3,8 @@ use masking::Secret;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
+use crate::payments;
+
/// The customer details
#[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)]
pub struct CustomerRequest {
@@ -30,18 +32,8 @@ pub struct CustomerRequest {
#[schema(max_length = 255, example = "+65")]
pub phone_country_code: Option<String>,
/// The address for the customer
- #[schema(value_type = Option<Object>,example = json!({
- "city": "Bangalore",
- "country": "IN",
- "line1": "Hyperswitch router",
- "line2": "Koramangala",
- "line3": "Stallion",
- "state": "Karnataka",
- "zip": "560095",
- "first_name": "John",
- "last_name": "Doe"
- }))]
- pub address: Option<pii::SecretSerdeValue>,
+ #[schema(value_type = Option<AddressDetails>)]
+ pub address: Option<payments::AddressDetails>,
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500
/// characters long. Metadata is useful for storing additional, structured information on an
/// object.
@@ -70,18 +62,8 @@ pub struct CustomerResponse {
#[schema(max_length = 255, example = "First Customer")]
pub description: Option<String>,
/// The address for the customer
- #[schema(value_type = Option<Object>,example = json!({
- "city": "Bangalore",
- "country": "IN",
- "line1": "Hyperswitch router",
- "line2": "Koramangala",
- "line3": "Stallion",
- "state": "Karnataka",
- "zip": "560095",
- "first_name": "John",
- "last_name": "Doe"
- }))]
- pub address: Option<Secret<serde_json::Value>>,
+ #[schema(value_type = Option<AddressDetails>)]
+ pub address: Option<payments::AddressDetails>,
/// A timestamp (ISO 8601 code) that determines when the customer was created
#[schema(value_type = PrimitiveDateTime,example = "2023-01-18T11:04:09.922Z")]
#[serde(with = "custom_serde::iso8601")]
diff --git a/crates/router/src/compatibility/stripe/customers/types.rs b/crates/router/src/compatibility/stripe/customers/types.rs
index c605a4efefe..8298595bbc5 100644
--- a/crates/router/src/compatibility/stripe/customers/types.rs
+++ b/crates/router/src/compatibility/stripe/customers/types.rs
@@ -1,6 +1,6 @@
use std::{convert::From, default::Default};
-use api_models::payment_methods as api_types;
+use api_models::{payment_methods as api_types, payments};
use common_utils::{
crypto::Encryptable,
date_time,
@@ -8,7 +8,29 @@ use common_utils::{
};
use serde::{Deserialize, Serialize};
-use crate::{logger, types::api};
+use crate::{
+ logger,
+ types::{api, api::enums as api_enums},
+};
+
+#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
+pub struct Shipping {
+ pub address: StripeAddressDetails,
+ pub name: Option<masking::Secret<String>>,
+ pub carrier: Option<String>,
+ pub phone: Option<masking::Secret<String>>,
+ pub tracking_number: Option<masking::Secret<String>>,
+}
+
+#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
+pub struct StripeAddressDetails {
+ pub city: Option<String>,
+ pub country: Option<api_enums::CountryAlpha2>,
+ pub line1: Option<masking::Secret<String>>,
+ pub line2: Option<masking::Secret<String>>,
+ pub postal_code: Option<masking::Secret<String>>,
+ pub state: Option<masking::Secret<String>>,
+}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct CreateCustomerRequest {
@@ -16,9 +38,23 @@ pub struct CreateCustomerRequest {
pub invoice_prefix: Option<String>,
pub name: Option<masking::Secret<String>>,
pub phone: Option<masking::Secret<String>>,
- pub address: Option<masking::Secret<serde_json::Value>>,
+ pub address: Option<StripeAddressDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub description: Option<String>,
+ pub shipping: Option<Shipping>,
+ pub payment_method: Option<String>, // not used
+ pub balance: Option<i64>, // not used
+ pub cash_balance: Option<pii::SecretSerdeValue>, // not used
+ pub coupon: Option<String>, // not used
+ pub invoice_settings: Option<pii::SecretSerdeValue>, // not used
+ pub next_invoice_sequence: Option<String>, // not used
+ pub preferred_locales: Option<String>, // not used
+ pub promotion_code: Option<String>, // not used
+ pub source: Option<String>, // not used
+ pub tax: Option<pii::SecretSerdeValue>, // not used
+ pub tax_exempt: Option<String>, // not used
+ pub tax_id_data: Option<String>, // not used
+ pub test_clock: Option<String>, // not used
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
@@ -27,8 +63,21 @@ pub struct CustomerUpdateRequest {
pub email: Option<Email>,
pub phone: Option<masking::Secret<String, masking::WithType>>,
pub name: Option<masking::Secret<String>>,
- pub address: Option<masking::Secret<serde_json::Value>>,
+ pub address: Option<StripeAddressDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
+ pub shipping: Option<Shipping>,
+ pub payment_method: Option<String>, // not used
+ pub balance: Option<i64>, // not used
+ pub cash_balance: Option<pii::SecretSerdeValue>, // not used
+ pub coupon: Option<String>, // not used
+ pub default_source: Option<String>, // not used
+ pub invoice_settings: Option<pii::SecretSerdeValue>, // not used
+ pub next_invoice_sequence: Option<String>, // not used
+ pub preferred_locales: Option<String>, // not used
+ pub promotion_code: Option<String>, // not used
+ pub source: Option<String>, // not used
+ pub tax: Option<pii::SecretSerdeValue>, // not used
+ pub tax_exempt: Option<String>, // not used
}
#[derive(Default, Serialize, PartialEq, Eq)]
@@ -52,6 +101,22 @@ pub struct CustomerDeleteResponse {
pub deleted: bool,
}
+impl From<StripeAddressDetails> for payments::AddressDetails {
+ fn from(address: StripeAddressDetails) -> Self {
+ Self {
+ city: address.city,
+ country: address.country,
+ line1: address.line1,
+ line2: address.line2,
+ zip: address.postal_code,
+ state: address.state,
+ first_name: None,
+ line3: None,
+ last_name: None,
+ }
+ }
+}
+
impl From<CreateCustomerRequest> for api::CustomerRequest {
fn from(req: CreateCustomerRequest) -> Self {
Self {
@@ -61,7 +126,7 @@ impl From<CreateCustomerRequest> for api::CustomerRequest {
email: req.email,
description: req.description,
metadata: req.metadata,
- address: req.address,
+ address: req.address.map(|s| s.into()),
..Default::default()
}
}
@@ -75,6 +140,7 @@ impl From<CustomerUpdateRequest> for api::CustomerRequest {
email: req.email,
description: req.description,
metadata: req.metadata,
+ address: req.address.map(|s| s.into()),
..Default::default()
}
}
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index eaee9c72399..6fe188058b5 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -1,7 +1,4 @@
-use common_utils::{
- crypto::{Encryptable, GcmAes256},
- ext_traits::ValueExt,
-};
+use common_utils::crypto::{Encryptable, GcmAes256};
use error_stack::ResultExt;
use masking::ExposeInterface;
use router_env::{instrument, tracing};
@@ -42,11 +39,7 @@ pub async fn create_customer(
let key = key_store.key.get_inner().peek();
if let Some(addr) = &customer_data.address {
- let customer_address: api_models::payments::AddressDetails = addr
- .peek()
- .clone()
- .parse_value("AddressDetails")
- .change_context(errors::ApiErrorResponse::AddressNotFound)?;
+ let customer_address: api_models::payments::AddressDetails = addr.clone();
let address = async {
Ok(domain::Address {
@@ -333,11 +326,7 @@ pub async fn update_customer(
let key = key_store.key.get_inner().peek();
if let Some(addr) = &update_customer.address {
- let customer_address: api_models::payments::AddressDetails = addr
- .peek()
- .clone()
- .parse_value("AddressDetails")
- .change_context(errors::ApiErrorResponse::AddressNotFound)?;
+ let customer_address: api_models::payments::AddressDetails = addr.clone();
let update_address = async {
Ok(storage::AddressUpdate::Update {
city: customer_address.city,
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 1aba2fd9b36..d4f1d299447 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -3700,8 +3700,11 @@
"maxLength": 255
},
"address": {
- "type": "object",
- "description": "The address for the customer",
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/AddressDetails"
+ }
+ ],
"nullable": true
},
"metadata": {
@@ -3760,8 +3763,11 @@
"maxLength": 255
},
"address": {
- "type": "object",
- "description": "The address for the customer",
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/AddressDetails"
+ }
+ ],
"nullable": true
},
"created_at": {
|
fix
|
fix AddressDetails in the customers flow (#1654)
|
57c9dc414cda688a03ff322479424c7c700345e9
|
2023-07-12 18:13:04
|
github-actions
|
chore(version): v1.3.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e82bc6a4fb4..702a10c1b72 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,22 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 1.3.0 (2023-07-12)
+
+### Features
+
+- **payments:** Dont delete client secret on success status ([#1692](https://github.com/juspay/hyperswitch/pull/1692)) ([`5216d22`](https://github.com/juspay/hyperswitch/commit/5216d22efcd291f7e460d1461ef16cef69ad6bd9))
+- Convert QrData into Qr data image source url ([#1674](https://github.com/juspay/hyperswitch/pull/1674)) ([`55ff761`](https://github.com/juspay/hyperswitch/commit/55ff761e9eca313327f67c1d271ea1672d12c339))
+
+### Refactors
+
+- Include binary name in `crates_to_filter` for logging ([#1689](https://github.com/juspay/hyperswitch/pull/1689)) ([`123b34c`](https://github.com/juspay/hyperswitch/commit/123b34c7dca543194b230bc9e46e14758f8bfb34))
+
+**Full Changelog:** [`v1.2.0...v1.3.0`](https://github.com/juspay/hyperswitch/compare/v1.2.0...v1.3.0)
+
+- - -
+
+
## 1.2.0 (2023-07-11)
### Features
|
chore
|
v1.3.0
|
6c0d136cee106fc25fbcf63e4bbc01b28baa1519
|
2023-06-15 14:07:31
|
Arjun Karthik
|
refactor(api_models): follow naming convention for wallets & paylater payment method data enums (#1338)
| false
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index ee8ef279876..e743e9a853c 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -504,8 +504,8 @@ pub enum PayLaterData {
#[schema(value_type = String)]
billing_name: Secret<String>,
},
- PayBright {},
- Walley {},
+ PayBrightRedirect {},
+ WalleyRedirect {},
}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)]
@@ -809,16 +809,16 @@ pub struct BankDebitBilling {
#[serde(rename_all = "snake_case")]
pub enum WalletData {
/// The wallet data for Ali Pay redirect
- AliPay(AliPayRedirection),
+ AliPayRedirect(AliPayRedirection),
/// The wallet data for Apple pay
ApplePay(ApplePayWalletData),
/// Wallet data for apple pay redirect flow
ApplePayRedirect(Box<ApplePayRedirectData>),
/// The wallet data for Google pay
GooglePay(GooglePayWalletData),
- MbWay(Box<MbWayRedirection>),
+ MbWayRedirect(Box<MbWayRedirection>),
/// The wallet data for MobilePay redirect
- MobilePay(Box<MobilePayRedirection>),
+ MobilePayRedirect(Box<MobilePayRedirection>),
/// This is for paypal redirection
PaypalRedirect(PaypalRedirection),
/// The wallet data for Paypal
diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs
index 01782f8ae15..e831cc4bc57 100644
--- a/crates/router/src/connector/aci/transformers.rs
+++ b/crates/router/src/connector/aci/transformers.rs
@@ -158,14 +158,14 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest {
})),
api::PaymentMethodData::PayLater(_) => PaymentDetails::Klarna,
api::PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
- api_models::payments::WalletData::MbWay(data) => {
+ api_models::payments::WalletData::MbWayRedirect(data) => {
PaymentDetails::Wallet(Box::new(WalletPMData {
payment_brand: PaymentBrand::Mbway,
account_id: Some(data.telephone_number.clone()),
shopper_result_url: item.request.router_return_url.clone(),
}))
}
- api_models::payments::WalletData::AliPay { .. } => {
+ api_models::payments::WalletData::AliPayRedirect { .. } => {
PaymentDetails::Wallet(Box::new(WalletPMData {
payment_brand: PaymentBrand::AliPay,
account_id: None,
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 422f50436e9..a724d87b300 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -1121,20 +1121,20 @@ impl<'a> TryFrom<&api::WalletData> for AdyenPaymentMethod<'a> {
};
Ok(AdyenPaymentMethod::AdyenPaypal(Box::new(wallet)))
}
- api_models::payments::WalletData::AliPay(_) => {
+ api_models::payments::WalletData::AliPayRedirect(_) => {
let alipay_data = AliPayData {
payment_type: PaymentType::Alipay,
};
Ok(AdyenPaymentMethod::AliPay(Box::new(alipay_data)))
}
- api_models::payments::WalletData::MbWay(data) => {
+ api_models::payments::WalletData::MbWayRedirect(data) => {
let mbway_data = MbwayData {
payment_type: PaymentType::Mbway,
telephone_number: data.telephone_number.clone(),
};
Ok(AdyenPaymentMethod::Mbway(Box::new(mbway_data)))
}
- api_models::payments::WalletData::MobilePay(_) => {
+ api_models::payments::WalletData::MobilePayRedirect(_) => {
let data = MobilePayData {
payment_type: PaymentType::MobilePay,
};
@@ -1171,12 +1171,12 @@ impl<'a> TryFrom<&api::PayLaterData> for AdyenPaymentMethod<'a> {
payment_type: PaymentType::Afterpaytouch,
})))
}
- api_models::payments::PayLaterData::PayBright { .. } => {
+ api_models::payments::PayLaterData::PayBrightRedirect { .. } => {
Ok(AdyenPaymentMethod::PayBright(Box::new(PayBrightData {
payment_type: PaymentType::PayBright,
})))
}
- api_models::payments::PayLaterData::Walley { .. } => {
+ api_models::payments::PayLaterData::WalleyRedirect { .. } => {
Ok(AdyenPaymentMethod::Walley(Box::new(WalleyData {
payment_type: PaymentType::Walley,
})))
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 2500365f836..ca0e35d6607 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -1042,7 +1042,7 @@ fn create_stripe_payment_method(
StripePaymentMethodType::Wechatpay,
StripeBillingAddress::default(),
)),
- payments::WalletData::AliPay(_) => Ok((
+ payments::WalletData::AliPayRedirect(_) => Ok((
StripePaymentMethodData::Wallet(StripeWallet::AlipayPayment(AlipayPayment {
payment_method_types: StripePaymentMethodType::Alipay,
payment_method_data_type: StripePaymentMethodType::Alipay,
@@ -2513,7 +2513,7 @@ impl
});
Ok(Self::Wallet(wallet_info))
}
- payments::WalletData::AliPay(_) => {
+ payments::WalletData::AliPayRedirect(_) => {
let wallet_info = StripeWallet::AlipayPayment(AlipayPayment {
payment_method_types: StripePaymentMethodType::Alipay,
payment_method_data_type: StripePaymentMethodType::Alipay,
|
refactor
|
follow naming convention for wallets & paylater payment method data enums (#1338)
|
4f4cbdff21b956b5939cdbe6a4f88f663e6b1281
|
2024-05-02 12:44:35
|
Sakil Mostak
|
feat(connector): [Ebanx] Add payout flows (#4146)
| false
|
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 452ad6332fb..02fac0fbfa5 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -89,7 +89,7 @@ pub enum Connector {
Cryptopay,
Cybersource,
Dlocal,
- // Ebanx,
+ Ebanx,
Fiserv,
Forte,
Globalpay,
@@ -201,6 +201,7 @@ impl Connector {
| Self::Coinbase
| Self::Cryptopay
| Self::Dlocal
+ | Self::Ebanx
| Self::Fiserv
| Self::Forte
| Self::Globalpay
@@ -259,6 +260,7 @@ impl Connector {
| Self::Coinbase
| Self::Cryptopay
| Self::Dlocal
+ | Self::Ebanx
| Self::Fiserv
| Self::Forte
| Self::Globalpay
@@ -345,6 +347,7 @@ pub enum PayoutConnectors {
Stripe,
Wise,
Paypal,
+ Ebanx,
}
#[cfg(feature = "payouts")]
@@ -355,6 +358,7 @@ impl From<PayoutConnectors> for RoutableConnectors {
PayoutConnectors::Stripe => Self::Stripe,
PayoutConnectors::Wise => Self::Wise,
PayoutConnectors::Paypal => Self::Paypal,
+ PayoutConnectors::Ebanx => Self::Ebanx,
}
}
}
@@ -367,6 +371,7 @@ impl From<PayoutConnectors> for Connector {
PayoutConnectors::Stripe => Self::Stripe,
PayoutConnectors::Wise => Self::Wise,
PayoutConnectors::Paypal => Self::Paypal,
+ PayoutConnectors::Ebanx => Self::Ebanx,
}
}
}
@@ -380,6 +385,7 @@ impl TryFrom<Connector> for PayoutConnectors {
Connector::Stripe => Ok(Self::Stripe),
Connector::Wise => Ok(Self::Wise),
Connector::Paypal => Ok(Self::Paypal),
+ Connector::Ebanx => Ok(Self::Ebanx),
_ => Err(format!("Invalid payout connector {}", value)),
}
}
diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs
index 0951f8c9dfc..891033c1aea 100644
--- a/crates/api_models/src/payouts.rs
+++ b/crates/api_models/src/payouts.rs
@@ -189,6 +189,7 @@ pub enum Bank {
Ach(AchBankTransfer),
Bacs(BacsBankTransfer),
Sepa(SepaBankTransfer),
+ Pix(PixBankTransfer),
}
#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
@@ -261,6 +262,29 @@ pub struct SepaBankTransfer {
pub bic: Option<Secret<String>>,
}
+#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
+pub struct PixBankTransfer {
+ /// Bank name
+ #[schema(value_type = Option<String>, example = "Deutsche Bank")]
+ pub bank_name: Option<String>,
+
+ /// Bank branch
+ #[schema(value_type = Option<String>, example = "3707")]
+ pub bank_branch: Option<String>,
+
+ /// Bank account number is an unique identifier assigned by a bank to a customer.
+ #[schema(value_type = String, example = "000123456")]
+ pub bank_account_number: Secret<String>,
+
+ /// Unique key for pix customer
+ #[schema(value_type = String, example = "000123456")]
+ pub pix_key: Secret<String>,
+
+ /// Individual taxpayer identification number
+ #[schema(value_type = Option<String>, example = "000123456")]
+ pub tax_id: Option<Secret<String>>,
+}
+
#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum Wallet {
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 78b7214e68e..5323a2dcf5a 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -128,7 +128,7 @@ pub enum RoutableConnectors {
Cryptopay,
Cybersource,
Dlocal,
- // Ebanx,
+ Ebanx,
Fiserv,
Forte,
Globalpay,
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index 497accc3346..0f5a953b064 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -137,6 +137,7 @@ pub struct ConnectorConfig {
pub opennode: Option<ConnectorTomlConfig>,
pub bambora: Option<ConnectorTomlConfig>,
pub dlocal: Option<ConnectorTomlConfig>,
+ pub ebanx_payout: Option<ConnectorTomlConfig>,
pub fiserv: Option<ConnectorTomlConfig>,
pub forte: Option<ConnectorTomlConfig>,
pub globalpay: Option<ConnectorTomlConfig>,
@@ -219,6 +220,7 @@ impl ConnectorConfig {
PayoutConnectors::Stripe => Ok(connector_data.stripe_payout),
PayoutConnectors::Wise => Ok(connector_data.wise_payout),
PayoutConnectors::Paypal => Ok(connector_data.paypal),
+ PayoutConnectors::Ebanx => Ok(connector_data.ebanx_payout),
}
}
@@ -256,6 +258,7 @@ impl ConnectorConfig {
Connector::Opennode => Ok(connector_data.opennode),
Connector::Bambora => Ok(connector_data.bambora),
Connector::Dlocal => Ok(connector_data.dlocal),
+ Connector::Ebanx => Ok(connector_data.ebanx_payout),
Connector::Fiserv => Ok(connector_data.fiserv),
Connector::Forte => Ok(connector_data.forte),
Connector::Globalpay => Ok(connector_data.globalpay),
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 810143d115b..aa30a480406 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -431,6 +431,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payouts::AchBankTransfer,
api_models::payouts::BacsBankTransfer,
api_models::payouts::SepaBankTransfer,
+ api_models::payouts::PixBankTransfer,
api_models::payouts::PayoutRequest,
api_models::payouts::PayoutAttemptResponse,
api_models::payouts::PayoutActionRequest,
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index bde04877e65..ec55a0be1c8 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -4633,6 +4633,10 @@ impl<F> TryFrom<&AdyenRouterData<&types::PayoutsRouterData<F>>> for AdyenPayoutC
message: "Bank transfer via Bacs is not supported".to_string(),
connector: "Adyen",
})?,
+ payouts::BankPayout::Pix(..) => Err(errors::ConnectorError::NotSupported {
+ message: "Bank transfer via Pix is not supported".to_string(),
+ connector: "Adyen",
+ })?,
};
let bank_data = PayoutBankData { bank: bank_details };
let address: &payments::AddressDetails = item.router_data.get_billing_address()?;
diff --git a/crates/router/src/connector/ebanx.rs b/crates/router/src/connector/ebanx.rs
index 284b592cd07..69cfc501f11 100644
--- a/crates/router/src/connector/ebanx.rs
+++ b/crates/router/src/connector/ebanx.rs
@@ -2,27 +2,29 @@ pub mod transformers;
use std::fmt::Debug;
+#[cfg(feature = "payouts")]
+use common_utils::request::RequestContent;
use error_stack::{report, ResultExt};
-use masking::ExposeInterface;
+#[cfg(feature = "payouts")]
+use router_env::{instrument, tracing};
use transformers as ebanx;
use crate::{
configs::settings,
core::errors::{self, CustomResult},
events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
- },
+ services::{ConnectorIntegration, ConnectorValidation},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, RequestContent, Response,
},
utils::BytesExt,
};
+#[cfg(feature = "payouts")]
+use crate::{
+ headers,
+ services::{self, request},
+};
#[derive(Debug, Clone)]
pub struct Ebanx;
@@ -40,31 +42,34 @@ impl api::RefundExecute for Ebanx {}
impl api::RefundSync for Ebanx {}
impl api::PaymentToken for Ebanx {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Ebanx
-{
- // Not Implemented (R)
-}
+impl api::Payouts for Ebanx {}
+#[cfg(feature = "payouts")]
+impl api::PayoutCancel for Ebanx {}
+#[cfg(feature = "payouts")]
+impl api::PayoutCreate for Ebanx {}
+#[cfg(feature = "payouts")]
+impl api::PayoutEligibility for Ebanx {}
+#[cfg(feature = "payouts")]
+impl api::PayoutQuote for Ebanx {}
+#[cfg(feature = "payouts")]
+impl api::PayoutRecipient for Ebanx {}
+#[cfg(feature = "payouts")]
+impl api::PayoutFulfill for Ebanx {}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Ebanx
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
+ #[cfg(feature = "payouts")]
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
+ _req: &types::RouterData<Flow, Request, Response>,
_connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let mut header = vec![(
+ let header = vec![(
headers::CONTENT_TYPE.to_string(),
- self.get_content_type().to_string().into(),
+ self.common_get_content_type().to_string().into(),
)];
- let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
- header.append(&mut api_key);
Ok(header)
}
}
@@ -86,23 +91,11 @@ impl ConnectorCommon for Ebanx {
connectors.ebanx.base_url.as_ref()
}
- fn get_auth_header(
- &self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let auth = ebanx::EbanxAuthType::try_from(auth_type)
- .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
- Ok(vec![(
- headers::AUTHORIZATION.to_string(),
- auth.api_key.expose().into_masked(),
- )])
- }
-
fn build_error_response(
&self,
- res: Response,
+ res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: ebanx::EbanxErrorResponse =
res.response
.parse_struct("EbanxErrorResponse")
@@ -111,113 +104,82 @@ impl ConnectorCommon for Ebanx {
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- Ok(ErrorResponse {
+ Ok(types::ErrorResponse {
status_code: res.status_code,
- code: response.code,
- message: response.message,
- reason: response.reason,
+ code: response.status_code,
+ message: response.code,
+ reason: response.message,
attempt_status: None,
connector_transaction_id: None,
})
}
}
-impl ConnectorValidation for Ebanx {
- //TODO: implement functions when support enabled
-}
-
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Ebanx
-{
- //TODO: implement sessions flow
-}
-
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Ebanx
-{
-}
-
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Ebanx
-{
-}
+#[cfg(feature = "payouts")]
+impl ConnectorIntegration<api::PoCreate, types::PayoutsData, types::PayoutsResponseData> for Ebanx {
+ fn get_url(
+ &self,
+ _req: &types::PayoutsRouterData<api::PoCreate>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!("{}ws/payout/create", connectors.ebanx.base_url))
+ }
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Ebanx
-{
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
+ req: &types::PayoutsRouterData<api::PoCreate>,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
- fn get_content_type(&self) -> &'static str {
- self.common_get_content_type()
- }
-
- fn get_url(
- &self,
- _req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
- }
-
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
+ req: &types::PayoutsRouterData<api::PoCreate>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = ebanx::EbanxRouterData::try_from((
&self.get_currency_unit(),
- req.request.currency,
+ req.request.source_currency,
req.request.amount,
req,
))?;
- let connector_req = ebanx::EbanxPaymentsRequest::try_from(&connector_router_data)?;
+ let connector_req = ebanx::EbanxPayoutCreateRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
+ req: &types::PayoutsRouterData<api::PoCreate>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
- .attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
- self, req, connectors,
- )?)
- .build(),
- ))
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PayoutCreateType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PayoutCreateType::get_headers(self, req, connectors)?)
+ .set_body(types::PayoutCreateType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build();
+
+ Ok(Some(request))
}
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &types::PayoutsRouterData<api::PoCreate>,
event_builder: Option<&mut ConnectorEvent>,
- res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
- let response: ebanx::EbanxPaymentsResponse = res
+ res: types::Response,
+ ) -> CustomResult<types::PayoutsRouterData<api::PoCreate>, errors::ConnectorError> {
+ let response: ebanx::EbanxPayoutResponse = res
.response
- .parse_struct("Ebanx PaymentsAuthorizeResponse")
+ .parse_struct("EbanxPayoutResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -227,142 +189,83 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
- res: Response,
+ res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
+#[cfg(feature = "payouts")]
+impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResponseData>
for Ebanx
{
- fn get_headers(
- &self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- self.build_headers(req, connectors)
- }
-
- fn get_content_type(&self) -> &'static str {
- self.common_get_content_type()
- }
-
fn get_url(
&self,
- _req: &types::PaymentsSyncRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
- }
-
- fn build_request(
- &self,
- req: &types::PaymentsSyncRouterData,
+ _req: &types::PayoutsRouterData<api::PoFulfill>,
connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
- .attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
- .build(),
- ))
- }
-
- fn handle_response(
- &self,
- data: &types::PaymentsSyncRouterData,
- event_builder: Option<&mut ConnectorEvent>,
- res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
- let response: ebanx::EbanxPaymentsResponse = res
- .response
- .parse_struct("ebanx PaymentsSyncResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
-
- fn get_error_response(
- &self,
- res: Response,
- event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res, event_builder)
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!("{}ws/payout/commit", connectors.ebanx.base_url,))
}
-}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Ebanx
-{
fn get_headers(
&self,
- req: &types::PaymentsCaptureRouterData,
+ req: &types::PayoutsRouterData<api::PoFulfill>,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
- fn get_content_type(&self) -> &'static str {
- self.common_get_content_type()
- }
-
- fn get_url(
- &self,
- _req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
- }
-
fn get_request_body(
&self,
- _req: &types::PaymentsCaptureRouterData,
+ req: &types::PayoutsRouterData<api::PoFulfill>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ let connector_router_data = ebanx::EbanxRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.source_currency,
+ req.request.amount,
+ req,
+ ))?;
+ let connector_req = ebanx::EbanxPayoutFulfillRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
- req: &types::PaymentsCaptureRouterData,
+ req: &types::PayoutsRouterData<api::PoFulfill>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
- .attach_default_headers()
- .headers(types::PaymentsCaptureType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsCaptureType::get_request_body(
- self, req, connectors,
- )?)
- .build(),
- ))
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PayoutFulfillType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PayoutFulfillType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PayoutFulfillType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build();
+
+ Ok(Some(request))
}
+ #[instrument(skip_all)]
fn handle_response(
&self,
- data: &types::PaymentsCaptureRouterData,
+ data: &types::PayoutsRouterData<api::PoFulfill>,
event_builder: Option<&mut ConnectorEvent>,
- res: Response,
- ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
- let response: ebanx::EbanxPaymentsResponse = res
+ res: types::Response,
+ ) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> {
+ let response: ebanx::EbanxFulfillResponse = res
.response
- .parse_struct("Ebanx PaymentsCaptureResponse")
+ .parse_struct("EbanxFulfillResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -372,85 +275,73 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
- res: Response,
+ res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Ebanx
-{
-}
-
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Ebanx {
- fn get_headers(
+#[cfg(feature = "payouts")]
+impl ConnectorIntegration<api::PoCancel, types::PayoutsData, types::PayoutsResponseData> for Ebanx {
+ fn get_url(
&self,
- req: &types::RefundsRouterData<api::Execute>,
+ _req: &types::PayoutsRouterData<api::PoCancel>,
connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- self.build_headers(req, connectors)
- }
-
- fn get_content_type(&self) -> &'static str {
- self.common_get_content_type()
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!("{}ws/payout/cancel", connectors.ebanx.base_url,))
}
- fn get_url(
+ fn get_headers(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
+ req: &types::PayoutsRouterData<api::PoCancel>,
_connectors: &settings::Connectors,
- ) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, _connectors)
}
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
+ req: &types::PayoutsRouterData<api::PoCancel>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_router_data = ebanx::EbanxRouterData::try_from((
- &self.get_currency_unit(),
- req.request.currency,
- req.request.refund_amount,
- req,
- ))?;
- let connector_req = ebanx::EbanxRefundRequest::try_from(&connector_router_data)?;
+ let connector_req = ebanx::EbanxPayoutCancelRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
+ req: &types::PayoutsRouterData<api::PoCancel>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ .method(services::Method::Put)
+ .url(&types::PayoutCancelType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundExecuteType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::RefundExecuteType::get_request_body(
+ .headers(types::PayoutCancelType::get_headers(self, req, connectors)?)
+ .set_body(types::PayoutCancelType::get_request_body(
self, req, connectors,
)?)
.build();
+
Ok(Some(request))
}
+ #[instrument(skip_all)]
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &types::PayoutsRouterData<api::PoCancel>,
event_builder: Option<&mut ConnectorEvent>,
- res: Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
- let response: ebanx::RefundResponse = res
+ res: types::Response,
+ ) -> CustomResult<types::PayoutsRouterData<api::PoCancel>, errors::ConnectorError> {
+ let response: ebanx::EbanxCancelResponse = res
.response
- .parse_struct("ebanx RefundResponse")
+ .parse_struct("EbanxCancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -460,81 +351,86 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
- res: Response,
+ res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Ebanx {
- fn get_headers(
- &self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- self.build_headers(req, connectors)
- }
+#[cfg(feature = "payouts")]
+impl ConnectorIntegration<api::PoQuote, types::PayoutsData, types::PayoutsResponseData> for Ebanx {}
- fn get_content_type(&self) -> &'static str {
- self.common_get_content_type()
- }
+#[cfg(feature = "payouts")]
+impl ConnectorIntegration<api::PoRecipient, types::PayoutsData, types::PayoutsResponseData>
+ for Ebanx
+{
+}
- fn get_url(
- &self,
- _req: &types::RefundSyncRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
- }
+#[cfg(feature = "payouts")]
+impl ConnectorIntegration<api::PoEligibility, types::PayoutsData, types::PayoutsResponseData>
+ for Ebanx
+{
+}
- fn build_request(
- &self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::RefundSyncType::get_url(self, req, connectors)?)
- .attach_default_headers()
- .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
- .set_body(types::RefundSyncType::get_request_body(
- self, req, connectors,
- )?)
- .build(),
- ))
- }
+impl
+ ConnectorIntegration<
+ api::PaymentMethodToken,
+ types::PaymentMethodTokenizationData,
+ types::PaymentsResponseData,
+ > for Ebanx
+{
+ // Not Implemented (R)
+}
- fn handle_response(
- &self,
- data: &types::RefundSyncRouterData,
- event_builder: Option<&mut ConnectorEvent>,
- res: Response,
- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
- let response: ebanx::RefundResponse = res
- .response
- .parse_struct("ebanx RefundSyncResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
+impl ConnectorValidation for Ebanx {
+ //TODO: implement functions when support enabled
+}
- fn get_error_response(
- &self,
- res: Response,
- event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res, event_builder)
- }
+impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
+ for Ebanx
+{
+ //TODO: implement sessions flow
+}
+
+impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
+ for Ebanx
+{
}
-#[async_trait::async_trait]
+impl
+ ConnectorIntegration<
+ api::SetupMandate,
+ types::SetupMandateRequestData,
+ types::PaymentsResponseData,
+ > for Ebanx
+{
+}
+
+impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+ for Ebanx
+{
+}
+
+impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
+ for Ebanx
+{
+}
+
+impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
+ for Ebanx
+{
+}
+
+impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
+ for Ebanx
+{
+}
+
+impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Ebanx {}
+
+impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Ebanx {}
+
impl api::IncomingWebhook for Ebanx {
fn get_webhook_object_reference_id(
&self,
diff --git a/crates/router/src/connector/ebanx/transformers.rs b/crates/router/src/connector/ebanx/transformers.rs
index e27fba788dc..472e2da1b69 100644
--- a/crates/router/src/connector/ebanx/transformers.rs
+++ b/crates/router/src/connector/ebanx/transformers.rs
@@ -1,87 +1,158 @@
+#[cfg(feature = "payouts")]
+use api_models::payouts::{Bank, PayoutMethodData};
+use common_enums::Currency;
+#[cfg(feature = "payouts")]
+use common_utils::pii::Email;
+#[cfg(feature = "payouts")]
+use masking::ExposeInterface;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::PaymentsAuthorizeRequestData,
+ connector::utils,
core::errors,
- types::{self, api, domain, storage::enums},
+ types::{self, api::CurrencyUnit},
+};
+#[cfg(feature = "payouts")]
+use crate::{
+ connector::utils::{AddressDetailsData, RouterData},
+ connector::utils::{CustomerDetails, PayoutsData},
+ types::{api, storage::enums as storage_enums},
};
-//TODO: Fill the struct with respective fields
pub struct EbanxRouterData<T> {
- pub amount: i64, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
+ pub amount: f64, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for EbanxRouterData<T>
-{
+impl<T> TryFrom<(&CurrencyUnit, Currency, i64, T)> for EbanxRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (_currency_unit, _currency, amount, item): (
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- ),
+ (_currency_unit, currency, amount, item): (&CurrencyUnit, Currency, i64, T),
) -> Result<Self, Self::Error> {
- //Todo : use utils to convert the amount to the type of amount that a connector accepts
Ok(Self {
- amount,
+ amount: utils::to_currency_base_unit_asf64(amount, currency)?,
router_data: item,
})
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct EbanxPaymentsRequest {
- amount: i64,
- card: EbanxCard,
+#[cfg(feature = "payouts")]
+#[derive(Debug, Serialize, Clone)]
+pub struct EbanxPayoutCreateRequest {
+ integration_key: Secret<String>,
+ external_reference: String,
+ country: String,
+ amount: f64,
+ currency: Currency,
+ target: EbanxPayoutType,
+ target_account: Secret<String>,
+ payee: EbanxPayoutDetails,
+}
+
+#[cfg(feature = "payouts")]
+#[derive(Debug, Serialize, Clone)]
+pub enum EbanxPayoutType {
+ BankAccount,
+ Mercadopago,
+ EwalletNequi,
+ PixKey,
+}
+
+#[cfg(feature = "payouts")]
+#[derive(Debug, Serialize, Clone)]
+pub struct EbanxPayoutDetails {
+ name: Secret<String>,
+ email: Option<Email>,
+ document: Option<Secret<String>>,
+ document_type: Option<EbanxDocumentType>,
+ bank_info: EbanxBankDetails,
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct EbanxCard {
- number: cards::CardNumber,
- expiry_month: Secret<String>,
- expiry_year: Secret<String>,
- cvc: Secret<String>,
- complete: bool,
+#[cfg(feature = "payouts")]
+#[derive(Debug, Serialize, Clone)]
+pub enum EbanxDocumentType {
+ #[serde(rename = "CPF")]
+ NaturalPersonsRegister,
+ #[serde(rename = "CNPJ")]
+ NationalRegistryOfLegalEntities,
}
-impl TryFrom<&EbanxRouterData<&types::PaymentsAuthorizeRouterData>> for EbanxPaymentsRequest {
+#[cfg(feature = "payouts")]
+#[derive(Debug, Serialize, Clone)]
+pub struct EbanxBankDetails {
+ bank_name: Option<String>,
+ bank_branch: Option<String>,
+ bank_account: Option<Secret<String>>,
+ account_type: Option<EbanxBankAccountType>,
+}
+
+#[cfg(feature = "payouts")]
+#[derive(Debug, Serialize, Clone)]
+pub enum EbanxBankAccountType {
+ #[serde(rename = "C")]
+ CheckingAccount,
+}
+
+#[cfg(feature = "payouts")]
+impl TryFrom<&EbanxRouterData<&types::PayoutsRouterData<api::PoCreate>>>
+ for EbanxPayoutCreateRequest
+{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &EbanxRouterData<&types::PaymentsAuthorizeRouterData>,
+ item: &EbanxRouterData<&types::PayoutsRouterData<api::PoCreate>>,
) -> Result<Self, Self::Error> {
- match item.router_data.request.payment_method_data.clone() {
- domain::payments::PaymentMethodData::Card(req_card) => {
- let card = EbanxCard {
- number: req_card.card_number,
- expiry_month: req_card.card_exp_month,
- expiry_year: req_card.card_exp_year,
- cvc: req_card.card_cvc,
- complete: item.router_data.request.is_auto_capture()?,
+ let ebanx_auth_type = EbanxAuthType::try_from(&item.router_data.connector_auth_type)?;
+ match item.router_data.get_payout_method_data()? {
+ PayoutMethodData::Bank(Bank::Pix(pix_data)) => {
+ let bank_info = EbanxBankDetails {
+ bank_account: Some(pix_data.bank_account_number),
+ bank_branch: pix_data.bank_branch,
+ bank_name: pix_data.bank_name,
+ account_type: Some(EbanxBankAccountType::CheckingAccount),
+ };
+
+ let billing_address = item.router_data.get_billing_address()?;
+ let customer_details = item.router_data.request.get_customer_details()?;
+
+ let document_type = pix_data.tax_id.clone().map(|tax_id| {
+ if tax_id.clone().expose().len() == 11 {
+ EbanxDocumentType::NaturalPersonsRegister
+ } else {
+ EbanxDocumentType::NationalRegistryOfLegalEntities
+ }
+ });
+
+ let payee = EbanxPayoutDetails {
+ name: billing_address.get_full_name()?,
+ email: customer_details.email.clone(),
+ bank_info,
+ document_type,
+ document: pix_data.tax_id.to_owned(),
};
Ok(Self {
- amount: item.amount.to_owned(),
- card,
+ amount: item.amount,
+ integration_key: ebanx_auth_type.integration_key,
+ country: customer_details.get_customer_phone_country_code()?,
+ currency: item.router_data.request.source_currency,
+ external_reference: item.router_data.connector_request_reference_id.to_owned(),
+ target: EbanxPayoutType::PixKey,
+ target_account: pix_data.pix_key,
+ payee,
})
}
- _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ PayoutMethodData::Card(_) | PayoutMethodData::Bank(_) | PayoutMethodData::Wallet(_) => {
+ Err(errors::ConnectorError::NotSupported {
+ message: "Payment Method Not Supported".to_string(),
+ connector: "Ebanx",
+ })?
+ }
}
}
}
-//TODO: Fill the struct with respective fields
-// Auth Struct
pub struct EbanxAuthType {
- pub(super) api_key: Secret<String>,
+ pub integration_key: Secret<String>,
}
impl TryFrom<&types::ConnectorAuthType> for EbanxAuthType {
@@ -89,149 +160,247 @@ impl TryFrom<&types::ConnectorAuthType> for EbanxAuthType {
fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
- api_key: api_key.to_owned(),
+ integration_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
-// PaymentsResponse
-//TODO: Append the remaining status flags
-#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
-#[serde(rename_all = "lowercase")]
-pub enum EbanxPaymentStatus {
+
+#[cfg(feature = "payouts")]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub enum EbanxPayoutStatus {
+ #[serde(rename = "PA")]
Succeeded,
- Failed,
- #[default]
+ #[serde(rename = "CA")]
+ Cancelled,
+ #[serde(rename = "PE")]
Processing,
+ #[serde(rename = "OP")]
+ RequiresFulfillment,
}
-impl From<EbanxPaymentStatus> for enums::AttemptStatus {
- fn from(item: EbanxPaymentStatus) -> Self {
+#[cfg(feature = "payouts")]
+impl From<EbanxPayoutStatus> for storage_enums::PayoutStatus {
+ fn from(item: EbanxPayoutStatus) -> Self {
match item {
- EbanxPaymentStatus::Succeeded => Self::Charged,
- EbanxPaymentStatus::Failed => Self::Failure,
- EbanxPaymentStatus::Processing => Self::Authorizing,
+ EbanxPayoutStatus::Succeeded => Self::Success,
+ EbanxPayoutStatus::Cancelled => Self::Cancelled,
+ EbanxPayoutStatus::Processing => Self::Pending,
+ EbanxPayoutStatus::RequiresFulfillment => Self::RequiresFulfillment,
}
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
-pub struct EbanxPaymentsResponse {
- status: EbanxPaymentStatus,
- id: String,
+#[cfg(feature = "payouts")]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EbanxPayoutResponse {
+ payout: EbanxPayoutResponseDetails,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, EbanxPaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+#[cfg(feature = "payouts")]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EbanxPayoutResponseDetails {
+ uid: String,
+ status: EbanxPayoutStatus,
+}
+
+#[cfg(feature = "payouts")]
+impl<F> TryFrom<types::PayoutsResponseRouterData<F, EbanxPayoutResponse>>
+ for types::PayoutsRouterData<F>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, EbanxPaymentsResponse, T, types::PaymentsResponseData>,
+ item: types::PayoutsResponseRouterData<F, EbanxPayoutResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- status: enums::AttemptStatus::from(item.response.status),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
- redirection_data: None,
- mandate_reference: None,
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
+ response: Ok(types::PayoutsResponseData {
+ status: Some(storage_enums::PayoutStatus::from(
+ item.response.payout.status,
+ )),
+ connector_payout_id: item.response.payout.uid,
+ payout_eligible: None,
+ should_add_next_step_to_process_tracker: false,
}),
..item.data
})
}
}
-//TODO: Fill the struct with respective fields
-// REFUND :
-// Type definition for RefundRequest
-#[derive(Default, Debug, Serialize)]
-pub struct EbanxRefundRequest {
- pub amount: i64,
+#[cfg(feature = "payouts")]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EbanxPayoutFulfillRequest {
+ integration_key: Secret<String>,
+ uid: String,
}
-impl<F> TryFrom<&EbanxRouterData<&types::RefundsRouterData<F>>> for EbanxRefundRequest {
+#[cfg(feature = "payouts")]
+impl<F> TryFrom<&EbanxRouterData<&types::PayoutsRouterData<F>>> for EbanxPayoutFulfillRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &EbanxRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> {
- Ok(Self {
- amount: item.amount.to_owned(),
- })
+ fn try_from(item: &EbanxRouterData<&types::PayoutsRouterData<F>>) -> Result<Self, Self::Error> {
+ let request = item.router_data.request.to_owned();
+ let ebanx_auth_type = EbanxAuthType::try_from(&item.router_data.connector_auth_type)?;
+ match request.payout_type.to_owned() {
+ storage_enums::PayoutType::Bank => Ok(Self {
+ integration_key: ebanx_auth_type.integration_key,
+ uid: request
+ .connector_payout_id
+ .to_owned()
+ .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "uid" })?,
+ }),
+ storage_enums::PayoutType::Card | storage_enums::PayoutType::Wallet => {
+ Err(errors::ConnectorError::NotSupported {
+ message: "Payout Method Not Supported".to_string(),
+ connector: "Ebanx",
+ })?
+ }
+ }
}
}
-// Type definition for Refund Response
+#[cfg(feature = "payouts")]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EbanxFulfillResponse {
+ #[serde(rename = "type")]
+ status: EbanxFulfillStatus,
+ message: String,
+}
-#[allow(dead_code)]
-#[derive(Debug, Serialize, Default, Deserialize, Clone)]
-pub enum RefundStatus {
- Succeeded,
- Failed,
- #[default]
- Processing,
+#[cfg(feature = "payouts")]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum EbanxFulfillStatus {
+ Success,
+ ApiError,
+ AuthenticationError,
+ InvalidRequestError,
+ RequestError,
}
-impl From<RefundStatus> for enums::RefundStatus {
- fn from(item: RefundStatus) -> Self {
+#[cfg(feature = "payouts")]
+impl From<EbanxFulfillStatus> for storage_enums::PayoutStatus {
+ fn from(item: EbanxFulfillStatus) -> Self {
match item {
- RefundStatus::Succeeded => Self::Success,
- RefundStatus::Failed => Self::Failure,
- RefundStatus::Processing => Self::Pending,
- //TODO: Review mapping
+ EbanxFulfillStatus::Success => Self::Success,
+ EbanxFulfillStatus::ApiError
+ | EbanxFulfillStatus::AuthenticationError
+ | EbanxFulfillStatus::InvalidRequestError
+ | EbanxFulfillStatus::RequestError => Self::Failed,
}
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Clone, Serialize, Deserialize)]
-pub struct RefundResponse {
- id: String,
- status: RefundStatus,
-}
-
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
+#[cfg(feature = "payouts")]
+impl<F> TryFrom<types::PayoutsResponseRouterData<F, EbanxFulfillResponse>>
+ for types::PayoutsRouterData<F>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: types::PayoutsResponseRouterData<F, EbanxFulfillResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::RefundsResponseData {
- connector_refund_id: item.response.id.to_string(),
- refund_status: enums::RefundStatus::from(item.response.status),
+ response: Ok(types::PayoutsResponseData {
+ status: Some(storage_enums::PayoutStatus::from(item.response.status)),
+ connector_payout_id: item.data.request.get_transfer_id()?,
+ payout_eligible: None,
+ should_add_next_step_to_process_tracker: false,
}),
..item.data
})
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
- for types::RefundsRouterData<api::RSync>
+#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+pub struct EbanxErrorResponse {
+ pub code: String,
+ pub status_code: String,
+ pub message: Option<String>,
+}
+
+#[cfg(feature = "payouts")]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EbanxPayoutCancelRequest {
+ integration_key: Secret<String>,
+ uid: String,
+}
+
+#[cfg(feature = "payouts")]
+impl<F> TryFrom<&types::PayoutsRouterData<F>> for EbanxPayoutCancelRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> {
+ let request = item.request.to_owned();
+ let ebanx_auth_type = EbanxAuthType::try_from(&item.connector_auth_type)?;
+ match request.payout_type.to_owned() {
+ storage_enums::PayoutType::Bank => Ok(Self {
+ integration_key: ebanx_auth_type.integration_key,
+ uid: request
+ .connector_payout_id
+ .to_owned()
+ .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "uid" })?,
+ }),
+ storage_enums::PayoutType::Card | storage_enums::PayoutType::Wallet => {
+ Err(errors::ConnectorError::NotSupported {
+ message: "Payout Method Not Supported".to_string(),
+ connector: "Ebanx",
+ })?
+ }
+ }
+ }
+}
+
+#[cfg(feature = "payouts")]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EbanxCancelResponse {
+ #[serde(rename = "type")]
+ status: EbanxCancelStatus,
+ message: String,
+}
+
+#[cfg(feature = "payouts")]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum EbanxCancelStatus {
+ Success,
+ ApiError,
+ AuthenticationError,
+ InvalidRequestError,
+ RequestError,
+}
+
+#[cfg(feature = "payouts")]
+impl From<EbanxCancelStatus> for storage_enums::PayoutStatus {
+ fn from(item: EbanxCancelStatus) -> Self {
+ match item {
+ EbanxCancelStatus::Success => Self::Cancelled,
+ EbanxCancelStatus::ApiError
+ | EbanxCancelStatus::AuthenticationError
+ | EbanxCancelStatus::InvalidRequestError
+ | EbanxCancelStatus::RequestError => Self::Failed,
+ }
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl<F> TryFrom<types::PayoutsResponseRouterData<F, EbanxCancelResponse>>
+ for types::PayoutsRouterData<F>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ item: types::PayoutsResponseRouterData<F, EbanxCancelResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::RefundsResponseData {
- connector_refund_id: item.response.id.to_string(),
- refund_status: enums::RefundStatus::from(item.response.status),
+ response: Ok(types::PayoutsResponseData {
+ status: Some(storage_enums::PayoutStatus::from(item.response.status)),
+ connector_payout_id: item
+ .data
+ .request
+ .connector_payout_id
+ .clone()
+ .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?,
+ payout_eligible: None,
+ should_add_next_step_to_process_tracker: false,
}),
..item.data
})
}
}
-
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
-pub struct EbanxErrorResponse {
- pub status_code: u16,
- pub code: String,
- pub message: String,
- pub reason: Option<String>,
-}
diff --git a/crates/router/src/connector/stripe/transformers/connect.rs b/crates/router/src/connector/stripe/transformers/connect.rs
index df4376b7174..43bc0f2f510 100644
--- a/crates/router/src/connector/stripe/transformers/connect.rs
+++ b/crates/router/src/connector/stripe/transformers/connect.rs
@@ -427,6 +427,11 @@ impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectRecipientAccountC
connector: "stripe",
}
.into()),
+ api_models::payouts::Bank::Pix(_) => Err(errors::ConnectorError::NotSupported {
+ message: "PIX payouts are not supported".to_string(),
+ connector: "stripe",
+ }
+ .into()),
},
api_models::payouts::PayoutMethodData::Wallet(_) => {
Err(errors::ConnectorError::NotSupported {
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 36c8e24aef4..efcaa5bfce7 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -20,8 +20,6 @@ use once_cell::sync::Lazy;
use regex::Regex;
use serde::Serializer;
use time::PrimitiveDateTime;
-#[cfg(feature = "payouts")]
-use types::CustomerDetails;
#[cfg(feature = "frm")]
use crate::types::{fraud_check, storage::enums as storage_enums};
@@ -850,6 +848,66 @@ impl PaymentsSyncRequestData for types::PaymentsSyncData {
}
}
+#[cfg(feature = "payouts")]
+pub trait CustomerDetails {
+ fn get_customer_id(&self) -> Result<String, errors::ConnectorError>;
+ fn get_customer_name(
+ &self,
+ ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError>;
+ fn get_customer_email(&self) -> Result<Email, errors::ConnectorError>;
+ fn get_customer_phone(
+ &self,
+ ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError>;
+ fn get_customer_phone_country_code(&self) -> Result<String, errors::ConnectorError>;
+}
+
+#[cfg(feature = "payouts")]
+impl CustomerDetails for types::CustomerDetails {
+ fn get_customer_id(&self) -> Result<String, errors::ConnectorError> {
+ self.customer_id
+ .clone()
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "customer_id",
+ })
+ }
+
+ fn get_customer_name(
+ &self,
+ ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError> {
+ self.name
+ .clone()
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "customer_name",
+ })
+ }
+
+ fn get_customer_email(&self) -> Result<Email, errors::ConnectorError> {
+ self.email
+ .clone()
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "customer_email",
+ })
+ }
+
+ fn get_customer_phone(
+ &self,
+ ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError> {
+ self.phone
+ .clone()
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "customer_phone",
+ })
+ }
+
+ fn get_customer_phone_country_code(&self) -> Result<String, errors::ConnectorError> {
+ self.phone_country_code
+ .clone()
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "customer_phone_country_code",
+ })
+ }
+}
+
pub trait PaymentsCancelRequestData {
fn get_amount(&self) -> Result<i64, Error>;
fn get_currency(&self) -> Result<diesel_models::enums::Currency, Error>;
@@ -905,7 +963,7 @@ impl RefundsRequestData for types::RefundsData {
#[cfg(feature = "payouts")]
pub trait PayoutsData {
fn get_transfer_id(&self) -> Result<String, Error>;
- fn get_customer_details(&self) -> Result<CustomerDetails, Error>;
+ fn get_customer_details(&self) -> Result<types::CustomerDetails, Error>;
fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error>;
}
@@ -916,7 +974,7 @@ impl PayoutsData for types::PayoutsData {
.clone()
.ok_or_else(missing_field_err("transfer_id"))
}
- fn get_customer_details(&self) -> Result<CustomerDetails, Error> {
+ fn get_customer_details(&self) -> Result<types::CustomerDetails, Error> {
self.customer_details
.clone()
.ok_or_else(missing_field_err("customer_details"))
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index eab7ea6a7ed..7d2fabc3f37 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1831,6 +1831,10 @@ pub(crate) fn validate_auth_and_metadata_type(
dlocal::transformers::DlocalAuthType::try_from(val)?;
Ok(())
}
+ api_enums::Connector::Ebanx => {
+ ebanx::transformers::EbanxAuthType::try_from(val)?;
+ Ok(())
+ }
api_enums::Connector::Fiserv => {
fiserv::transformers::FiservAuthType::try_from(val)?;
fiserv::transformers::FiservSessionObject::try_from(connector_meta_data)?;
diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs
index 1bfa4830291..fafff7253a2 100644
--- a/crates/router/src/core/payment_methods/vault.rs
+++ b/crates/router/src/core/payment_methods/vault.rs
@@ -483,6 +483,8 @@ pub struct TokenizedBankSensitiveValues {
pub bic: Option<masking::Secret<String>>,
pub bank_sort_code: Option<masking::Secret<String>>,
pub iban: Option<masking::Secret<String>>,
+ pub pix_key: Option<masking::Secret<String>>,
+ pub tax_id: Option<masking::Secret<String>>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
@@ -491,6 +493,7 @@ pub struct TokenizedBankInsensitiveValues {
pub bank_name: Option<String>,
pub bank_country_code: Option<api::enums::CountryAlpha2>,
pub bank_city: Option<String>,
+ pub bank_branch: Option<String>,
}
#[cfg(feature = "payouts")]
@@ -503,6 +506,8 @@ impl Vaultable for api::BankPayout {
bic: None,
bank_sort_code: None,
iban: None,
+ pix_key: None,
+ tax_id: None,
},
Self::Bacs(b) => TokenizedBankSensitiveValues {
bank_account_number: Some(b.bank_account_number.to_owned()),
@@ -510,6 +515,8 @@ impl Vaultable for api::BankPayout {
bic: None,
bank_sort_code: Some(b.bank_sort_code.to_owned()),
iban: None,
+ pix_key: None,
+ tax_id: None,
},
Self::Sepa(b) => TokenizedBankSensitiveValues {
bank_account_number: None,
@@ -517,13 +524,24 @@ impl Vaultable for api::BankPayout {
bic: b.bic.to_owned(),
bank_sort_code: None,
iban: Some(b.iban.to_owned()),
+ pix_key: None,
+ tax_id: None,
+ },
+ Self::Pix(bank_details) => TokenizedBankSensitiveValues {
+ bank_account_number: Some(bank_details.bank_account_number.to_owned()),
+ bank_routing_number: None,
+ bic: None,
+ bank_sort_code: None,
+ iban: None,
+ pix_key: Some(bank_details.pix_key.to_owned()),
+ tax_id: bank_details.tax_id.to_owned(),
},
};
bank_sensitive_data
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
- .attach_printable("Failed to encode wallet data bank_sensitive_data")
+ .attach_printable("Failed to encode data - bank_sensitive_data")
}
fn get_value2(&self, customer_id: Option<String>) -> CustomResult<String, errors::VaultError> {
@@ -533,18 +551,28 @@ impl Vaultable for api::BankPayout {
bank_name: b.bank_name.to_owned(),
bank_country_code: b.bank_country_code.to_owned(),
bank_city: b.bank_city.to_owned(),
+ bank_branch: None,
},
Self::Bacs(b) => TokenizedBankInsensitiveValues {
customer_id,
bank_name: b.bank_name.to_owned(),
bank_country_code: b.bank_country_code.to_owned(),
bank_city: b.bank_city.to_owned(),
+ bank_branch: None,
},
- Self::Sepa(b) => TokenizedBankInsensitiveValues {
+ Self::Sepa(bank_details) => TokenizedBankInsensitiveValues {
customer_id,
- bank_name: b.bank_name.to_owned(),
- bank_country_code: b.bank_country_code.to_owned(),
- bank_city: b.bank_city.to_owned(),
+ bank_name: bank_details.bank_name.to_owned(),
+ bank_country_code: bank_details.bank_country_code.to_owned(),
+ bank_city: bank_details.bank_city.to_owned(),
+ bank_branch: None,
+ },
+ Self::Pix(bank_details) => TokenizedBankInsensitiveValues {
+ customer_id,
+ bank_name: bank_details.bank_name.to_owned(),
+ bank_country_code: None,
+ bank_city: None,
+ bank_branch: bank_details.bank_branch.to_owned(),
},
};
@@ -569,35 +597,53 @@ impl Vaultable for api::BankPayout {
.attach_printable("Could not deserialize into wallet data bank_insensitive_data")?;
let bank = match (
- // ACH + BACS
+ // ACH + BACS + PIX
bank_sensitive_data.bank_account_number.to_owned(),
bank_sensitive_data.bank_routing_number.to_owned(), // ACH
bank_sensitive_data.bank_sort_code.to_owned(), // BACS
// SEPA
bank_sensitive_data.iban.to_owned(),
bank_sensitive_data.bic,
+ // PIX
+ bank_sensitive_data.pix_key,
+ bank_sensitive_data.tax_id,
) {
- (Some(ban), Some(brn), None, None, None) => Self::Ach(payouts::AchBankTransfer {
- bank_account_number: ban,
- bank_routing_number: brn,
- bank_name: bank_insensitive_data.bank_name,
- bank_country_code: bank_insensitive_data.bank_country_code,
- bank_city: bank_insensitive_data.bank_city,
- }),
- (Some(ban), None, Some(bsc), None, None) => Self::Bacs(payouts::BacsBankTransfer {
- bank_account_number: ban,
- bank_sort_code: bsc,
- bank_name: bank_insensitive_data.bank_name,
- bank_country_code: bank_insensitive_data.bank_country_code,
- bank_city: bank_insensitive_data.bank_city,
- }),
- (None, None, None, Some(iban), bic) => Self::Sepa(payouts::SepaBankTransfer {
- iban,
- bic,
- bank_name: bank_insensitive_data.bank_name,
- bank_country_code: bank_insensitive_data.bank_country_code,
- bank_city: bank_insensitive_data.bank_city,
- }),
+ (Some(ban), Some(brn), None, None, None, None, None) => {
+ Self::Ach(payouts::AchBankTransfer {
+ bank_account_number: ban,
+ bank_routing_number: brn,
+ bank_name: bank_insensitive_data.bank_name,
+ bank_country_code: bank_insensitive_data.bank_country_code,
+ bank_city: bank_insensitive_data.bank_city,
+ })
+ }
+ (Some(ban), None, Some(bsc), None, None, None, None) => {
+ Self::Bacs(payouts::BacsBankTransfer {
+ bank_account_number: ban,
+ bank_sort_code: bsc,
+ bank_name: bank_insensitive_data.bank_name,
+ bank_country_code: bank_insensitive_data.bank_country_code,
+ bank_city: bank_insensitive_data.bank_city,
+ })
+ }
+ (None, None, None, Some(iban), bic, None, None) => {
+ Self::Sepa(payouts::SepaBankTransfer {
+ iban,
+ bic,
+ bank_name: bank_insensitive_data.bank_name,
+ bank_country_code: bank_insensitive_data.bank_country_code,
+ bank_city: bank_insensitive_data.bank_city,
+ })
+ }
+ (Some(ban), None, None, None, None, Some(pix_key), tax_id) => {
+ Self::Pix(payouts::PixBankTransfer {
+ bank_account_number: ban,
+ bank_branch: bank_insensitive_data.bank_branch,
+ bank_name: bank_insensitive_data.bank_name,
+ pix_key,
+ tax_id,
+ })
+ }
_ => Err(errors::VaultError::ResponseDeserializationFailed)?,
};
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index e2c17a37d92..c96f6f2c144 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -978,7 +978,6 @@ default_imp_for_payouts!(
connector::Cybersource,
connector::Coinbase,
connector::Dlocal,
- connector::Ebanx,
connector::Fiserv,
connector::Forte,
connector::Globalpay,
@@ -1064,7 +1063,6 @@ default_imp_for_payouts_create!(
connector::Cybersource,
connector::Coinbase,
connector::Dlocal,
- connector::Ebanx,
connector::Fiserv,
connector::Forte,
connector::Globalpay,
@@ -1153,7 +1151,6 @@ default_imp_for_payouts_eligibility!(
connector::Cybersource,
connector::Coinbase,
connector::Dlocal,
- connector::Ebanx,
connector::Fiserv,
connector::Forte,
connector::Globalpay,
@@ -1240,7 +1237,6 @@ default_imp_for_payouts_fulfill!(
connector::Cybersource,
connector::Coinbase,
connector::Dlocal,
- connector::Ebanx,
connector::Fiserv,
connector::Forte,
connector::Globalpay,
@@ -1326,7 +1322,6 @@ default_imp_for_payouts_cancel!(
connector::Cybersource,
connector::Coinbase,
connector::Dlocal,
- connector::Ebanx,
connector::Fiserv,
connector::Forte,
connector::Globalpay,
@@ -1413,7 +1408,6 @@ default_imp_for_payouts_quote!(
connector::Cybersource,
connector::Coinbase,
connector::Dlocal,
- connector::Ebanx,
connector::Fiserv,
connector::Forte,
connector::Globalpay,
@@ -1501,7 +1495,6 @@ default_imp_for_payouts_recipient!(
connector::Cybersource,
connector::Coinbase,
connector::Dlocal,
- connector::Ebanx,
connector::Fiserv,
connector::Forte,
connector::Globalpay,
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 648c7a224eb..38fd773b9b3 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -352,6 +352,7 @@ impl ConnectorData {
enums::Connector::DummyConnector6 => Ok(Box::new(&connector::DummyConnector::<6>)),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector7 => Ok(Box::new(&connector::DummyConnector::<7>)),
+ enums::Connector::Ebanx => Ok(Box::new(&connector::Ebanx)),
enums::Connector::Fiserv => Ok(Box::new(&connector::Fiserv)),
enums::Connector::Forte => Ok(Box::new(&connector::Forte)),
enums::Connector::Globalpay => Ok(Box::new(&connector::Globalpay)),
diff --git a/crates/router/src/types/api/payouts.rs b/crates/router/src/types/api/payouts.rs
index a04c2fd095b..53f015290df 100644
--- a/crates/router/src/types/api/payouts.rs
+++ b/crates/router/src/types/api/payouts.rs
@@ -2,7 +2,7 @@ pub use api_models::payouts::{
AchBankTransfer, BacsBankTransfer, Bank as BankPayout, Card as CardPayout, PayoutActionRequest,
PayoutCreateRequest, PayoutCreateResponse, PayoutListConstraints, PayoutListFilterConstraints,
PayoutListFilters, PayoutListResponse, PayoutMethodData, PayoutRequest, PayoutRetrieveBody,
- PayoutRetrieveRequest, SepaBankTransfer, Wallet as WalletPayout,
+ PayoutRetrieveRequest, PixBankTransfer, SepaBankTransfer, Wallet as WalletPayout,
};
use crate::{services::api, types};
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 6ecd53afaed..b1b185eb92a 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -224,6 +224,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
api_enums::Connector::Cryptopay => Self::Cryptopay,
api_enums::Connector::Cybersource => Self::Cybersource,
api_enums::Connector::Dlocal => Self::Dlocal,
+ api_enums::Connector::Ebanx => Self::Ebanx,
api_enums::Connector::Fiserv => Self::Fiserv,
api_enums::Connector::Forte => Self::Forte,
api_enums::Connector::Globalpay => Self::Globalpay,
@@ -960,6 +961,7 @@ impl ForeignFrom<api_models::payouts::Bank> for api_enums::PaymentMethodType {
api_models::payouts::Bank::Ach(_) => Self::Ach,
api_models::payouts::Bank::Bacs(_) => Self::Bacs,
api_models::payouts::Bank::Sepa(_) => Self::Sepa,
+ api_models::payouts::Bank::Pix(_) => Self::Pix,
}
}
}
diff --git a/crates/router/tests/connectors/ebanx.rs b/crates/router/tests/connectors/ebanx.rs
index 0c675be2242..8571ed1e3f8 100644
--- a/crates/router/tests/connectors/ebanx.rs
+++ b/crates/router/tests/connectors/ebanx.rs
@@ -12,23 +12,12 @@ impl utils::Connector for EbanxTest {
use router::connector::Ebanx;
types::api::ConnectorData {
connector: Box::new(&Ebanx),
- connector_name: types::Connector::Adyen,
+ connector_name: types::Connector::Ebanx,
get_token: types::api::GetToken::Connector,
merchant_connector_id: None,
}
}
- #[cfg(feature = "payouts")]
- fn get_payout_data(&self) -> Option<types::api::ConnectorData> {
- use router::connector::Ebanx;
- Some(types::api::ConnectorData {
- connector: Box::new(&Ebanx),
- connector_name: types::Connector::Adyen,
- get_token: types::api::GetToken::Connector,
- merchant_connector_id: None,
- })
- }
-
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
@@ -313,12 +302,10 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::payments::PaymentMethodData::Card(
- types::domain::Card {
- card_cvc: Secret::new("12345".to_string()),
- ..utils::CCardType::default().0
- },
- ),
+ payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
+ card_cvc: Secret::new("12345".to_string()),
+ ..utils::CCardType::default().0
+ }),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
@@ -337,12 +324,10 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::payments::PaymentMethodData::Card(
- types::domain::Card {
- card_exp_month: Secret::new("20".to_string()),
- ..utils::CCardType::default().0
- },
- ),
+ payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
+ card_exp_month: Secret::new("20".to_string()),
+ ..utils::CCardType::default().0
+ }),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
@@ -361,12 +346,10 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::payments::PaymentMethodData::Card(
- types::domain::Card {
- card_exp_year: Secret::new("2000".to_string()),
- ..utils::CCardType::default().0
- },
- ),
+ payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
+ card_exp_year: Secret::new("2000".to_string()),
+ ..utils::CCardType::default().0
+ }),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml
index a72326b903d..a1f7919cd78 100644
--- a/crates/router/tests/connectors/sample_auth.toml
+++ b/crates/router/tests/connectors/sample_auth.toml
@@ -199,6 +199,9 @@ key1= "Trankey"
api_key="API Key"
+[ebanx]
+api_key="API Key"
+
[billwerk]
api_key="API Key"
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 9d9d96ccac1..42ea3e54559 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -5264,6 +5264,9 @@
},
{
"$ref": "#/components/schemas/SepaBankTransfer"
+ },
+ {
+ "$ref": "#/components/schemas/PixBankTransfer"
}
]
},
@@ -7218,6 +7221,7 @@
"cryptopay",
"cybersource",
"dlocal",
+ "ebanx",
"fiserv",
"forte",
"globalpay",
@@ -15620,7 +15624,8 @@
"adyen",
"stripe",
"wise",
- "paypal"
+ "paypal",
+ "ebanx"
]
},
"PayoutCreateRequest": {
@@ -16333,6 +16338,43 @@
}
}
},
+ "PixBankTransfer": {
+ "type": "object",
+ "required": [
+ "bank_account_number",
+ "pix_key"
+ ],
+ "properties": {
+ "bank_name": {
+ "type": "string",
+ "description": "Bank name",
+ "example": "Deutsche Bank",
+ "nullable": true
+ },
+ "bank_branch": {
+ "type": "string",
+ "description": "Bank branch",
+ "example": "3707",
+ "nullable": true
+ },
+ "bank_account_number": {
+ "type": "string",
+ "description": "Bank account number is an unique identifier assigned by a bank to a customer.",
+ "example": "000123456"
+ },
+ "pix_key": {
+ "type": "string",
+ "description": "Unique key for pix customer",
+ "example": "000123456"
+ },
+ "tax_id": {
+ "type": "string",
+ "description": "Individual taxpayer identification number",
+ "example": "000123456",
+ "nullable": true
+ }
+ }
+ },
"PollConfigResponse": {
"type": "object",
"required": [
@@ -17140,6 +17182,7 @@
"cryptopay",
"cybersource",
"dlocal",
+ "ebanx",
"fiserv",
"forte",
"globalpay",
|
feat
|
[Ebanx] Add payout flows (#4146)
|
cf88718e69518a1cf7566840b7cffe07149d15ca
|
2023-01-20 12:57:50
|
Sangamesh Kulkarni
|
docs: request and response in refund routes (#423)
| false
|
diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs
index f419dcfd0de..b78d1521f8b 100644
--- a/crates/api_models/src/refunds.rs
+++ b/crates/api_models/src/refunds.rs
@@ -82,22 +82,29 @@ pub struct RefundResponse {
pub updated_at: Option<PrimitiveDateTime>,
}
-#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
+#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
pub struct RefundListRequest {
+ /// The identifier for the payment
pub payment_id: Option<String>,
+ /// Limit on the number of objects to return
pub limit: Option<i64>,
+ /// The time at which refund is created
#[serde(default, with = "custom_serde::iso8601::option")]
pub created: Option<PrimitiveDateTime>,
+ /// Time less than the refund created time
#[serde(default, rename = "created.lt", with = "custom_serde::iso8601::option")]
pub created_lt: Option<PrimitiveDateTime>,
+ /// Time greater than the refund created time
#[serde(default, rename = "created.gt", with = "custom_serde::iso8601::option")]
pub created_gt: Option<PrimitiveDateTime>,
+ /// Time less than or equals to the refund created time
#[serde(
default,
rename = "created.lte",
with = "custom_serde::iso8601::option"
)]
pub created_lte: Option<PrimitiveDateTime>,
+ /// Time greater than or equals to the refund created time
#[serde(
default,
rename = "created.gte",
diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs
index ae6543fec67..94b8d3797b4 100644
--- a/crates/router/src/openapi.rs
+++ b/crates/router/src/openapi.rs
@@ -52,6 +52,7 @@ Never share your secret api keys. Keep them guarded and secure.
crate::types::api::refunds::RefundType,
crate::types::api::refunds::RefundResponse,
crate::types::api::refunds::RefundStatus,
+ crate::types::api::refunds::RefundUpdateRequest,
crate::types::api::admin::CreateMerchantAccount,
crate::types::api::admin::DeleteResponse,
crate::types::api::admin::DeleteMcaResponse,
@@ -112,6 +113,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::PaymentsCancelRequest,
api_models::payments::PaymentListConstraints,
api_models::payments::PaymentListResponse,
+ api_models::refunds::RefundListRequest,
crate::types::api::admin::MerchantAccountResponse,
crate::types::api::admin::MerchantConnectorId,
crate::types::api::admin::MerchantDetails,
diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs
index f627c2baddb..0d9a5fed542 100644
--- a/crates/router/src/routes/refunds.rs
+++ b/crates/router/src/routes/refunds.rs
@@ -37,6 +37,20 @@ pub async fn refunds_create(
.await
}
+/// Refunds - Retrieve
+///
+/// To retrieve a refund against an already processed payment
+#[utoipa::path(
+ get,
+ path = "/refunds/{refund_id}",
+ params(
+ ("refund_id" = String, Path, description = "The identifier for refund")
+ ),
+ responses(
+ (status = 200, description = "Refund retrieved", body = RefundResponse),
+ (status = 404, description = "Refund does not exist in our records")
+ )
+)]
#[instrument(skip_all, fields(flow = ?Flow::RefundsRetrieve))]
// #[get("/{id}")]
pub async fn refunds_retrieve(
@@ -58,6 +72,21 @@ pub async fn refunds_retrieve(
.await
}
+/// Refunds - Update
+///
+/// To update a refund against an already processed payment
+#[utoipa::path(
+ post,
+ path = "/refunds/{refund_id}",
+ params(
+ ("refund_id" = String, Path, description = "The identifier for refund")
+ ),
+ request_body=RefundUpdateRequest,
+ responses(
+ (status = 200, description = "Refund updated", body = RefundResponse),
+ (status = 400, description = "Missing Mandatory fields")
+ )
+)]
#[instrument(skip_all, fields(flow = ?Flow::RefundsUpdate))]
// #[post("/{id}")]
pub async fn refunds_update(
@@ -79,6 +108,26 @@ pub async fn refunds_update(
.await
}
+/// Refunds - List
+///
+/// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided
+#[utoipa::path(
+ get,
+ path = "/refunds/list",
+ params(
+ ("payment_id" = String, Query, description = "The identifier for the payment"),
+ ("limit" = i64, Query, description = "Limit on the number of objects to return"),
+ ("created" = PrimitiveDateTime, Query, description = "The time at which refund is created"),
+ ("created_lt" = PrimitiveDateTime, Query, description = "Time less than the refund created time"),
+ ("created_gt" = PrimitiveDateTime, Query, description = "Time greater than the refund created time"),
+ ("created_lte" = PrimitiveDateTime, Query, description = "Time less than or equals to the refund created time"),
+ ("created_gte" = PrimitiveDateTime, Query, description = "Time greater than or equals to the refund created time")
+ ),
+ responses(
+ (status = 200, description = "List of refunds", body = RefundListResponse),
+ (status = 404, description = "Refund does not exist in our records")
+ )
+)]
#[instrument(skip_all, fields(flow = ?Flow::RefundsList))]
#[cfg(feature = "olap")]
// #[get("/list")]
diff --git a/openapi/generated.json b/openapi/generated.json
index a96a2dc9e8b..9bb1f01f601 100644
--- a/openapi/generated.json
+++ b/openapi/generated.json
@@ -2086,6 +2086,45 @@
}
}
},
+ "RefundListRequest": {
+ "type": "object",
+ "properties": {
+ "payment_id": {
+ "type": "string",
+ "description": "The identifier for the payment"
+ },
+ "limit": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Limit on the number of objects to return"
+ },
+ "created": {
+ "type": "string",
+ "format": "date-time",
+ "description": "The time at which refund is created"
+ },
+ "created.lt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Time less than the refund created time"
+ },
+ "created.gt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Time greater than the refund created time"
+ },
+ "created.lte": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Time less than or equals to the refund created time"
+ },
+ "created.gte": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Time greater than or equals to the refund created time"
+ }
+ }
+ },
"RefundRequest": {
"type": "object",
"required": [
@@ -2194,6 +2233,20 @@
"instant"
]
},
+ "RefundUpdateRequest": {
+ "type": "object",
+ "properties": {
+ "reason": {
+ "type": "string",
+ "description": "An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive",
+ "example": "Customer returned the product",
+ "maxLength": 255
+ },
+ "metadata": {
+ "type": "object"
+ }
+ }
+ },
"RoutingAlgorithm": {
"type": "string",
"description": "The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom'",
|
docs
|
request and response in refund routes (#423)
|
cff1ce61f0347665d18040486cfbbcd93139950b
|
2023-06-16 18:55:01
|
Narayan Bhat
|
refactor(core): accept customer data in customer object (#1447)
| false
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 173b795efa3..53ce196737a 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -45,6 +45,28 @@ pub struct BankCodeResponse {
pub eligible_connectors: Vec<String>,
}
+#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+pub struct CustomerDetails {
+ /// The identifier for the customer.
+ pub id: String,
+
+ /// The customer's name
+ #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")]
+ pub name: Option<Secret<String>>,
+
+ /// The customer's email address
+ #[schema(max_length = 255, value_type = Option<String>, example = "[email protected]")]
+ pub email: Option<Email>,
+
+ /// The customer's phone number
+ #[schema(value_type = Option<String>, max_length = 10, example = "3141592653")]
+ pub phone: Option<Secret<String>>,
+
+ /// The country code for the customer's phone number
+ #[schema(max_length = 2, example = "+1")]
+ pub phone_country_code: Option<String>,
+}
+
#[derive(
Default,
Debug,
@@ -114,23 +136,33 @@ pub struct PaymentsRequest {
#[schema(default = false, example = true)]
pub confirm: Option<bool>,
- /// The identifier for the customer object. If not provided the customer ID will be autogenerated.
+ /// The details of a customer for this payment
+ /// This will create the customer if `customer.id` does not exist
+ /// If customer id already exists, it will update the details of the customer
+ pub customer: Option<CustomerDetails>,
+
+ /// The identifier for the customer object.
+ /// This field will be deprecated soon, use the customer object instead
#[schema(max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
pub customer_id: Option<String>,
- /// description: The customer's email address
+ /// The customer's email address
+ /// This field will be deprecated soon, use the customer object instead
#[schema(max_length = 255, value_type = Option<String>, example = "[email protected]")]
pub email: Option<Email>,
/// description: The customer's name
+ /// This field will be deprecated soon, use the customer object instead
#[schema(value_type = Option<String>, max_length = 255, example = "John Test")]
pub name: Option<Secret<String>>,
/// The customer's phone number
+ /// This field will be deprecated soon, use the customer object instead
#[schema(value_type = Option<String>, max_length = 255, example = "3141592653")]
pub phone: Option<Secret<String>>,
/// The country code for the customer phone number
+ /// This field will be deprecated soon, use the customer object instead
#[schema(max_length = 255, example = "+1")]
pub phone_country_code: Option<String>,
@@ -303,27 +335,6 @@ pub struct VerifyRequest {
pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,
}
-impl From<PaymentsRequest> for VerifyRequest {
- fn from(item: PaymentsRequest) -> Self {
- Self {
- client_secret: item.client_secret,
- merchant_id: item.merchant_id,
- customer_id: item.customer_id,
- email: item.email,
- name: item.name,
- phone: item.phone,
- phone_country_code: item.phone_country_code,
- payment_method: item.payment_method,
- payment_method_data: item.payment_method_data,
- payment_token: item.payment_token,
- mandate_data: item.mandate_data,
- setup_future_usage: item.setup_future_usage,
- off_session: item.off_session,
- merchant_connector_details: item.merchant_connector_details,
- }
- }
-}
-
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MandateTxnType {
@@ -1478,7 +1489,12 @@ impl From<&PaymentsRequest> for MandateValidationFields {
Self {
mandate_id: req.mandate_id.clone(),
confirm: req.confirm,
- customer_id: req.customer_id.clone(),
+ customer_id: req
+ .customer
+ .as_ref()
+ .map(|customer_details| &customer_details.id)
+ .or(req.customer_id.as_ref())
+ .map(ToOwned::to_owned),
mandate_data: req.mandate_data.clone(),
setup_future_usage: req.setup_future_usage,
off_session: req.off_session,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 235ef14e7c1..badb8d948bf 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -96,7 +96,7 @@ pub async fn get_address_for_payment_request(
req_address: Option<&api::Address>,
address_id: Option<&str>,
merchant_id: &str,
- customer_id: &Option<String>,
+ customer_id: Option<&String>,
) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> {
let key = types::get_merchant_enc_key(db, merchant_id.to_string())
.await
@@ -179,7 +179,7 @@ pub async fn get_address_for_payment_request(
}
None => {
// generate a new address here
- let customer_id = customer_id.as_deref().get_required_value("customer_id")?;
+ let customer_id = customer_id.get_required_value("customer_id")?;
let address_details = address.address.clone().unwrap_or_default();
Some(
@@ -460,7 +460,7 @@ fn validate_new_mandate_request(
is_confirm_operation: bool,
) -> RouterResult<()> {
// We need not check for customer_id in the confirm request if it is already passed
- //in create request
+ // in create request
fp_utils::when(!is_confirm_operation && req.customer_id.is_none(), || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
@@ -810,6 +810,109 @@ pub async fn get_customer_from_details<F: Clone>(
}
}
+// Checks if the inner values of two options are not equal and throws appropriate error
+fn validate_options_for_inequality<T: PartialEq>(
+ first_option: Option<&T>,
+ second_option: Option<&T>,
+ field_name: &str,
+) -> Result<(), errors::ApiErrorResponse> {
+ fp_utils::when(
+ first_option
+ .zip(second_option)
+ .map(|(value1, value2)| value1 != value2)
+ .unwrap_or(false),
+ || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: format!("The field name `{field_name}` sent in both places is ambiguous"),
+ })
+ },
+ )
+}
+
+// Checks if the customer details are passed in both places
+// If so, raise an error
+pub fn validate_customer_details_in_request(
+ request: &api_models::payments::PaymentsRequest,
+) -> Result<(), errors::ApiErrorResponse> {
+ if let Some(customer_details) = request.customer.as_ref() {
+ validate_options_for_inequality(
+ request.customer_id.as_ref(),
+ Some(&customer_details.id),
+ "customer_id",
+ )?;
+
+ validate_options_for_inequality(
+ request.email.as_ref(),
+ customer_details.email.as_ref(),
+ "email",
+ )?;
+
+ validate_options_for_inequality(
+ request.name.as_ref(),
+ customer_details.name.as_ref(),
+ "name",
+ )?;
+
+ validate_options_for_inequality(
+ request.phone.as_ref(),
+ customer_details.phone.as_ref(),
+ "phone",
+ )?;
+
+ validate_options_for_inequality(
+ request.phone_country_code.as_ref(),
+ customer_details.phone_country_code.as_ref(),
+ "phone_country_code",
+ )?;
+ }
+
+ Ok(())
+}
+
+/// Get the customer details from customer field if present
+/// or from the individual fields in `PaymentsRequest`
+pub fn get_customer_details_from_request(
+ request: &api_models::payments::PaymentsRequest,
+) -> CustomerDetails {
+ let customer_id = request
+ .customer
+ .as_ref()
+ .map(|customer_details| customer_details.id.clone())
+ .or(request.customer_id.clone());
+
+ let customer_name = request
+ .customer
+ .as_ref()
+ .and_then(|customer_details| customer_details.name.clone())
+ .or(request.name.clone());
+
+ let customer_email = request
+ .customer
+ .as_ref()
+ .and_then(|customer_details| customer_details.email.clone())
+ .or(request.email.clone());
+
+ let customer_phone = request
+ .customer
+ .as_ref()
+ .and_then(|customer_details| customer_details.phone.clone())
+ .or(request.phone.clone());
+
+ let customer_phone_code = request
+ .customer
+ .as_ref()
+ .and_then(|customer_details| customer_details.phone_country_code.clone())
+ .or(request.phone_country_code.clone());
+
+ CustomerDetails {
+ customer_id,
+ name: customer_name,
+ email: customer_email,
+ phone: customer_phone,
+ phone_country_code: customer_phone_code,
+ }
+}
+
pub async fn get_connector_default(
_state: &AppState,
request_connector: Option<serde_json::Value>,
diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs
index 54cc83581ae..f06bf9e252a 100644
--- a/crates/router/src/core/payments/operations/payment_cancel.rs
+++ b/crates/router/src/core/payments/operations/payment_cancel.rs
@@ -80,7 +80,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest>
None,
payment_intent.shipping_address_id.as_deref(),
merchant_id,
- &payment_intent.customer_id,
+ payment_intent.customer_id.as_ref(),
)
.await?;
let billing_address = helpers::get_address_for_payment_request(
@@ -88,7 +88,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest>
None,
payment_intent.billing_address_id.as_deref(),
merchant_id,
- &payment_intent.customer_id,
+ payment_intent.customer_id.as_ref(),
)
.await?;
diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs
index 37f2ccb9d1b..cedc9d7a6d3 100644
--- a/crates/router/src/core/payments/operations/payment_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_capture.rs
@@ -99,7 +99,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu
None,
payment_intent.shipping_address_id.as_deref(),
merchant_id,
- &payment_intent.customer_id,
+ payment_intent.customer_id.as_ref(),
)
.await?;
@@ -108,7 +108,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu
None,
payment_intent.billing_address_id.as_deref(),
merchant_id,
- &payment_intent.customer_id,
+ payment_intent.customer_id.as_ref(),
)
.await?;
diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
index fd06d9a6727..6f7bb3494ec 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -135,7 +135,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co
request.shipping.as_ref(),
payment_intent.shipping_address_id.as_deref(),
merchant_id,
- &payment_intent.customer_id,
+ payment_intent.customer_id.as_ref(),
)
.await?;
let billing_address = helpers::get_address_for_payment_request(
@@ -143,7 +143,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co
request.billing.as_ref(),
payment_intent.billing_address_id.as_deref(),
merchant_id,
- &payment_intent.customer_id,
+ payment_intent.customer_id.as_ref(),
)
.await?;
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index b136610f726..00951faee3f 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -122,6 +122,8 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
field_name: "browser_info",
})?;
+ let customer_details = helpers::get_customer_details_from_request(request);
+
let token = token.or_else(|| payment_attempt.payment_token.clone());
helpers::validate_pm_or_token_given(
@@ -159,7 +161,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
&payment_intent
.customer_id
.clone()
- .or_else(|| request.customer_id.clone()),
+ .or_else(|| customer_details.customer_id.clone()),
)?;
let shipping_address = helpers::get_address_for_payment_request(
@@ -167,7 +169,10 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
request.shipping.as_ref(),
payment_intent.shipping_address_id.as_deref(),
merchant_id,
- &payment_intent.customer_id,
+ payment_intent
+ .customer_id
+ .as_ref()
+ .or(customer_details.customer_id.as_ref()),
)
.await?;
let billing_address = helpers::get_address_for_payment_request(
@@ -175,7 +180,10 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
request.billing.as_ref(),
payment_intent.billing_address_id.as_deref(),
merchant_id,
- &payment_intent.customer_id,
+ payment_intent
+ .customer_id
+ .as_ref()
+ .or(customer_details.customer_id.as_ref()),
)
.await?;
@@ -255,13 +263,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
ephemeral_key: None,
redirect_response: None,
},
- Some(CustomerDetails {
- customer_id: request.customer_id.clone(),
- name: request.name.clone(),
- email: request.email.clone(),
- phone: request.phone.clone(),
- phone_country_code: request.phone_country_code.clone(),
- }),
+ Some(customer_details),
))
}
}
@@ -472,6 +474,9 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentConfir
{
Err(errors::ApiErrorResponse::NotSupported { message: "order_details cannot be present both inside and outside metadata in payments request".to_string() })?
}
+
+ helpers::validate_customer_details_in_request(request)?;
+
let given_payment_id = match &request.payment_id {
Some(id_type) => Some(
id_type
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index ee4af6244b0..b4b75cd815c 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -74,12 +74,14 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
)
.await?;
+ let customer_details = helpers::get_customer_details_from_request(request);
+
let shipping_address = helpers::get_address_for_payment_request(
db,
request.shipping.as_ref(),
None,
merchant_id,
- &request.customer_id,
+ customer_details.customer_id.as_ref(),
)
.await?;
@@ -88,7 +90,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
request.billing.as_ref(),
None,
merchant_id,
- &request.customer_id,
+ customer_details.customer_id.as_ref(),
)
.await?;
@@ -256,13 +258,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
ephemeral_key,
redirect_response: None,
},
- Some(CustomerDetails {
- customer_id: request.customer_id.clone(),
- name: request.name.clone(),
- email: request.email.clone(),
- phone: request.phone.clone(),
- phone_country_code: request.phone_country_code.clone(),
- }),
+ Some(customer_details),
))
}
}
@@ -423,6 +419,9 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate
{
Err(errors::ApiErrorResponse::NotSupported { message: "order_details cannot be present both inside and outside metadata in payments request".to_string() })?
}
+
+ helpers::validate_customer_details_in_request(request)?;
+
let given_payment_id = match &request.payment_id {
Some(id_type) => Some(
id_type
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 3c1e9529113..5fe496aa281 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -87,7 +87,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest>
None,
payment_intent.shipping_address_id.as_deref(),
merchant_id,
- &payment_intent.customer_id,
+ payment_intent.customer_id.as_ref(),
)
.await?;
@@ -96,7 +96,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest>
None,
payment_intent.billing_address_id.as_deref(),
merchant_id,
- &payment_intent.customer_id,
+ payment_intent.customer_id.as_ref(),
)
.await?;
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index c197097e7ac..5cb6613a28b 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -81,7 +81,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f
None,
payment_intent.shipping_address_id.as_deref(),
merchant_id,
- &payment_intent.customer_id,
+ payment_intent.customer_id.as_ref(),
)
.await?;
let billing_address = helpers::get_address_for_payment_request(
@@ -89,7 +89,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f
None,
payment_intent.billing_address_id.as_deref(),
merchant_id,
- &payment_intent.customer_id,
+ payment_intent.customer_id.as_ref(),
)
.await?;
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index b36fe6ea966..15ef40f34e5 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -107,6 +107,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
};
payment_attempt.payment_method = payment_method_type.or(payment_attempt.payment_method);
+ let customer_details = helpers::get_customer_details_from_request(request);
let amount = request
.amount
@@ -120,7 +121,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
&payment_intent
.customer_id
.clone()
- .or_else(|| request.customer_id.clone()),
+ .or_else(|| customer_details.customer_id.clone()),
)?;
}
@@ -129,7 +130,10 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
request.shipping.as_ref(),
payment_intent.shipping_address_id.as_deref(),
merchant_id,
- &payment_intent.customer_id,
+ payment_intent
+ .customer_id
+ .as_ref()
+ .or(customer_details.customer_id.as_ref()),
)
.await?;
let billing_address = helpers::get_address_for_payment_request(
@@ -137,7 +141,10 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
request.billing.as_ref(),
payment_intent.billing_address_id.as_deref(),
merchant_id,
- &payment_intent.customer_id,
+ payment_intent
+ .customer_id
+ .as_ref()
+ .or(customer_details.customer_id.as_ref()),
)
.await?;
@@ -281,6 +288,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
.clone()
.map(ForeignInto::foreign_into)),
});
+
Ok((
next_operation,
PaymentData {
@@ -312,13 +320,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
ephemeral_key: None,
redirect_response: None,
},
- Some(CustomerDetails {
- customer_id: request.customer_id.clone(),
- name: request.name.clone(),
- email: request.email.clone(),
- phone: request.phone.clone(),
- phone_country_code: request.phone_country_code.clone(),
- }),
+ Some(customer_details),
))
}
}
@@ -526,6 +528,9 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentUpdate
{
Err(errors::ApiErrorResponse::NotSupported { message: "order_details cannot be present both inside and outside metadata in payments request".to_string() })?
}
+
+ helpers::validate_customer_details_in_request(request)?;
+
let given_payment_id = match &request.payment_id {
Some(id_type) => Some(
id_type
diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs
index 1ae4cce0334..9e870c5cd25 100644
--- a/crates/router/src/openapi.rs
+++ b/crates/router/src/openapi.rs
@@ -241,6 +241,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::mandates::MandateResponse,
api_models::mandates::MandateCardDetails,
api_models::ephemeral_key::EphemeralKeyCreateResponse,
+ api_models::payments::CustomerDetails,
crate::types::api::admin::MerchantAccountResponse,
crate::types::api::admin::MerchantConnectorId,
crate::types::api::admin::MerchantDetails,
|
refactor
|
accept customer data in customer object (#1447)
|
9c1ebd219fcaeefb6bd06c21c2358bf19a332891
|
2025-01-22 06:00:48
|
github-actions
|
chore(version): 2025.01.22.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5084a0990d2..f8246d67ed0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,28 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 2025.01.22.0
+
+### Features
+
+- **connectors:** Fiuu,novalnet,worldpay - extend NTI flows ([#6946](https://github.com/juspay/hyperswitch/pull/6946)) ([`d6b0660`](https://github.com/juspay/hyperswitch/commit/d6b0660569eb8bbbc6557aa6ed29184fe51ab209))
+- **email:** Add mailhog by default in docker-compose for local smtp server ([#6869](https://github.com/juspay/hyperswitch/pull/6869)) ([`100a178`](https://github.com/juspay/hyperswitch/commit/100a1783ac79b1f0888de786c5d12ce813126c21))
+- **router:** Add payment method-specific features to connector feature list ([#6963](https://github.com/juspay/hyperswitch/pull/6963)) ([`e35f707`](https://github.com/juspay/hyperswitch/commit/e35f7079e3fc9ada76d0602739053bdd5d595008))
+- **routing:** Integrate global success rates ([#6950](https://github.com/juspay/hyperswitch/pull/6950)) ([`39d2d6c`](https://github.com/juspay/hyperswitch/commit/39d2d6c43800f609070b61a6148ddef7e40001bc))
+
+### Bug Fixes
+
+- **cypress:** Address cybersource redirection inconsistency ([#7057](https://github.com/juspay/hyperswitch/pull/7057)) ([`90c932a`](https://github.com/juspay/hyperswitch/commit/90c932a6d798453f7e828c55a7668c5c64c933a5))
+
+### Refactors
+
+- Customer email and browser Information ([#7034](https://github.com/juspay/hyperswitch/pull/7034)) ([`d35a922`](https://github.com/juspay/hyperswitch/commit/d35a9222815e9259a6097eabd41cd458650cb62e))
+- Check allowed payment method types in enabled options ([#7019](https://github.com/juspay/hyperswitch/pull/7019)) ([`0eca55f`](https://github.com/juspay/hyperswitch/commit/0eca55f75392f8091a1cf8f378e8cbee9afd3eac))
+
+**Full Changelog:** [`2025.01.21.0...2025.01.22.0`](https://github.com/juspay/hyperswitch/compare/2025.01.21.0...2025.01.22.0)
+
+- - -
+
## 2025.01.21.0
### Refactors
|
chore
|
2025.01.22.0
|
275155a84db77d9b4b3619894b40d479a357fb1c
|
2023-02-25 18:47:47
|
Narayan Bhat
|
refactor: add better log to parse struct (#621)
| false
|
diff --git a/crates/common_utils/src/ext_traits.rs b/crates/common_utils/src/ext_traits.rs
index 1d98f7d3452..101b11920c3 100644
--- a/crates/common_utils/src/ext_traits.rs
+++ b/crates/common_utils/src/ext_traits.rs
@@ -157,7 +157,7 @@ pub trait BytesExt<T> {
}
impl<T> BytesExt<T> for bytes::Bytes {
- fn parse_struct<'de>(&'de self, type_name: &str) -> CustomResult<T, errors::ParsingError>
+ fn parse_struct<'de>(&'de self, _type_name: &str) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>,
{
@@ -166,7 +166,10 @@ impl<T> BytesExt<T> for bytes::Bytes {
serde_json::from_slice::<T>(self.chunk())
.into_report()
.change_context(errors::ParsingError)
- .attach_printable_lazy(|| format!("Unable to parse {type_name} from bytes"))
+ .attach_printable_lazy(|| {
+ let variable_type = std::any::type_name::<T>();
+ format!("Unable to parse {variable_type} from bytes {self:?}")
+ })
}
}
|
refactor
|
add better log to parse struct (#621)
|
3509b45e1b855dce4561beb5cded4ba490be6f8c
|
2024-06-05 00:01:59
|
Swangi Kumari
|
refactor(connector): [Klarna] Add support for Klarna Optional Shipping Address (#4876)
| false
|
diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs
index 69b9dfc67bb..a3d84a3546a 100644
--- a/crates/router/src/connector/klarna/transformers.rs
+++ b/crates/router/src/connector/klarna/transformers.rs
@@ -5,7 +5,9 @@ use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{self, PaymentsAuthorizeRequestData, RouterData},
+ connector::utils::{
+ self, AddressData, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData,
+ },
core::errors,
types::{self, api, storage::enums, transformers::ForeignFrom},
};
@@ -96,15 +98,15 @@ pub struct KlarnaSessionRequest {
#[derive(Debug, Serialize)]
pub struct KlarnaShippingAddress {
- city: Option<String>,
- country: Option<enums::CountryAlpha2>,
- email: Option<pii::Email>,
- given_name: Option<Secret<String>>,
- family_name: Option<Secret<String>>,
- phone: Option<Secret<String>>,
- postal_code: Option<Secret<String>>,
- region: Option<Secret<String>>,
- street_address: Option<Secret<String>>,
+ city: String,
+ country: enums::CountryAlpha2,
+ email: pii::Email,
+ given_name: Secret<String>,
+ family_name: Secret<String>,
+ phone: Secret<String>,
+ postal_code: Secret<String>,
+ region: Secret<String>,
+ street_address: Secret<String>,
street_address2: Option<Secret<String>>,
}
@@ -139,18 +141,8 @@ impl TryFrom<&KlarnaRouterData<&types::PaymentsSessionRouterData>> for KlarnaSes
total_amount: i64::from(data.quantity) * (data.amount),
})
.collect(),
- shipping_address: Some(KlarnaShippingAddress {
- city: item.router_data.get_optional_shipping_city(),
- country: item.router_data.get_optional_shipping_country(),
- email: item.router_data.get_optional_shipping_email(),
- given_name: item.router_data.get_optional_shipping_first_name(),
- family_name: item.router_data.get_optional_shipping_last_name(),
- phone: item.router_data.get_optional_shipping_phone_number(),
- postal_code: item.router_data.get_optional_shipping_zip(),
- region: item.router_data.get_optional_shipping_state(),
- street_address: item.router_data.get_optional_shipping_line1(),
- street_address2: item.router_data.get_optional_shipping_line2(),
- }),
+ shipping_address: get_address_info(item.router_data.get_optional_shipping())
+ .transpose()?,
}),
None => Err(report!(errors::ConnectorError::MissingRequiredField {
field_name: "order_details",
@@ -204,18 +196,8 @@ impl TryFrom<&KlarnaRouterData<&types::PaymentsAuthorizeRouterData>> for KlarnaP
.collect(),
merchant_reference1: Some(item.router_data.connector_request_reference_id.clone()),
auto_capture: request.is_auto_capture()?,
- shipping_address: Some(KlarnaShippingAddress {
- city: item.router_data.get_optional_shipping_city(),
- country: item.router_data.get_optional_shipping_country(),
- email: item.router_data.get_optional_shipping_email(),
- given_name: item.router_data.get_optional_shipping_first_name(),
- family_name: item.router_data.get_optional_shipping_last_name(),
- phone: item.router_data.get_optional_shipping_phone_number(),
- postal_code: item.router_data.get_optional_shipping_zip(),
- region: item.router_data.get_optional_shipping_state(),
- street_address: item.router_data.get_optional_shipping_line1(),
- street_address2: item.router_data.get_optional_shipping_line2(),
- }),
+ shipping_address: get_address_info(item.router_data.get_optional_shipping())
+ .transpose()?,
}),
None => Err(report!(errors::ConnectorError::MissingRequiredField {
field_name: "order_details"
@@ -224,6 +206,29 @@ impl TryFrom<&KlarnaRouterData<&types::PaymentsAuthorizeRouterData>> for KlarnaP
}
}
+fn get_address_info(
+ address: Option<&payments::Address>,
+) -> Option<Result<KlarnaShippingAddress, error_stack::Report<errors::ConnectorError>>> {
+ address.and_then(|add| {
+ add.address.as_ref().map(
+ |address_details| -> Result<KlarnaShippingAddress, error_stack::Report<errors::ConnectorError>> {
+ Ok(KlarnaShippingAddress {
+ city: address_details.get_city()?.to_owned(),
+ country: address_details.get_country()?.to_owned(),
+ email: add.get_email()?.to_owned(),
+ postal_code: address_details.get_zip()?.to_owned(),
+ region: address_details.to_state_code()?.to_owned(),
+ street_address: address_details.get_line1()?.to_owned(),
+ street_address2: address_details.get_optional_line2(),
+ given_name: address_details.get_first_name()?.to_owned(),
+ family_name: address_details.get_last_name()?.to_owned(),
+ phone: add.get_phone_with_country_code()?.to_owned(),
+ })
+ },
+ )
+ })
+}
+
impl TryFrom<types::PaymentsResponseRouterData<KlarnaPaymentsResponse>>
for types::PaymentsAuthorizeRouterData
{
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 873e6f18d23..898a368436e 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -541,6 +541,25 @@ impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Re
}
}
+pub trait AddressData {
+ fn get_email(&self) -> Result<Email, Error>;
+ fn get_phone_with_country_code(&self) -> Result<Secret<String>, Error>;
+}
+
+impl AddressData for api::Address {
+ fn get_email(&self) -> Result<Email, Error> {
+ self.email.clone().ok_or_else(missing_field_err("email"))
+ }
+
+ fn get_phone_with_country_code(&self) -> Result<Secret<String>, Error> {
+ self.phone
+ .clone()
+ .map(|phone_details| phone_details.get_number_with_country_code())
+ .transpose()?
+ .ok_or_else(missing_field_err("phone"))
+ }
+}
+
pub trait PaymentsPreProcessingData {
fn get_email(&self) -> Result<Email, Error>;
fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>;
@@ -1519,6 +1538,7 @@ pub trait AddressDetailsData {
fn get_combined_address_line(&self) -> Result<Secret<String>, Error>;
fn to_state_code(&self) -> Result<Secret<String>, Error>;
fn to_state_code_as_optional(&self) -> Result<Option<Secret<String>>, Error>;
+ fn get_optional_line2(&self) -> Option<Secret<String>>;
}
impl AddressDetailsData for api::AddressDetails {
@@ -1614,6 +1634,10 @@ impl AddressDetailsData for api::AddressDetails {
})
.transpose()
}
+
+ fn get_optional_line2(&self) -> Option<Secret<String>> {
+ self.line2.clone()
+ }
}
pub trait MandateData {
|
refactor
|
[Klarna] Add support for Klarna Optional Shipping Address (#4876)
|
9c1c44a706750b14857e9180f5161b61ed89a2ad
|
2023-12-06 20:48:41
|
Chethan Rao
|
feat(pm_auth): pm_auth service migration (#3047)
| false
|
diff --git a/.github/workflows/CI-pr.yml b/.github/workflows/CI-pr.yml
index ecb13f3c1a8..79cb352acbb 100644
--- a/.github/workflows/CI-pr.yml
+++ b/.github/workflows/CI-pr.yml
@@ -203,6 +203,11 @@ jobs:
else
echo "test_utils_changes_exist=true" >> $GITHUB_ENV
fi
+ if git diff --submodule=diff --exit-code --quiet origin/$GITHUB_BASE_REF -- crates/pm_auth/; then
+ echo "pm_auth_changes_exist=false" >> $GITHUB_ENV
+ else
+ echo "pm_auth_changes_exist=true" >> $GITHUB_ENV
+ fi
- name: Cargo hack api_models
if: env.api_models_changes_exist == 'true'
@@ -249,6 +254,11 @@ jobs:
shell: bash
run: cargo hack check --each-feature --no-dev-deps -p redis_interface
+ - name: Cargo hack pm_auth
+ if: env.pm_auth_changes_exist == 'true'
+ shell: bash
+ run: cargo hack check --each-feature --no-dev-deps -p pm_auth
+
- name: Cargo hack router
if: env.router_changes_exist == 'true'
shell: bash
@@ -456,6 +466,11 @@ jobs:
else
echo "test_utils_changes_exist=true" >> $GITHUB_ENV
fi
+ if git diff --submodule=diff --exit-code --quiet origin/$GITHUB_BASE_REF -- crates/pm_auth/; then
+ echo "pm_auth_changes_exist=false" >> $GITHUB_ENV
+ else
+ echo "pm_auth_changes_exist=true" >> $GITHUB_ENV
+ fi
- name: Cargo hack api_models
if: env.api_models_changes_exist == 'true'
@@ -502,6 +517,11 @@ jobs:
shell: bash
run: cargo hack check --each-feature --no-dev-deps -p redis_interface
+ - name: Cargo hack pm_auth
+ if: env.pm_auth_changes_exist == 'true'
+ shell: bash
+ run: cargo hack check --each-feature --no-dev-deps -p pm_auth
+
- name: Cargo hack router
if: env.router_changes_exist == 'true'
shell: bash
diff --git a/Cargo.lock b/Cargo.lock
index d2e8d9dd5df..307a5ca2398 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -405,6 +405,8 @@ dependencies = [
"common_utils",
"error-stack",
"euclid",
+ "frunk",
+ "frunk_core",
"masking",
"mime",
"reqwest",
@@ -4436,6 +4438,27 @@ dependencies = [
"plotters-backend",
]
+[[package]]
+name = "pm_auth"
+version = "0.1.0"
+dependencies = [
+ "api_models",
+ "async-trait",
+ "bytes 1.5.0",
+ "common_enums",
+ "common_utils",
+ "error-stack",
+ "http",
+ "masking",
+ "mime",
+ "router_derive",
+ "router_env",
+ "serde",
+ "serde_json",
+ "strum 0.24.1",
+ "thiserror",
+]
+
[[package]]
name = "png"
version = "0.16.8"
@@ -5110,6 +5133,7 @@ dependencies = [
"num_cpus",
"once_cell",
"openssl",
+ "pm_auth",
"qrcode",
"rand 0.8.5",
"rand_chacha 0.3.1",
diff --git a/config/config.example.toml b/config/config.example.toml
index 1897c935581..7a50c23f484 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -122,7 +122,7 @@ kms_encrypted_recon_admin_api_key = "" # Base64-encoded (KMS encrypted) cipher
# like card details
[locker]
host = "" # Locker host
-host_rs = "" # Rust Locker host
+host_rs = "" # Rust Locker host
mock_locker = true # Emulate a locker locally using Postgres
basilisk_host = "" # Basilisk host
locker_signing_key_id = "1" # Key_id to sign basilisk hs locker
@@ -461,6 +461,10 @@ apple_pay_merchant_cert_key = "APPLE_PAY_MERCHNAT_CERTIFICATE_KEY" #Private key
[payment_link]
sdk_url = "http://localhost:9090/dist/HyperLoader.js"
+[payment_method_auth]
+redis_expiry = 900
+pm_auth_key = "Some_pm_auth_key"
+
# Analytics configuration.
[analytics]
source = "sqlx" # The Analytics source/strategy to be used
diff --git a/config/development.toml b/config/development.toml
index 4ee33795676..15acfdee9b7 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -470,6 +470,10 @@ apple_pay_merchant_cert_key = "APPLE_PAY_MERCHNAT_CERTIFICATE_KEY"
[payment_link]
sdk_url = "http://localhost:9090/dist/HyperLoader.js"
+[payment_method_auth]
+redis_expiry = 900
+pm_auth_key = "Some_pm_auth_key"
+
[lock_settings]
redis_lock_expiry_seconds = 180 # 3 * 60 seconds
delay_between_retries_in_milliseconds = 500
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 55fc62329d4..5eec8d733d6 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -330,6 +330,10 @@ payout_connector_list = "wise"
[multiple_api_version_supported_connectors]
supported_connectors = "braintree"
+[payment_method_auth]
+redis_expiry = 900
+pm_auth_key = "Some_pm_auth_key"
+
[lock_settings]
redis_lock_expiry_seconds = 180 # 3 * 60 seconds
delay_between_retries_in_milliseconds = 500
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml
index 116aad25d5c..afba129b601 100644
--- a/crates/api_models/Cargo.toml
+++ b/crates/api_models/Cargo.toml
@@ -30,6 +30,8 @@ strum = { version = "0.25", features = ["derive"] }
time = { version = "0.3.21", features = ["serde", "serde-well-known", "std"] }
url = { version = "2.4.0", features = ["serde"] }
utoipa = { version = "3.3.0", features = ["preserve_order"] }
+frunk = "0.4.1"
+frunk_core = "0.4.1"
# First party crates
cards = { version = "0.1.0", path = "../cards" }
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 17787929a46..21586054055 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -1,3 +1,5 @@
+use std::str::FromStr;
+
pub use common_enums::*;
use utoipa::ToSchema;
@@ -500,3 +502,26 @@ pub enum LockerChoice {
Basilisk,
Tartarus,
}
+
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Eq,
+ PartialEq,
+ serde::Serialize,
+ serde::Deserialize,
+ strum::Display,
+ strum::EnumString,
+ frunk::LabelledGeneric,
+ ToSchema,
+)]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum PmAuthConnectors {
+ Plaid,
+}
+
+pub fn convert_pm_auth_connector(connector_name: &str) -> Option<PmAuthConnectors> {
+ PmAuthConnectors::from_str(connector_name).ok()
+}
diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs
index ce3c11d9c2f..935944cf74c 100644
--- a/crates/api_models/src/lib.rs
+++ b/crates/api_models/src/lib.rs
@@ -23,6 +23,7 @@ pub mod payment_methods;
pub mod payments;
#[cfg(feature = "payouts")]
pub mod payouts;
+pub mod pm_auth;
pub mod refunds;
pub mod routing;
pub mod surcharge_decision_configs;
diff --git a/crates/api_models/src/pm_auth.rs b/crates/api_models/src/pm_auth.rs
new file mode 100644
index 00000000000..7044bd8d335
--- /dev/null
+++ b/crates/api_models/src/pm_auth.rs
@@ -0,0 +1,57 @@
+use common_enums::{PaymentMethod, PaymentMethodType};
+use common_utils::{
+ events::{ApiEventMetric, ApiEventsType},
+ impl_misc_api_event_type,
+};
+
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub struct LinkTokenCreateRequest {
+ pub language: Option<String>, // optional language field to be passed
+ pub client_secret: Option<String>, // client secret to be passed in req body
+ pub payment_id: String, // payment_id to be passed in req body for redis pm_auth connector name fetch
+ pub payment_method: PaymentMethod, // payment_method to be used for filtering pm_auth connector
+ pub payment_method_type: PaymentMethodType, // payment_method_type to be used for filtering pm_auth connector
+}
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct LinkTokenCreateResponse {
+ pub link_token: String, // link_token received in response
+ pub connector: String, // pm_auth connector name in response
+}
+
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+
+pub struct ExchangeTokenCreateRequest {
+ pub public_token: String,
+ pub client_secret: Option<String>,
+ pub payment_id: String,
+ pub payment_method: PaymentMethod,
+ pub payment_method_type: PaymentMethodType,
+}
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct ExchangeTokenCreateResponse {
+ pub access_token: String,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct PaymentMethodAuthConfig {
+ pub enabled_payment_methods: Vec<PaymentMethodAuthConnectorChoice>,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct PaymentMethodAuthConnectorChoice {
+ pub payment_method: PaymentMethod,
+ pub payment_method_type: PaymentMethodType,
+ pub connector_name: String,
+ pub mca_id: String,
+}
+
+impl_misc_api_event_type!(
+ LinkTokenCreateRequest,
+ LinkTokenCreateResponse,
+ ExchangeTokenCreateRequest,
+ ExchangeTokenCreateResponse
+);
diff --git a/crates/pm_auth/Cargo.toml b/crates/pm_auth/Cargo.toml
new file mode 100644
index 00000000000..a9aebc5b540
--- /dev/null
+++ b/crates/pm_auth/Cargo.toml
@@ -0,0 +1,27 @@
+[package]
+name = "pm_auth"
+description = "Open banking services"
+version = "0.1.0"
+edition.workspace = true
+rust-version.workspace = true
+readme = "README.md"
+
+[dependencies]
+# First party crates
+api_models = { version = "0.1.0", path = "../api_models" }
+common_enums = { version = "0.1.0", path = "../common_enums" }
+common_utils = { version = "0.1.0", path = "../common_utils" }
+masking = { version = "0.1.0", path = "../masking" }
+router_derive = { version = "0.1.0", path = "../router_derive" }
+router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }
+
+# Third party crates
+async-trait = "0.1.66"
+bytes = "1.4.0"
+error-stack = "0.3.1"
+http = "0.2.9"
+mime = "0.3.17"
+serde = "1.0.159"
+serde_json = "1.0.91"
+strum = { version = "0.24.1", features = ["derive"] }
+thiserror = "1.0.43"
diff --git a/crates/pm_auth/README.md b/crates/pm_auth/README.md
new file mode 100644
index 00000000000..c630a7fe676
--- /dev/null
+++ b/crates/pm_auth/README.md
@@ -0,0 +1,3 @@
+# Payment Method Auth Services
+
+An open banking services for payment method auth validation
diff --git a/crates/pm_auth/src/connector.rs b/crates/pm_auth/src/connector.rs
new file mode 100644
index 00000000000..56aad846e24
--- /dev/null
+++ b/crates/pm_auth/src/connector.rs
@@ -0,0 +1,3 @@
+pub mod plaid;
+
+pub use self::plaid::Plaid;
diff --git a/crates/pm_auth/src/connector/plaid.rs b/crates/pm_auth/src/connector/plaid.rs
new file mode 100644
index 00000000000..d25aba881d2
--- /dev/null
+++ b/crates/pm_auth/src/connector/plaid.rs
@@ -0,0 +1,353 @@
+pub mod transformers;
+
+use std::fmt::Debug;
+
+use common_utils::{
+ ext_traits::{BytesExt, Encode},
+ request::{Method, Request, RequestBody, RequestBuilder},
+};
+use error_stack::ResultExt;
+use masking::{Mask, Maskable};
+use transformers as plaid;
+
+use crate::{
+ core::errors,
+ types::{
+ self as auth_types,
+ api::{
+ auth_service::{self, BankAccountCredentials, ExchangeToken, LinkToken},
+ ConnectorCommon, ConnectorCommonExt, ConnectorIntegration,
+ },
+ },
+};
+
+#[derive(Debug, Clone)]
+pub struct Plaid;
+
+impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Plaid
+where
+ Self: ConnectorIntegration<Flow, Request, Response>,
+{
+ fn build_headers(
+ &self,
+ req: &auth_types::PaymentAuthRouterData<Flow, Request, Response>,
+ _connectors: &auth_types::PaymentMethodAuthConnectors,
+ ) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
+ let mut header = vec![(
+ "Content-Type".to_string(),
+ self.get_content_type().to_string().into(),
+ )];
+
+ let mut auth = self.get_auth_header(&req.connector_auth_type)?;
+ header.append(&mut auth);
+ Ok(header)
+ }
+}
+
+impl ConnectorCommon for Plaid {
+ fn id(&self) -> &'static str {
+ "plaid"
+ }
+
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+ fn base_url<'a>(&self, _connectors: &'a auth_types::PaymentMethodAuthConnectors) -> &'a str {
+ "https://sandbox.plaid.com"
+ }
+
+ fn get_auth_header(
+ &self,
+ auth_type: &auth_types::ConnectorAuthType,
+ ) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
+ let auth = plaid::PlaidAuthType::try_from(auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ let client_id = auth.client_id.into_masked();
+ let secret = auth.secret.into_masked();
+
+ Ok(vec![
+ ("PLAID-CLIENT-ID".to_string(), client_id),
+ ("PLAID-SECRET".to_string(), secret),
+ ])
+ }
+
+ fn build_error_response(
+ &self,
+ res: auth_types::Response,
+ ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
+ let response: plaid::PlaidErrorResponse =
+ res.response
+ .parse_struct("PlaidErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ Ok(auth_types::ErrorResponse {
+ status_code: res.status_code,
+ code: crate::consts::NO_ERROR_CODE.to_string(),
+ message: response.error_message,
+ reason: response.display_message,
+ })
+ }
+}
+
+impl auth_service::AuthService for Plaid {}
+impl auth_service::AuthServiceLinkToken for Plaid {}
+
+impl ConnectorIntegration<LinkToken, auth_types::LinkTokenRequest, auth_types::LinkTokenResponse>
+ for Plaid
+{
+ fn get_headers(
+ &self,
+ req: &auth_types::LinkTokenRouterData,
+ connectors: &auth_types::PaymentMethodAuthConnectors,
+ ) -> errors::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: &auth_types::LinkTokenRouterData,
+ connectors: &auth_types::PaymentMethodAuthConnectors,
+ ) -> errors::CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}{}",
+ self.base_url(connectors),
+ "/link/token/create"
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &auth_types::LinkTokenRouterData,
+ ) -> errors::CustomResult<Option<RequestBody>, errors::ConnectorError> {
+ let req_obj = plaid::PlaidLinkTokenRequest::try_from(req)?;
+ let plaid_req = RequestBody::log_and_get_request_body(
+ &req_obj,
+ Encode::<plaid::PlaidLinkTokenRequest>::encode_to_string_of_json,
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(plaid_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &auth_types::LinkTokenRouterData,
+ connectors: &auth_types::PaymentMethodAuthConnectors,
+ ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&auth_types::PaymentAuthLinkTokenType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(auth_types::PaymentAuthLinkTokenType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(auth_types::PaymentAuthLinkTokenType::get_request_body(
+ self, req,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &auth_types::LinkTokenRouterData,
+ res: auth_types::Response,
+ ) -> errors::CustomResult<auth_types::LinkTokenRouterData, errors::ConnectorError> {
+ let response: plaid::PlaidLinkTokenResponse = res
+ .response
+ .parse_struct("PlaidLinkTokenResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ <auth_types::LinkTokenRouterData>::try_from(auth_types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+ fn get_error_response(
+ &self,
+ res: auth_types::Response,
+ ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl auth_service::AuthServiceExchangeToken for Plaid {}
+
+impl
+ ConnectorIntegration<
+ ExchangeToken,
+ auth_types::ExchangeTokenRequest,
+ auth_types::ExchangeTokenResponse,
+ > for Plaid
+{
+ fn get_headers(
+ &self,
+ req: &auth_types::ExchangeTokenRouterData,
+ connectors: &auth_types::PaymentMethodAuthConnectors,
+ ) -> errors::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: &auth_types::ExchangeTokenRouterData,
+ connectors: &auth_types::PaymentMethodAuthConnectors,
+ ) -> errors::CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}{}",
+ self.base_url(connectors),
+ "/item/public_token/exchange"
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &auth_types::ExchangeTokenRouterData,
+ ) -> errors::CustomResult<Option<RequestBody>, errors::ConnectorError> {
+ let req_obj = plaid::PlaidExchangeTokenRequest::try_from(req)?;
+ let plaid_req = RequestBody::log_and_get_request_body(
+ &req_obj,
+ Encode::<plaid::PlaidExchangeTokenRequest>::encode_to_string_of_json,
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(plaid_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &auth_types::ExchangeTokenRouterData,
+ connectors: &auth_types::PaymentMethodAuthConnectors,
+ ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&auth_types::PaymentAuthExchangeTokenType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(auth_types::PaymentAuthExchangeTokenType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(auth_types::PaymentAuthExchangeTokenType::get_request_body(
+ self, req,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &auth_types::ExchangeTokenRouterData,
+ res: auth_types::Response,
+ ) -> errors::CustomResult<auth_types::ExchangeTokenRouterData, errors::ConnectorError> {
+ let response: plaid::PlaidExchangeTokenResponse = res
+ .response
+ .parse_struct("PlaidExchangeTokenResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ <auth_types::ExchangeTokenRouterData>::try_from(auth_types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+ fn get_error_response(
+ &self,
+ res: auth_types::Response,
+ ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl auth_service::AuthServiceBankAccountCredentials for Plaid {}
+
+impl
+ ConnectorIntegration<
+ BankAccountCredentials,
+ auth_types::BankAccountCredentialsRequest,
+ auth_types::BankAccountCredentialsResponse,
+ > for Plaid
+{
+ fn get_headers(
+ &self,
+ req: &auth_types::BankDetailsRouterData,
+ connectors: &auth_types::PaymentMethodAuthConnectors,
+ ) -> errors::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: &auth_types::BankDetailsRouterData,
+ connectors: &auth_types::PaymentMethodAuthConnectors,
+ ) -> errors::CustomResult<String, errors::ConnectorError> {
+ Ok(format!("{}{}", self.base_url(connectors), "/auth/get"))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &auth_types::BankDetailsRouterData,
+ ) -> errors::CustomResult<Option<RequestBody>, errors::ConnectorError> {
+ let req_obj = plaid::PlaidBankAccountCredentialsRequest::try_from(req)?;
+ let plaid_req = RequestBody::log_and_get_request_body(
+ &req_obj,
+ Encode::<plaid::PlaidBankAccountCredentialsRequest>::encode_to_string_of_json,
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(plaid_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &auth_types::BankDetailsRouterData,
+ connectors: &auth_types::PaymentMethodAuthConnectors,
+ ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&auth_types::PaymentAuthBankAccountDetailsType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(auth_types::PaymentAuthBankAccountDetailsType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(auth_types::PaymentAuthBankAccountDetailsType::get_request_body(self, req)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &auth_types::BankDetailsRouterData,
+ res: auth_types::Response,
+ ) -> errors::CustomResult<auth_types::BankDetailsRouterData, errors::ConnectorError> {
+ let response: plaid::PlaidBankAccountCredentialsResponse = res
+ .response
+ .parse_struct("PlaidBankAccountCredentialsResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ <auth_types::BankDetailsRouterData>::try_from(auth_types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+ fn get_error_response(
+ &self,
+ res: auth_types::Response,
+ ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
diff --git a/crates/pm_auth/src/connector/plaid/transformers.rs b/crates/pm_auth/src/connector/plaid/transformers.rs
new file mode 100644
index 00000000000..5e1ad67aead
--- /dev/null
+++ b/crates/pm_auth/src/connector/plaid/transformers.rs
@@ -0,0 +1,294 @@
+use std::collections::HashMap;
+
+use common_enums::PaymentMethodType;
+use masking::Secret;
+use serde::{Deserialize, Serialize};
+
+use crate::{core::errors, types};
+
+#[derive(Debug, Serialize, Eq, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub struct PlaidLinkTokenRequest {
+ client_name: String,
+ country_codes: Vec<String>,
+ language: String,
+ products: Vec<String>,
+ user: User,
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq)]
+
+pub struct User {
+ pub client_user_id: String,
+}
+
+impl TryFrom<&types::LinkTokenRouterData> for PlaidLinkTokenRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::LinkTokenRouterData) -> Result<Self, Self::Error> {
+ Ok(Self {
+ client_name: item.request.client_name.clone(),
+ country_codes: item.request.country_codes.clone().ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "country_codes",
+ },
+ )?,
+ language: item.request.language.clone().unwrap_or("en".to_string()),
+ products: vec!["auth".to_string()],
+ user: User {
+ client_user_id: item.request.user_info.clone().ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "country_codes",
+ },
+ )?,
+ },
+ })
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub struct PlaidLinkTokenResponse {
+ link_token: String,
+}
+
+impl<F, T>
+ TryFrom<types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::LinkTokenResponse>>
+ for types::PaymentAuthRouterData<F, T, types::LinkTokenResponse>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::LinkTokenResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::LinkTokenResponse {
+ link_token: item.response.link_token,
+ }),
+ ..item.data
+ })
+ }
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub struct PlaidExchangeTokenRequest {
+ public_token: String,
+}
+
+#[derive(Debug, Deserialize, Eq, PartialEq)]
+
+pub struct PlaidExchangeTokenResponse {
+ pub access_token: String,
+}
+
+impl<F, T>
+ TryFrom<
+ types::ResponseRouterData<F, PlaidExchangeTokenResponse, T, types::ExchangeTokenResponse>,
+ > for types::PaymentAuthRouterData<F, T, types::ExchangeTokenResponse>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<
+ F,
+ PlaidExchangeTokenResponse,
+ T,
+ types::ExchangeTokenResponse,
+ >,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::ExchangeTokenResponse {
+ access_token: item.response.access_token,
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<&types::ExchangeTokenRouterData> for PlaidExchangeTokenRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::ExchangeTokenRouterData) -> Result<Self, Self::Error> {
+ Ok(Self {
+ public_token: item.request.public_token.clone(),
+ })
+ }
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub struct PlaidBankAccountCredentialsRequest {
+ access_token: String,
+ options: Option<BankAccountCredentialsOptions>,
+}
+
+#[derive(Debug, Deserialize, Eq, PartialEq)]
+
+pub struct PlaidBankAccountCredentialsResponse {
+ pub accounts: Vec<PlaidBankAccountCredentialsAccounts>,
+ pub numbers: PlaidBankAccountCredentialsNumbers,
+ // pub item: PlaidBankAccountCredentialsItem,
+ pub request_id: String,
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub struct BankAccountCredentialsOptions {
+ account_ids: Vec<String>,
+}
+
+#[derive(Debug, Deserialize, Eq, PartialEq)]
+
+pub struct PlaidBankAccountCredentialsAccounts {
+ pub account_id: String,
+ pub name: String,
+ pub subtype: Option<String>,
+}
+
+#[derive(Debug, Deserialize, Eq, PartialEq)]
+pub struct PlaidBankAccountCredentialsBalances {
+ pub available: Option<i32>,
+ pub current: Option<i32>,
+ pub limit: Option<i32>,
+ pub iso_currency_code: Option<String>,
+ pub unofficial_currency_code: Option<String>,
+ pub last_updated_datetime: Option<String>,
+}
+
+#[derive(Debug, Deserialize, Eq, PartialEq)]
+pub struct PlaidBankAccountCredentialsNumbers {
+ pub ach: Vec<PlaidBankAccountCredentialsACH>,
+ pub eft: Vec<PlaidBankAccountCredentialsEFT>,
+ pub international: Vec<PlaidBankAccountCredentialsInternational>,
+ pub bacs: Vec<PlaidBankAccountCredentialsBacs>,
+}
+
+#[derive(Debug, Deserialize, Eq, PartialEq)]
+pub struct PlaidBankAccountCredentialsItem {
+ pub item_id: String,
+ pub institution_id: Option<String>,
+ pub webhook: Option<String>,
+ pub error: Option<PlaidErrorResponse>,
+}
+#[derive(Debug, Deserialize, Eq, PartialEq)]
+pub struct PlaidBankAccountCredentialsACH {
+ pub account_id: String,
+ pub account: String,
+ pub routing: String,
+ pub wire_routing: Option<String>,
+}
+
+#[derive(Debug, Deserialize, Eq, PartialEq)]
+pub struct PlaidBankAccountCredentialsEFT {
+ pub account_id: String,
+ pub account: String,
+ pub institution: String,
+ pub branch: String,
+}
+
+#[derive(Debug, Deserialize, Eq, PartialEq)]
+pub struct PlaidBankAccountCredentialsInternational {
+ pub account_id: String,
+ pub iban: String,
+ pub bic: String,
+}
+
+#[derive(Debug, Deserialize, Eq, PartialEq)]
+pub struct PlaidBankAccountCredentialsBacs {
+ pub account_id: String,
+ pub account: String,
+ pub sort_code: String,
+}
+
+impl TryFrom<&types::BankDetailsRouterData> for PlaidBankAccountCredentialsRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::BankDetailsRouterData) -> Result<Self, Self::Error> {
+ Ok(Self {
+ access_token: item.request.access_token.clone(),
+ options: item.request.optional_ids.as_ref().map(|bank_account_ids| {
+ BankAccountCredentialsOptions {
+ account_ids: bank_account_ids.ids.clone(),
+ }
+ }),
+ })
+ }
+}
+
+impl<F, T>
+ TryFrom<
+ types::ResponseRouterData<
+ F,
+ PlaidBankAccountCredentialsResponse,
+ T,
+ types::BankAccountCredentialsResponse,
+ >,
+ > for types::PaymentAuthRouterData<F, T, types::BankAccountCredentialsResponse>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<
+ F,
+ PlaidBankAccountCredentialsResponse,
+ T,
+ types::BankAccountCredentialsResponse,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let (account_numbers, accounts_info) = (item.response.numbers, item.response.accounts);
+ let mut bank_account_vec = Vec::new();
+ let mut id_to_suptype = HashMap::new();
+
+ accounts_info.into_iter().for_each(|acc| {
+ id_to_suptype.insert(acc.account_id, (acc.subtype, acc.name));
+ });
+
+ account_numbers.ach.into_iter().for_each(|ach| {
+ let (acc_type, acc_name) =
+ if let Some((_type, name)) = id_to_suptype.get(&ach.account_id) {
+ (_type.to_owned(), Some(name.clone()))
+ } else {
+ (None, None)
+ };
+
+ let bank_details_new = types::BankAccountDetails {
+ account_name: acc_name,
+ account_number: ach.account,
+ routing_number: ach.routing,
+ payment_method_type: PaymentMethodType::Ach,
+ account_id: ach.account_id,
+ account_type: acc_type,
+ };
+
+ bank_account_vec.push(bank_details_new);
+ });
+
+ Ok(Self {
+ response: Ok(types::BankAccountCredentialsResponse {
+ credentials: bank_account_vec,
+ }),
+ ..item.data
+ })
+ }
+}
+pub struct PlaidAuthType {
+ pub client_id: Secret<String>,
+ pub secret: Secret<String>,
+}
+
+impl TryFrom<&types::ConnectorAuthType> for PlaidAuthType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ match auth_type {
+ types::ConnectorAuthType::BodyKey { client_id, secret } => Ok(Self {
+ client_id: client_id.to_owned(),
+ secret: secret.to_owned(),
+ }),
+ _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
+ }
+ }
+}
+
+#[derive(Debug, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub struct PlaidErrorResponse {
+ pub display_message: Option<String>,
+ pub error_code: Option<String>,
+ pub error_message: String,
+ pub error_type: Option<String>,
+}
diff --git a/crates/pm_auth/src/consts.rs b/crates/pm_auth/src/consts.rs
new file mode 100644
index 00000000000..dac3485ec8f
--- /dev/null
+++ b/crates/pm_auth/src/consts.rs
@@ -0,0 +1,5 @@
+pub const REQUEST_TIME_OUT: u64 = 30; // will timeout after the mentioned limit
+pub const REQUEST_TIMEOUT_ERROR_CODE: &str = "TIMEOUT"; // timeout error code
+pub const REQUEST_TIMEOUT_ERROR_MESSAGE: &str = "Connector did not respond in specified time"; // error message for timed out request
+pub const NO_ERROR_CODE: &str = "No error code";
+pub const NO_ERROR_MESSAGE: &str = "No error message";
diff --git a/crates/pm_auth/src/core.rs b/crates/pm_auth/src/core.rs
new file mode 100644
index 00000000000..629e98fbf87
--- /dev/null
+++ b/crates/pm_auth/src/core.rs
@@ -0,0 +1 @@
+pub mod errors;
diff --git a/crates/pm_auth/src/core/errors.rs b/crates/pm_auth/src/core/errors.rs
new file mode 100644
index 00000000000..31b178a6276
--- /dev/null
+++ b/crates/pm_auth/src/core/errors.rs
@@ -0,0 +1,27 @@
+#[derive(Debug, thiserror::Error, PartialEq)]
+pub enum ConnectorError {
+ #[error("Failed to obtain authentication type")]
+ FailedToObtainAuthType,
+ #[error("Missing required field: {field_name}")]
+ MissingRequiredField { field_name: &'static str },
+ #[error("Failed to execute a processing step: {0:?}")]
+ ProcessingStepFailed(Option<bytes::Bytes>),
+ #[error("Failed to deserialize connector response")]
+ ResponseDeserializationFailed,
+ #[error("Failed to encode connector request")]
+ RequestEncodingFailed,
+}
+
+pub type CustomResult<T, E> = error_stack::Result<T, E>;
+
+#[derive(Debug, thiserror::Error)]
+pub enum ParsingError {
+ #[error("Failed to parse enum: {0}")]
+ EnumParseFailure(&'static str),
+ #[error("Failed to parse struct: {0}")]
+ StructParseFailure(&'static str),
+ #[error("Failed to serialize to {0} format")]
+ EncodeError(&'static str),
+ #[error("Unknown error while parsing")]
+ UnknownError,
+}
diff --git a/crates/pm_auth/src/lib.rs b/crates/pm_auth/src/lib.rs
new file mode 100644
index 00000000000..60d0e06a1e0
--- /dev/null
+++ b/crates/pm_auth/src/lib.rs
@@ -0,0 +1,4 @@
+pub mod connector;
+pub mod consts;
+pub mod core;
+pub mod types;
diff --git a/crates/pm_auth/src/types.rs b/crates/pm_auth/src/types.rs
new file mode 100644
index 00000000000..6f5875247f1
--- /dev/null
+++ b/crates/pm_auth/src/types.rs
@@ -0,0 +1,152 @@
+pub mod api;
+
+use std::marker::PhantomData;
+
+use api::auth_service::{BankAccountCredentials, ExchangeToken, LinkToken};
+use common_enums::PaymentMethodType;
+use masking::Secret;
+#[derive(Debug, Clone)]
+pub struct PaymentAuthRouterData<F, Request, Response> {
+ pub flow: PhantomData<F>,
+ pub merchant_id: Option<String>,
+ pub connector: Option<String>,
+ pub request: Request,
+ pub response: Result<Response, ErrorResponse>,
+ pub connector_auth_type: ConnectorAuthType,
+ pub connector_http_status_code: Option<u16>,
+}
+
+#[derive(Debug, Clone)]
+pub struct LinkTokenRequest {
+ pub client_name: String,
+ pub country_codes: Option<Vec<String>>,
+ pub language: Option<String>,
+ pub user_info: Option<String>,
+}
+
+#[derive(Debug, Clone)]
+pub struct LinkTokenResponse {
+ pub link_token: String,
+}
+
+pub type LinkTokenRouterData =
+ PaymentAuthRouterData<LinkToken, LinkTokenRequest, LinkTokenResponse>;
+
+#[derive(Debug, Clone)]
+pub struct ExchangeTokenRequest {
+ pub public_token: String,
+}
+
+#[derive(Debug, Clone)]
+pub struct ExchangeTokenResponse {
+ pub access_token: String,
+}
+
+impl From<ExchangeTokenResponse> for api_models::pm_auth::ExchangeTokenCreateResponse {
+ fn from(value: ExchangeTokenResponse) -> Self {
+ Self {
+ access_token: value.access_token,
+ }
+ }
+}
+
+pub type ExchangeTokenRouterData =
+ PaymentAuthRouterData<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>;
+
+#[derive(Debug, Clone)]
+pub struct BankAccountCredentialsRequest {
+ pub access_token: String,
+ pub optional_ids: Option<BankAccountOptionalIDs>,
+}
+
+#[derive(Debug, Clone)]
+pub struct BankAccountOptionalIDs {
+ pub ids: Vec<String>,
+}
+
+#[derive(Debug, Clone)]
+pub struct BankAccountCredentialsResponse {
+ pub credentials: Vec<BankAccountDetails>,
+}
+
+#[derive(Debug, Clone)]
+pub struct BankAccountDetails {
+ pub account_name: Option<String>,
+ pub account_number: String,
+ pub routing_number: String,
+ pub payment_method_type: PaymentMethodType,
+ pub account_id: String,
+ pub account_type: Option<String>,
+}
+
+pub type BankDetailsRouterData = PaymentAuthRouterData<
+ BankAccountCredentials,
+ BankAccountCredentialsRequest,
+ BankAccountCredentialsResponse,
+>;
+
+pub type PaymentAuthLinkTokenType =
+ dyn self::api::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse>;
+
+pub type PaymentAuthExchangeTokenType =
+ dyn self::api::ConnectorIntegration<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>;
+
+pub type PaymentAuthBankAccountDetailsType = dyn self::api::ConnectorIntegration<
+ BankAccountCredentials,
+ BankAccountCredentialsRequest,
+ BankAccountCredentialsResponse,
+>;
+
+#[derive(Clone, Debug, strum::EnumString, strum::Display)]
+#[strum(serialize_all = "snake_case")]
+pub enum PaymentMethodAuthConnectors {
+ Plaid,
+}
+
+#[derive(Debug, Clone)]
+pub struct ResponseRouterData<Flow, R, Request, Response> {
+ pub response: R,
+ pub data: PaymentAuthRouterData<Flow, Request, Response>,
+ pub http_code: u16,
+}
+
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct ErrorResponse {
+ pub code: String,
+ pub message: String,
+ pub reason: Option<String>,
+ pub status_code: u16,
+}
+
+impl ErrorResponse {
+ fn get_not_implemented() -> Self {
+ Self {
+ code: "IR_00".to_string(),
+ message: "This API is under development and will be made available soon.".to_string(),
+ reason: None,
+ status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
+ }
+ }
+}
+
+#[derive(Default, Debug, Clone, serde::Deserialize)]
+pub enum ConnectorAuthType {
+ BodyKey {
+ client_id: Secret<String>,
+ secret: Secret<String>,
+ },
+ #[default]
+ NoKey,
+}
+
+#[derive(Clone, Debug)]
+pub struct Response {
+ pub headers: Option<http::HeaderMap>,
+ pub response: bytes::Bytes,
+ pub status_code: u16,
+}
+
+#[derive(serde::Deserialize, Clone)]
+pub struct AuthServiceQueryParam {
+ pub client_secret: Option<String>,
+}
diff --git a/crates/pm_auth/src/types/api.rs b/crates/pm_auth/src/types/api.rs
new file mode 100644
index 00000000000..2416d0fee1d
--- /dev/null
+++ b/crates/pm_auth/src/types/api.rs
@@ -0,0 +1,167 @@
+pub mod auth_service;
+
+use std::fmt::Debug;
+
+use common_utils::{
+ errors::CustomResult,
+ request::{Request, RequestBody},
+};
+use masking::Maskable;
+
+use crate::{
+ core::errors::ConnectorError,
+ types::{self as auth_types, api::auth_service::AuthService},
+};
+
+#[async_trait::async_trait]
+pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Resp> + Sync {
+ fn get_headers(
+ &self,
+ _req: &super::PaymentAuthRouterData<T, Req, Resp>,
+ _connectors: &auth_types::PaymentMethodAuthConnectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
+ Ok(vec![])
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ mime::APPLICATION_JSON.essence_str()
+ }
+
+ fn get_url(
+ &self,
+ _req: &super::PaymentAuthRouterData<T, Req, Resp>,
+ _connectors: &auth_types::PaymentMethodAuthConnectors,
+ ) -> CustomResult<String, ConnectorError> {
+ Ok(String::new())
+ }
+
+ fn get_request_body(
+ &self,
+ _req: &super::PaymentAuthRouterData<T, Req, Resp>,
+ ) -> CustomResult<Option<RequestBody>, ConnectorError> {
+ Ok(None)
+ }
+
+ fn build_request(
+ &self,
+ _req: &super::PaymentAuthRouterData<T, Req, Resp>,
+ _connectors: &auth_types::PaymentMethodAuthConnectors,
+ ) -> CustomResult<Option<Request>, ConnectorError> {
+ Ok(None)
+ }
+
+ fn handle_response(
+ &self,
+ data: &super::PaymentAuthRouterData<T, Req, Resp>,
+ _res: auth_types::Response,
+ ) -> CustomResult<super::PaymentAuthRouterData<T, Req, Resp>, ConnectorError>
+ where
+ T: Clone,
+ Req: Clone,
+ Resp: Clone,
+ {
+ Ok(data.clone())
+ }
+
+ fn get_error_response(
+ &self,
+ _res: auth_types::Response,
+ ) -> CustomResult<auth_types::ErrorResponse, ConnectorError> {
+ Ok(auth_types::ErrorResponse::get_not_implemented())
+ }
+
+ fn get_5xx_error_response(
+ &self,
+ res: auth_types::Response,
+ ) -> CustomResult<auth_types::ErrorResponse, ConnectorError> {
+ let error_message = match res.status_code {
+ 500 => "internal_server_error",
+ 501 => "not_implemented",
+ 502 => "bad_gateway",
+ 503 => "service_unavailable",
+ 504 => "gateway_timeout",
+ 505 => "http_version_not_supported",
+ 506 => "variant_also_negotiates",
+ 507 => "insufficient_storage",
+ 508 => "loop_detected",
+ 510 => "not_extended",
+ 511 => "network_authentication_required",
+ _ => "unknown_error",
+ };
+ Ok(auth_types::ErrorResponse {
+ code: res.status_code.to_string(),
+ message: error_message.to_string(),
+ reason: String::from_utf8(res.response.to_vec()).ok(),
+ status_code: res.status_code,
+ })
+ }
+}
+
+pub trait ConnectorCommonExt<Flow, Req, Resp>:
+ ConnectorCommon + ConnectorIntegration<Flow, Req, Resp>
+{
+ fn build_headers(
+ &self,
+ _req: &auth_types::PaymentAuthRouterData<Flow, Req, Resp>,
+ _connectors: &auth_types::PaymentMethodAuthConnectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
+ Ok(Vec::new())
+ }
+}
+
+pub type BoxedConnectorIntegration<'a, T, Req, Resp> =
+ Box<&'a (dyn ConnectorIntegration<T, Req, Resp> + Send + Sync)>;
+
+pub trait ConnectorIntegrationAny<T, Req, Resp>: Send + Sync + 'static {
+ fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp>;
+}
+
+impl<S, T, Req, Resp> ConnectorIntegrationAny<T, Req, Resp> for S
+where
+ S: ConnectorIntegration<T, Req, Resp>,
+{
+ fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp> {
+ Box::new(self)
+ }
+}
+
+pub trait AuthServiceConnector: AuthService + Send + Debug {}
+
+impl<T: Send + Debug + AuthService> AuthServiceConnector for T {}
+
+pub type BoxedPaymentAuthConnector = Box<&'static (dyn AuthServiceConnector + Sync)>;
+
+#[derive(Clone, Debug)]
+pub struct PaymentAuthConnectorData {
+ pub connector: BoxedPaymentAuthConnector,
+ pub connector_name: super::PaymentMethodAuthConnectors,
+}
+
+pub trait ConnectorCommon {
+ fn id(&self) -> &'static str;
+
+ fn get_auth_header(
+ &self,
+ _auth_type: &auth_types::ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
+ Ok(Vec::new())
+ }
+
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+
+ fn base_url<'a>(&self, connectors: &'a auth_types::PaymentMethodAuthConnectors) -> &'a str;
+
+ fn build_error_response(
+ &self,
+ res: auth_types::Response,
+ ) -> CustomResult<auth_types::ErrorResponse, ConnectorError> {
+ Ok(auth_types::ErrorResponse {
+ status_code: res.status_code,
+ code: crate::consts::NO_ERROR_CODE.to_string(),
+ message: crate::consts::NO_ERROR_MESSAGE.to_string(),
+ reason: None,
+ })
+ }
+}
diff --git a/crates/pm_auth/src/types/api/auth_service.rs b/crates/pm_auth/src/types/api/auth_service.rs
new file mode 100644
index 00000000000..35d44970d51
--- /dev/null
+++ b/crates/pm_auth/src/types/api/auth_service.rs
@@ -0,0 +1,40 @@
+use crate::types::{
+ BankAccountCredentialsRequest, BankAccountCredentialsResponse, ExchangeTokenRequest,
+ ExchangeTokenResponse, LinkTokenRequest, LinkTokenResponse,
+};
+
+pub trait AuthService:
+ super::ConnectorCommon
+ + AuthServiceLinkToken
+ + AuthServiceExchangeToken
+ + AuthServiceBankAccountCredentials
+{
+}
+
+#[derive(Debug, Clone)]
+pub struct LinkToken;
+
+pub trait AuthServiceLinkToken:
+ super::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse>
+{
+}
+
+#[derive(Debug, Clone)]
+pub struct ExchangeToken;
+
+pub trait AuthServiceExchangeToken:
+ super::ConnectorIntegration<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>
+{
+}
+
+#[derive(Debug, Clone)]
+pub struct BankAccountCredentials;
+
+pub trait AuthServiceBankAccountCredentials:
+ super::ConnectorIntegration<
+ BankAccountCredentials,
+ BankAccountCredentialsRequest,
+ BankAccountCredentialsResponse,
+>
+{
+}
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 791f617b30d..e498658e457 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -111,6 +111,7 @@ currency_conversion = { version = "0.1.0", path = "../currency_conversion" }
data_models = { version = "0.1.0", path = "../data_models", default-features = false }
diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] }
euclid = { version = "0.1.0", path = "../euclid", features = ["valued_jit"] }
+pm_auth = { version = "0.1.0", path = "../pm_auth", package = "pm_auth" }
external_services = { version = "0.1.0", path = "../external_services" }
kgraph_utils = { version = "0.1.0", path = "../kgraph_utils" }
masking = { version = "0.1.0", path = "../masking" }
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 7b469a2165f..1c885e90cc7 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -100,6 +100,7 @@ pub struct Settings {
pub required_fields: RequiredFields,
pub delayed_session_response: DelayedSessionConfig,
pub webhook_source_verification_call: WebhookSourceVerificationCall,
+ pub payment_method_auth: PaymentMethodAuth,
pub connector_request_reference_id_config: ConnectorRequestReferenceIdConfig,
#[cfg(feature = "payouts")]
pub payouts: Payouts,
@@ -154,6 +155,12 @@ pub struct ForexApi {
pub redis_lock_timeout: u64,
}
+#[derive(Debug, Deserialize, Clone, Default)]
+pub struct PaymentMethodAuth {
+ pub redis_expiry: i64,
+ pub pm_auth_key: String,
+}
+
#[derive(Debug, Deserialize, Clone, Default)]
pub struct DefaultExchangeRates {
pub base_currency: String,
diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs
index be83de84916..0bd197ee22e 100644
--- a/crates/router/src/core.rs
+++ b/crates/router/src/core.rs
@@ -24,6 +24,7 @@ pub mod payment_methods;
pub mod payments;
#[cfg(feature = "payouts")]
pub mod payouts;
+pub mod pm_auth;
pub mod refunds;
pub mod routing;
pub mod surcharge_decision_config;
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 5ab543d382f..113bc7d677d 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -10,9 +10,10 @@ use common_utils::{
ext_traits::{AsyncExt, ConfigExt, Encode, ValueExt},
pii,
};
-use error_stack::{report, FutureExt, ResultExt};
+use error_stack::{report, FutureExt, IntoReport, ResultExt};
use futures::future::try_join_all;
use masking::{PeekInterface, Secret};
+use pm_auth::connector::plaid::transformers::PlaidAuthType;
use uuid::Uuid;
use crate::{
@@ -762,7 +763,7 @@ pub async fn create_payment_connector(
)
.await?;
- let routable_connector =
+ let mut routable_connector =
api_enums::RoutableConnectors::from_str(&req.connector_name.to_string()).ok();
let business_profile = state
@@ -773,6 +774,30 @@ pub async fn create_payment_connector(
id: profile_id.to_owned(),
})?;
+ let pm_auth_connector =
+ api_enums::convert_pm_auth_connector(req.connector_name.to_string().as_str());
+
+ let is_unroutable_connector = if pm_auth_connector.is_some() {
+ if req.connector_type != api_enums::ConnectorType::PaymentMethodAuth {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid connector type given".to_string(),
+ })
+ .into_report();
+ }
+ true
+ } else {
+ let routable_connector_option = req
+ .connector_name
+ .to_string()
+ .parse()
+ .into_report()
+ .change_context(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid connector name given".to_string(),
+ })?;
+ routable_connector = Some(routable_connector_option);
+ false
+ };
+
// If connector label is not passed in the request, generate one
let connector_label = req
.connector_label
@@ -877,6 +902,20 @@ pub async fn create_payment_connector(
api_enums::ConnectorStatus::Active,
)?;
+ if req.connector_type != api_enums::ConnectorType::PaymentMethodAuth {
+ if let Some(val) = req.pm_auth_config.clone() {
+ validate_pm_auth(
+ val,
+ &*state.clone().store,
+ merchant_id.clone().as_str(),
+ &key_store,
+ merchant_account,
+ &Some(profile_id.clone()),
+ )
+ .await?;
+ }
+ }
+
let merchant_connector_account = domain::MerchantConnectorAccount {
merchant_id: merchant_id.to_string(),
connector_type: req.connector_type,
@@ -948,7 +987,7 @@ pub async fn create_payment_connector(
#[cfg(feature = "connector_choice_mca_id")]
merchant_connector_id: Some(mca.merchant_connector_id.clone()),
#[cfg(not(feature = "connector_choice_mca_id"))]
- sub_label: req.business_sub_label,
+ sub_label: req.business_sub_label.clone(),
};
if !default_routing_config.contains(&choice) {
@@ -956,7 +995,7 @@ pub async fn create_payment_connector(
routing_helpers::update_merchant_default_config(
&*state.store,
merchant_id,
- default_routing_config,
+ default_routing_config.clone(),
)
.await?;
}
@@ -965,7 +1004,7 @@ pub async fn create_payment_connector(
routing_helpers::update_merchant_default_config(
&*state.store,
&profile_id.clone(),
- default_routing_config_for_profile,
+ default_routing_config_for_profile.clone(),
)
.await?;
}
@@ -980,10 +1019,92 @@ pub async fn create_payment_connector(
],
);
+ if !is_unroutable_connector {
+ if let Some(routable_connector_val) = routable_connector {
+ let choice = routing_types::RoutableConnectorChoice {
+ #[cfg(feature = "backwards_compatibility")]
+ choice_kind: routing_types::RoutableChoiceKind::FullStruct,
+ connector: routable_connector_val,
+ #[cfg(feature = "connector_choice_mca_id")]
+ merchant_connector_id: Some(mca.merchant_connector_id.clone()),
+ #[cfg(not(feature = "connector_choice_mca_id"))]
+ sub_label: req.business_sub_label.clone(),
+ };
+
+ if !default_routing_config.contains(&choice) {
+ default_routing_config.push(choice.clone());
+ routing_helpers::update_merchant_default_config(
+ &*state.clone().store,
+ merchant_id,
+ default_routing_config,
+ )
+ .await?;
+ }
+
+ if !default_routing_config_for_profile.contains(&choice) {
+ default_routing_config_for_profile.push(choice);
+ routing_helpers::update_merchant_default_config(
+ &*state.store,
+ &profile_id,
+ default_routing_config_for_profile,
+ )
+ .await?;
+ }
+ }
+ };
+
let mca_response = mca.try_into()?;
Ok(service_api::ApplicationResponse::Json(mca_response))
}
+async fn validate_pm_auth(
+ val: serde_json::Value,
+ db: &dyn StorageInterface,
+ merchant_id: &str,
+ key_store: &domain::MerchantKeyStore,
+ merchant_account: domain::MerchantAccount,
+ profile_id: &Option<String>,
+) -> RouterResponse<()> {
+ let config = serde_json::from_value::<api_models::pm_auth::PaymentMethodAuthConfig>(val)
+ .into_report()
+ .change_context(errors::ApiErrorResponse::InvalidRequestData {
+ message: "invalid data received for payment method auth config".to_string(),
+ })
+ .attach_printable("Failed to deserialize Payment Method Auth config")?;
+
+ let all_mcas = db
+ .find_merchant_connector_account_by_merchant_id_and_disabled_list(
+ merchant_id,
+ true,
+ key_store,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ id: merchant_account.merchant_id.clone(),
+ })?;
+
+ for conn_choice in config.enabled_payment_methods {
+ let pm_auth_mca = all_mcas
+ .clone()
+ .into_iter()
+ .find(|mca| mca.merchant_connector_id == conn_choice.mca_id)
+ .ok_or(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "payment method auth connector account not found".to_string(),
+ })
+ .into_report()?;
+
+ if &pm_auth_mca.profile_id != profile_id {
+ return Err(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "payment method auth profile_id differs from connector profile_id"
+ .to_string(),
+ })
+ .into_report();
+ }
+ }
+
+ Ok(services::ApplicationResponse::StatusOk)
+}
+
pub async fn retrieve_payment_connector(
state: AppState,
merchant_id: String,
@@ -1066,7 +1187,7 @@ pub async fn update_payment_connector(
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
- let _merchant_account = db
+ let merchant_account = db
.find_merchant_account_by_merchant_id(merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
@@ -1106,6 +1227,20 @@ pub async fn update_payment_connector(
let (connector_status, disabled) =
validate_status_and_disabled(req.status, req.disabled, auth, mca.status)?;
+ if req.connector_type != api_enums::ConnectorType::PaymentMethodAuth {
+ if let Some(val) = req.pm_auth_config.clone() {
+ validate_pm_auth(
+ val,
+ db,
+ merchant_id,
+ &key_store,
+ merchant_account,
+ &mca.profile_id,
+ )
+ .await?;
+ }
+ }
+
let payment_connector = storage::MerchantConnectorAccountUpdate::Update {
merchant_id: None,
connector_type: Some(req.connector_type),
@@ -1720,8 +1855,10 @@ pub(crate) fn validate_auth_and_metadata_type(
signifyd::transformers::SignifydAuthType::try_from(val)?;
Ok(())
}
- api_enums::Connector::Plaid => Err(report!(errors::ConnectorError::InvalidConnectorName)
- .attach_printable(format!("invalid connector name: {connector_name}"))),
+ api_enums::Connector::Plaid => {
+ PlaidAuthType::foreign_try_from(val)?;
+ Ok(())
+ }
}
}
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index a2dbfb1480c..14a39f1d955 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -11,12 +11,12 @@ pub use api_models::{
pub use common_utils::request::RequestBody;
use data_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
use diesel_models::enums;
-use error_stack::IntoReport;
use crate::{
core::{
- errors::{self, RouterResult},
+ errors::RouterResult,
payments::helpers,
+ pm_auth::{self as core_pm_auth},
},
routes::AppState,
types::{
@@ -172,11 +172,14 @@ impl PaymentMethodRetrieve for Oss {
.map(|card| Some((card, enums::PaymentMethod::Card)))
}
- storage::PaymentTokenData::AuthBankDebit(_) => {
- Err(errors::ApiErrorResponse::NotImplemented {
- message: errors::NotImplementedMessage::Default,
- })
- .into_report()
+ storage::PaymentTokenData::AuthBankDebit(auth_token) => {
+ core_pm_auth::retrieve_payment_method_from_auth_service(
+ state,
+ merchant_key_store,
+ auth_token,
+ payment_intent,
+ )
+ .await
}
}
}
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index bbcfe45a1d0..84aef952a53 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -13,6 +13,7 @@ use api_models::{
ResponsePaymentMethodsEnabled,
},
payments::BankCodeResponse,
+ pm_auth::PaymentMethodAuthConfig,
surcharge_decision_configs as api_surcharge_decision_configs,
};
use common_utils::{
@@ -29,6 +30,8 @@ use super::surcharge_decision_configs::{
perform_surcharge_decision_management_for_payment_method_list,
perform_surcharge_decision_management_for_saved_cards,
};
+#[cfg(not(feature = "connector_choice_mca_id"))]
+use crate::core::utils::get_connector_label;
use crate::{
configs::settings,
core::{
@@ -1081,9 +1084,9 @@ pub async fn list_payment_methods(
logger::debug!(mca_before_filtering=?filtered_mcas);
let mut response: Vec<ResponsePaymentMethodIntermediate> = vec![];
- for mca in filtered_mcas {
- let payment_methods = match mca.payment_methods_enabled {
- Some(pm) => pm,
+ for mca in &filtered_mcas {
+ let payment_methods = match &mca.payment_methods_enabled {
+ Some(pm) => pm.clone(),
None => continue,
};
@@ -1094,13 +1097,15 @@ pub async fn list_payment_methods(
payment_intent.as_ref(),
payment_attempt.as_ref(),
billing_address.as_ref(),
- mca.connector_name,
+ mca.connector_name.clone(),
pm_config_mapping,
&state.conf.mandates.supported_payment_methods,
)
.await?;
}
+ let mut pmt_to_auth_connector = HashMap::new();
+
if let Some((payment_attempt, payment_intent)) =
payment_attempt.as_ref().zip(payment_intent.as_ref())
{
@@ -1204,6 +1209,84 @@ pub async fn list_payment_methods(
pre_routing_results.insert(pm_type, routable_choice);
}
+ let redis_conn = db
+ .get_redis_conn()
+ .map_err(|redis_error| logger::error!(?redis_error))
+ .ok();
+
+ let mut val = Vec::new();
+
+ for (payment_method_type, routable_connector_choice) in &pre_routing_results {
+ #[cfg(not(feature = "connector_choice_mca_id"))]
+ let connector_label = get_connector_label(
+ payment_intent.business_country,
+ payment_intent.business_label.as_ref(),
+ #[cfg(not(feature = "connector_choice_mca_id"))]
+ routable_connector_choice.sub_label.as_ref(),
+ #[cfg(feature = "connector_choice_mca_id")]
+ None,
+ routable_connector_choice.connector.to_string().as_str(),
+ );
+ #[cfg(not(feature = "connector_choice_mca_id"))]
+ let matched_mca = filtered_mcas
+ .iter()
+ .find(|m| connector_label == m.connector_label);
+
+ #[cfg(feature = "connector_choice_mca_id")]
+ let matched_mca = filtered_mcas.iter().find(|m| {
+ routable_connector_choice.merchant_connector_id.as_ref()
+ == Some(&m.merchant_connector_id)
+ });
+
+ if let Some(m) = matched_mca {
+ let pm_auth_config = m
+ .pm_auth_config
+ .as_ref()
+ .map(|config| {
+ serde_json::from_value::<PaymentMethodAuthConfig>(config.clone())
+ .into_report()
+ .change_context(errors::StorageError::DeserializationFailed)
+ .attach_printable("Failed to deserialize Payment Method Auth config")
+ })
+ .transpose()
+ .unwrap_or_else(|err| {
+ logger::error!(error=?err);
+ None
+ });
+
+ let matched_config = match pm_auth_config {
+ Some(config) => {
+ let internal_config = config
+ .enabled_payment_methods
+ .iter()
+ .find(|config| config.payment_method_type == *payment_method_type)
+ .cloned();
+
+ internal_config
+ }
+ None => None,
+ };
+
+ if let Some(config) = matched_config {
+ pmt_to_auth_connector
+ .insert(*payment_method_type, config.connector_name.clone());
+ val.push(config);
+ }
+ }
+ }
+
+ let pm_auth_key = format!("pm_auth_{}", payment_intent.payment_id);
+ let redis_expiry = state.conf.payment_method_auth.redis_expiry;
+
+ if let Some(rc) = redis_conn {
+ rc.serialize_and_set_key_with_expiry(pm_auth_key.as_str(), val, redis_expiry)
+ .await
+ .attach_printable("Failed to store pm auth data in redis")
+ .unwrap_or_else(|err| {
+ logger::error!(error=?err);
+ })
+ };
+
routing_info.pre_routing_results = Some(pre_routing_results);
let encoded = utils::Encode::<storage::PaymentRoutingInfo>::encode_to_value(&routing_info)
@@ -1461,7 +1544,9 @@ pub async fn list_payment_methods(
.and_then(|inner_hm| inner_hm.get(payment_method_types_hm.0))
.cloned(),
surcharge_details: None,
- pm_auth_connector: None,
+ pm_auth_connector: pmt_to_auth_connector
+ .get(payment_method_types_hm.0)
+ .cloned(),
})
}
@@ -1496,7 +1581,9 @@ pub async fn list_payment_methods(
.and_then(|inner_hm| inner_hm.get(payment_method_types_hm.0))
.cloned(),
surcharge_details: None,
- pm_auth_connector: None,
+ pm_auth_connector: pmt_to_auth_connector
+ .get(payment_method_types_hm.0)
+ .cloned(),
})
}
@@ -1526,7 +1613,7 @@ pub async fn list_payment_methods(
.and_then(|inner_hm| inner_hm.get(key.0))
.cloned(),
surcharge_details: None,
- pm_auth_connector: None,
+ pm_auth_connector: pmt_to_auth_connector.get(&payment_method_type).cloned(),
}
})
}
@@ -1559,7 +1646,7 @@ pub async fn list_payment_methods(
.and_then(|inner_hm| inner_hm.get(key.0))
.cloned(),
surcharge_details: None,
- pm_auth_connector: None,
+ pm_auth_connector: pmt_to_auth_connector.get(&payment_method_type).cloned(),
}
})
}
@@ -1592,7 +1679,7 @@ pub async fn list_payment_methods(
.and_then(|inner_hm| inner_hm.get(key.0))
.cloned(),
surcharge_details: None,
- pm_auth_connector: None,
+ pm_auth_connector: pmt_to_auth_connector.get(&payment_method_type).cloned(),
}
})
}
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
new file mode 100644
index 00000000000..821f049d8cf
--- /dev/null
+++ b/crates/router/src/core/pm_auth.rs
@@ -0,0 +1,729 @@
+use std::{collections::HashMap, str::FromStr};
+
+use api_models::{
+ enums,
+ payment_methods::{self, BankAccountAccessCreds},
+ payments::{AddressDetails, BankDebitBilling, BankDebitData, PaymentMethodData},
+};
+use hex;
+pub mod helpers;
+pub mod transformers;
+
+use common_utils::{
+ consts,
+ crypto::{HmacSha256, SignMessage},
+ ext_traits::AsyncExt,
+ generate_id,
+};
+use data_models::payments::PaymentIntent;
+use error_stack::{IntoReport, ResultExt};
+#[cfg(feature = "kms")]
+pub use external_services::kms;
+use helpers::PaymentAuthConnectorDataExt;
+use masking::{ExposeInterface, PeekInterface};
+use pm_auth::{
+ connector::plaid::transformers::PlaidAuthType,
+ types::{
+ self as pm_auth_types,
+ api::{
+ auth_service::{BankAccountCredentials, ExchangeToken, LinkToken},
+ BoxedConnectorIntegration, PaymentAuthConnectorData,
+ },
+ },
+};
+
+use crate::{
+ core::{
+ errors::{self, ApiErrorResponse, RouterResponse, RouterResult, StorageErrorExt},
+ payment_methods::cards,
+ payments::helpers as oss_helpers,
+ pm_auth::helpers::{self as pm_auth_helpers},
+ },
+ db::StorageInterface,
+ logger,
+ routes::AppState,
+ services::{
+ pm_auth::{self as pm_auth_services},
+ ApplicationResponse,
+ },
+ types::{
+ self,
+ domain::{self, types::decrypt},
+ storage,
+ transformers::ForeignTryFrom,
+ },
+};
+
+pub async fn create_link_token(
+ state: AppState,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ payload: api_models::pm_auth::LinkTokenCreateRequest,
+) -> RouterResponse<api_models::pm_auth::LinkTokenCreateResponse> {
+ let db = &*state.store;
+
+ let redis_conn = db
+ .get_redis_conn()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get redis connection")?;
+
+ let pm_auth_key = format!("pm_auth_{}", payload.payment_id);
+
+ let pm_auth_configs = redis_conn
+ .get_and_deserialize_key::<Vec<api_models::pm_auth::PaymentMethodAuthConnectorChoice>>(
+ pm_auth_key.as_str(),
+ "Vec<PaymentMethodAuthConnectorChoice>",
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get payment method auth choices from redis")?;
+
+ let selected_config = pm_auth_configs
+ .into_iter()
+ .find(|config| {
+ config.payment_method == payload.payment_method
+ && config.payment_method_type == payload.payment_method_type
+ })
+ .ok_or(ApiErrorResponse::GenericNotFoundError {
+ message: "payment method auth connector name not found".to_string(),
+ })
+ .into_report()?;
+
+ let connector_name = selected_config.connector_name.as_str();
+
+ let connector = PaymentAuthConnectorData::get_connector_by_name(connector_name)?;
+ let connector_integration: BoxedConnectorIntegration<
+ '_,
+ LinkToken,
+ pm_auth_types::LinkTokenRequest,
+ pm_auth_types::LinkTokenResponse,
+ > = connector.connector.get_connector_integration();
+
+ let payment_intent = oss_helpers::verify_payment_intent_time_and_client_secret(
+ &*state.store,
+ &merchant_account,
+ payload.client_secret,
+ )
+ .await?;
+
+ let billing_country = payment_intent
+ .as_ref()
+ .async_map(|pi| async {
+ oss_helpers::get_address_by_id(
+ &*state.store,
+ pi.billing_address_id.clone(),
+ &key_store,
+ pi.payment_id.clone(),
+ merchant_account.merchant_id.clone(),
+ merchant_account.storage_scheme,
+ )
+ .await
+ })
+ .await
+ .transpose()?
+ .flatten()
+ .and_then(|address| address.country)
+ .map(|country| country.to_string());
+
+ let merchant_connector_account = state
+ .store
+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(
+ merchant_account.merchant_id.as_str(),
+ &selected_config.mca_id,
+ &key_store,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ id: merchant_account.merchant_id.clone(),
+ })?;
+
+ let auth_type = helpers::get_connector_auth_type(merchant_connector_account)?;
+
+ let router_data = pm_auth_types::LinkTokenRouterData {
+ flow: std::marker::PhantomData,
+ merchant_id: Some(merchant_account.merchant_id),
+ connector: Some(connector_name.to_string()),
+ request: pm_auth_types::LinkTokenRequest {
+ client_name: "HyperSwitch".to_string(),
+ country_codes: Some(vec![billing_country.ok_or(
+ errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "billing_country",
+ },
+ )?]),
+ language: payload.language,
+ user_info: payment_intent.and_then(|pi| pi.customer_id),
+ },
+ response: Ok(pm_auth_types::LinkTokenResponse {
+ link_token: "".to_string(),
+ }),
+ connector_http_status_code: None,
+ connector_auth_type: auth_type,
+ };
+
+ let connector_resp = pm_auth_services::execute_connector_processing_step(
+ state.as_ref(),
+ connector_integration,
+ &router_data,
+ &connector.connector_name,
+ )
+ .await
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while calling link token creation connector api")?;
+
+ let link_token_resp =
+ connector_resp
+ .response
+ .map_err(|err| ApiErrorResponse::ExternalConnectorError {
+ code: err.code,
+ message: err.message,
+ connector: connector.connector_name.to_string(),
+ status_code: err.status_code,
+ reason: err.reason,
+ })?;
+
+ let response = api_models::pm_auth::LinkTokenCreateResponse {
+ link_token: link_token_resp.link_token,
+ connector: connector.connector_name.to_string(),
+ };
+
+ Ok(ApplicationResponse::Json(response))
+}
+
+impl ForeignTryFrom<&types::ConnectorAuthType> for PlaidAuthType {
+ type Error = errors::ConnectorError;
+
+ fn foreign_try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ match auth_type {
+ types::ConnectorAuthType::BodyKey { api_key, key1 } => {
+ Ok::<Self, errors::ConnectorError>(Self {
+ client_id: api_key.to_owned(),
+ secret: key1.to_owned(),
+ })
+ }
+ _ => Err(errors::ConnectorError::FailedToObtainAuthType),
+ }
+ }
+}
+
+pub async fn exchange_token_core(
+ state: AppState,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ payload: api_models::pm_auth::ExchangeTokenCreateRequest,
+) -> RouterResponse<()> {
+ let db = &*state.store;
+
+ let config = get_selected_config_from_redis(db, &payload).await?;
+
+ let connector_name = config.connector_name.as_str();
+
+ let connector =
+ pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name(connector_name)?;
+
+ let merchant_connector_account = state
+ .store
+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(
+ merchant_account.merchant_id.as_str(),
+ &config.mca_id,
+ &key_store,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ id: merchant_account.merchant_id.clone(),
+ })?;
+
+ let auth_type = helpers::get_connector_auth_type(merchant_connector_account.clone())?;
+
+ let access_token = get_access_token_from_exchange_api(
+ &connector,
+ connector_name,
+ &payload,
+ &auth_type,
+ &state,
+ )
+ .await?;
+
+ let bank_account_details_resp = get_bank_account_creds(
+ connector,
+ &merchant_account,
+ connector_name,
+ &access_token,
+ auth_type,
+ &state,
+ None,
+ )
+ .await?;
+
+ Box::pin(store_bank_details_in_payment_methods(
+ key_store,
+ payload,
+ merchant_account,
+ state,
+ bank_account_details_resp,
+ (connector_name, access_token),
+ merchant_connector_account.merchant_connector_id,
+ ))
+ .await?;
+
+ Ok(ApplicationResponse::StatusOk)
+}
+
+async fn store_bank_details_in_payment_methods(
+ key_store: domain::MerchantKeyStore,
+ payload: api_models::pm_auth::ExchangeTokenCreateRequest,
+ merchant_account: domain::MerchantAccount,
+ state: AppState,
+ bank_account_details_resp: pm_auth_types::BankAccountCredentialsResponse,
+ connector_details: (&str, String),
+ mca_id: String,
+) -> RouterResult<()> {
+ let key = key_store.key.get_inner().peek();
+ let db = &*state.clone().store;
+ let (connector_name, access_token) = connector_details;
+
+ let payment_intent = db
+ .find_payment_intent_by_payment_id_merchant_id(
+ &payload.payment_id,
+ &merchant_account.merchant_id,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .to_not_found_response(ApiErrorResponse::PaymentNotFound)?;
+
+ let customer_id = payment_intent
+ .customer_id
+ .ok_or(ApiErrorResponse::CustomerNotFound)?;
+
+ let payment_methods = db
+ .find_payment_method_by_customer_id_merchant_id_list(
+ &customer_id,
+ &merchant_account.merchant_id,
+ )
+ .await
+ .change_context(ApiErrorResponse::InternalServerError)?;
+
+ let mut hash_to_payment_method: HashMap<
+ String,
+ (
+ storage::PaymentMethod,
+ payment_methods::PaymentMethodDataBankCreds,
+ ),
+ > = HashMap::new();
+
+ for pm in payment_methods {
+ if pm.payment_method == enums::PaymentMethod::BankDebit {
+ let bank_details_pm_data = decrypt::<serde_json::Value, masking::WithType>(
+ pm.payment_method_data.clone(),
+ key,
+ )
+ .await
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to decrypt bank account details")?
+ .map(|x| x.into_inner().expose())
+ .map(|v| {
+ serde_json::from_value::<payment_methods::PaymentMethodsData>(v)
+ .into_report()
+ .change_context(errors::StorageError::DeserializationFailed)
+ .attach_printable("Failed to deserialize Payment Method Auth config")
+ })
+ .transpose()
+ .unwrap_or_else(|err| {
+ logger::error!(error=?err);
+ None
+ })
+ .and_then(|pmd| match pmd {
+ payment_methods::PaymentMethodsData::BankDetails(bank_creds) => Some(bank_creds),
+ _ => None,
+ })
+ .ok_or(ApiErrorResponse::InternalServerError)?;
+
+ hash_to_payment_method.insert(
+ bank_details_pm_data.hash.clone(),
+ (pm, bank_details_pm_data),
+ );
+ }
+ }
+
+ #[cfg(feature = "kms")]
+ let pm_auth_key = kms::get_kms_client(&state.conf.kms)
+ .await
+ .decrypt(state.conf.payment_method_auth.pm_auth_key.clone())
+ .await
+ .change_context(ApiErrorResponse::InternalServerError)?;
+
+ #[cfg(not(feature = "kms"))]
+ let pm_auth_key = state.conf.payment_method_auth.pm_auth_key.clone();
+
+ let mut update_entries: Vec<(storage::PaymentMethod, storage::PaymentMethodUpdate)> =
+ Vec::new();
+ let mut new_entries: Vec<storage::PaymentMethodNew> = Vec::new();
+
+ for creds in bank_account_details_resp.credentials {
+ let hash_string = format!("{}-{}", creds.account_number, creds.routing_number);
+ let generated_hash = hex::encode(
+ HmacSha256::sign_message(&HmacSha256, pm_auth_key.as_bytes(), hash_string.as_bytes())
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to sign the message")?,
+ );
+
+ let contains_account = hash_to_payment_method.get(&generated_hash);
+ let mut pmd = payment_methods::PaymentMethodDataBankCreds {
+ mask: creds
+ .account_number
+ .chars()
+ .rev()
+ .take(4)
+ .collect::<String>()
+ .chars()
+ .rev()
+ .collect::<String>(),
+ hash: generated_hash,
+ account_type: creds.account_type,
+ account_name: creds.account_name,
+ payment_method_type: creds.payment_method_type,
+ connector_details: vec![payment_methods::BankAccountConnectorDetails {
+ connector: connector_name.to_string(),
+ mca_id: mca_id.clone(),
+ access_token: payment_methods::BankAccountAccessCreds::AccessToken(
+ access_token.clone(),
+ ),
+ account_id: creds.account_id,
+ }],
+ };
+
+ if let Some((pm, details)) = contains_account {
+ pmd.connector_details.extend(
+ details
+ .connector_details
+ .clone()
+ .into_iter()
+ .filter(|conn| conn.mca_id != mca_id),
+ );
+
+ let payment_method_data = payment_methods::PaymentMethodsData::BankDetails(pmd);
+ let encrypted_data =
+ cards::create_encrypted_payment_method_data(&key_store, Some(payment_method_data))
+ .await
+ .ok_or(ApiErrorResponse::InternalServerError)?;
+ let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
+ payment_method_data: Some(encrypted_data),
+ };
+
+ update_entries.push((pm.clone(), pm_update));
+ } else {
+ let payment_method_data = payment_methods::PaymentMethodsData::BankDetails(pmd);
+ let encrypted_data =
+ cards::create_encrypted_payment_method_data(&key_store, Some(payment_method_data))
+ .await
+ .ok_or(ApiErrorResponse::InternalServerError)?;
+ let pm_id = generate_id(consts::ID_LENGTH, "pm");
+ let pm_new = storage::PaymentMethodNew {
+ customer_id: customer_id.clone(),
+ merchant_id: merchant_account.merchant_id.clone(),
+ payment_method_id: pm_id,
+ payment_method: enums::PaymentMethod::BankDebit,
+ payment_method_type: Some(creds.payment_method_type),
+ payment_method_issuer: None,
+ scheme: None,
+ metadata: None,
+ payment_method_data: Some(encrypted_data),
+ ..storage::PaymentMethodNew::default()
+ };
+
+ new_entries.push(pm_new);
+ };
+ }
+
+ store_in_db(update_entries, new_entries, db).await?;
+
+ Ok(())
+}
+
+async fn store_in_db(
+ update_entries: Vec<(storage::PaymentMethod, storage::PaymentMethodUpdate)>,
+ new_entries: Vec<storage::PaymentMethodNew>,
+ db: &dyn StorageInterface,
+) -> RouterResult<()> {
+ let update_entries_futures = update_entries
+ .into_iter()
+ .map(|(pm, pm_update)| db.update_payment_method(pm, pm_update))
+ .collect::<Vec<_>>();
+
+ let new_entries_futures = new_entries
+ .into_iter()
+ .map(|pm_new| db.insert_payment_method(pm_new))
+ .collect::<Vec<_>>();
+
+ let update_futures = futures::future::join_all(update_entries_futures);
+ let new_futures = futures::future::join_all(new_entries_futures);
+
+ let (update, new) = tokio::join!(update_futures, new_futures);
+
+ let _ = update
+ .into_iter()
+ .map(|res| res.map_err(|err| logger::error!("Payment method storage failed {err:?}")));
+
+ let _ = new
+ .into_iter()
+ .map(|res| res.map_err(|err| logger::error!("Payment method storage failed {err:?}")));
+
+ Ok(())
+}
+
+pub async fn get_bank_account_creds(
+ connector: PaymentAuthConnectorData,
+ merchant_account: &domain::MerchantAccount,
+ connector_name: &str,
+ access_token: &str,
+ auth_type: pm_auth_types::ConnectorAuthType,
+ state: &AppState,
+ bank_account_id: Option<String>,
+) -> RouterResult<pm_auth_types::BankAccountCredentialsResponse> {
+ let connector_integration_bank_details: BoxedConnectorIntegration<
+ '_,
+ BankAccountCredentials,
+ pm_auth_types::BankAccountCredentialsRequest,
+ pm_auth_types::BankAccountCredentialsResponse,
+ > = connector.connector.get_connector_integration();
+
+ let router_data_bank_details = pm_auth_types::BankDetailsRouterData {
+ flow: std::marker::PhantomData,
+ merchant_id: Some(merchant_account.merchant_id.clone()),
+ connector: Some(connector_name.to_string()),
+ request: pm_auth_types::BankAccountCredentialsRequest {
+ access_token: access_token.to_string(),
+ optional_ids: bank_account_id
+ .map(|id| pm_auth_types::BankAccountOptionalIDs { ids: vec![id] }),
+ },
+ response: Ok(pm_auth_types::BankAccountCredentialsResponse {
+ credentials: Vec::new(),
+ }),
+ connector_http_status_code: None,
+ connector_auth_type: auth_type,
+ };
+
+ let bank_details_resp = pm_auth_services::execute_connector_processing_step(
+ state,
+ connector_integration_bank_details,
+ &router_data_bank_details,
+ &connector.connector_name,
+ )
+ .await
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while calling bank account details connector api")?;
+
+ let bank_account_details_resp =
+ bank_details_resp
+ .response
+ .map_err(|err| ApiErrorResponse::ExternalConnectorError {
+ code: err.code,
+ message: err.message,
+ connector: connector.connector_name.to_string(),
+ status_code: err.status_code,
+ reason: err.reason,
+ })?;
+
+ Ok(bank_account_details_resp)
+}
+
+async fn get_access_token_from_exchange_api(
+ connector: &PaymentAuthConnectorData,
+ connector_name: &str,
+ payload: &api_models::pm_auth::ExchangeTokenCreateRequest,
+ auth_type: &pm_auth_types::ConnectorAuthType,
+ state: &AppState,
+) -> RouterResult<String> {
+ let connector_integration: BoxedConnectorIntegration<
+ '_,
+ ExchangeToken,
+ pm_auth_types::ExchangeTokenRequest,
+ pm_auth_types::ExchangeTokenResponse,
+ > = connector.connector.get_connector_integration();
+
+ let router_data = pm_auth_types::ExchangeTokenRouterData {
+ flow: std::marker::PhantomData,
+ merchant_id: None,
+ connector: Some(connector_name.to_string()),
+ request: pm_auth_types::ExchangeTokenRequest {
+ public_token: payload.public_token.clone(),
+ },
+ response: Ok(pm_auth_types::ExchangeTokenResponse {
+ access_token: "".to_string(),
+ }),
+ connector_http_status_code: None,
+ connector_auth_type: auth_type.clone(),
+ };
+
+ let resp = pm_auth_services::execute_connector_processing_step(
+ state,
+ connector_integration,
+ &router_data,
+ &connector.connector_name,
+ )
+ .await
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while calling exchange token connector api")?;
+
+ let exchange_token_resp =
+ resp.response
+ .map_err(|err| ApiErrorResponse::ExternalConnectorError {
+ code: err.code,
+ message: err.message,
+ connector: connector.connector_name.to_string(),
+ status_code: err.status_code,
+ reason: err.reason,
+ })?;
+
+ let access_token = exchange_token_resp.access_token;
+ Ok(access_token)
+}
+
+async fn get_selected_config_from_redis(
+ db: &dyn StorageInterface,
+ payload: &api_models::pm_auth::ExchangeTokenCreateRequest,
+) -> RouterResult<api_models::pm_auth::PaymentMethodAuthConnectorChoice> {
+ let redis_conn = db
+ .get_redis_conn()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get redis connection")?;
+
+ let pm_auth_key = format!("pm_auth_{}", payload.payment_id);
+
+ let pm_auth_configs = redis_conn
+ .get_and_deserialize_key::<Vec<api_models::pm_auth::PaymentMethodAuthConnectorChoice>>(
+ pm_auth_key.as_str(),
+ "Vec<PaymentMethodAuthConnectorChoice>",
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get payment method auth choices from redis")?;
+
+ let selected_config = pm_auth_configs
+ .iter()
+ .find(|conf| {
+ conf.payment_method == payload.payment_method
+ && conf.payment_method_type == payload.payment_method_type
+ })
+ .ok_or(ApiErrorResponse::GenericNotFoundError {
+ message: "connector name not found".to_string(),
+ })
+ .into_report()?
+ .clone();
+
+ Ok(selected_config)
+}
+
+pub async fn retrieve_payment_method_from_auth_service(
+ state: &AppState,
+ key_store: &domain::MerchantKeyStore,
+ auth_token: &payment_methods::BankAccountConnectorDetails,
+ payment_intent: &PaymentIntent,
+) -> RouterResult<Option<(PaymentMethodData, enums::PaymentMethod)>> {
+ let db = state.store.as_ref();
+
+ let connector = pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name(
+ auth_token.connector.as_str(),
+ )?;
+
+ let merchant_account = db
+ .find_merchant_account_by_merchant_id(&payment_intent.merchant_id, key_store)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
+
+ let mca = db
+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(
+ &payment_intent.merchant_id,
+ &auth_token.mca_id,
+ key_store,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ id: auth_token.mca_id.clone(),
+ })
+ .attach_printable(
+ "error while fetching merchant_connector_account from merchant_id and connector name",
+ )?;
+
+ let auth_type = pm_auth_helpers::get_connector_auth_type(mca)?;
+
+ let BankAccountAccessCreds::AccessToken(access_token) = &auth_token.access_token;
+
+ let bank_account_creds = get_bank_account_creds(
+ connector,
+ &merchant_account,
+ &auth_token.connector,
+ access_token,
+ auth_type,
+ state,
+ Some(auth_token.account_id.clone()),
+ )
+ .await?;
+
+ logger::debug!("bank_creds: {:?}", bank_account_creds);
+
+ let bank_account = bank_account_creds
+ .credentials
+ .first()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .into_report()
+ .attach_printable("Bank account details not found")?;
+
+ let mut bank_type = None;
+ if let Some(account_type) = bank_account.account_type.clone() {
+ bank_type = api_models::enums::BankType::from_str(account_type.as_str())
+ .map_err(|error| logger::error!(%error,"unable to parse account_type {account_type:?}"))
+ .ok();
+ }
+
+ let address = oss_helpers::get_address_by_id(
+ &*state.store,
+ payment_intent.billing_address_id.clone(),
+ key_store,
+ payment_intent.payment_id.clone(),
+ merchant_account.merchant_id.clone(),
+ merchant_account.storage_scheme,
+ )
+ .await?;
+
+ let name = address
+ .as_ref()
+ .and_then(|addr| addr.first_name.clone().map(|name| name.into_inner()));
+
+ let address_details = address.clone().map(|addr| {
+ let line1 = addr.line1.map(|line1| line1.into_inner());
+ let line2 = addr.line2.map(|line2| line2.into_inner());
+ let line3 = addr.line3.map(|line3| line3.into_inner());
+ let zip = addr.zip.map(|zip| zip.into_inner());
+ let state = addr.state.map(|state| state.into_inner());
+ let first_name = addr.first_name.map(|first_name| first_name.into_inner());
+ let last_name = addr.last_name.map(|last_name| last_name.into_inner());
+
+ AddressDetails {
+ city: addr.city,
+ country: addr.country,
+ line1,
+ line2,
+ line3,
+ zip,
+ state,
+ first_name,
+ last_name,
+ }
+ });
+ let payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit {
+ billing_details: BankDebitBilling {
+ name: name.unwrap_or_default(),
+ email: common_utils::pii::Email::from(masking::Secret::new("".to_string())),
+ address: address_details,
+ },
+ account_number: masking::Secret::new(bank_account.account_number.clone()),
+ routing_number: masking::Secret::new(bank_account.routing_number.clone()),
+ card_holder_name: None,
+ bank_account_holder_name: None,
+ bank_name: None,
+ bank_type,
+ bank_holder_type: None,
+ });
+
+ Ok(Some((payment_method_data, enums::PaymentMethod::BankDebit)))
+}
diff --git a/crates/router/src/core/pm_auth/helpers.rs b/crates/router/src/core/pm_auth/helpers.rs
new file mode 100644
index 00000000000..43d30705a80
--- /dev/null
+++ b/crates/router/src/core/pm_auth/helpers.rs
@@ -0,0 +1,33 @@
+use common_utils::ext_traits::ValueExt;
+use error_stack::{IntoReport, ResultExt};
+use pm_auth::types::{self as pm_auth_types, api::BoxedPaymentAuthConnector};
+
+use crate::{
+ core::errors::{self, ApiErrorResponse},
+ types::{self, domain, transformers::ForeignTryFrom},
+};
+
+pub trait PaymentAuthConnectorDataExt {
+ fn get_connector_by_name(name: &str) -> errors::CustomResult<Self, ApiErrorResponse>
+ where
+ Self: Sized;
+ fn convert_connector(
+ connector_name: pm_auth_types::PaymentMethodAuthConnectors,
+ ) -> errors::CustomResult<BoxedPaymentAuthConnector, ApiErrorResponse>;
+}
+
+pub fn get_connector_auth_type(
+ merchant_connector_account: domain::MerchantConnectorAccount,
+) -> errors::CustomResult<pm_auth_types::ConnectorAuthType, ApiErrorResponse> {
+ let auth_type: types::ConnectorAuthType = merchant_connector_account
+ .connector_account_details
+ .parse_value("ConnectorAuthType")
+ .change_context(ApiErrorResponse::MerchantConnectorAccountNotFound {
+ id: "ConnectorAuthType".to_string(),
+ })?;
+
+ pm_auth_types::ConnectorAuthType::foreign_try_from(auth_type)
+ .into_report()
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while converting ConnectorAuthType")
+}
diff --git a/crates/router/src/core/pm_auth/transformers.rs b/crates/router/src/core/pm_auth/transformers.rs
new file mode 100644
index 00000000000..8a1369c2e02
--- /dev/null
+++ b/crates/router/src/core/pm_auth/transformers.rs
@@ -0,0 +1,18 @@
+use pm_auth::types::{self as pm_auth_types};
+
+use crate::{core::errors, types, types::transformers::ForeignTryFrom};
+
+impl ForeignTryFrom<types::ConnectorAuthType> for pm_auth_types::ConnectorAuthType {
+ type Error = errors::ConnectorError;
+ fn foreign_try_from(auth_type: types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ match auth_type {
+ types::ConnectorAuthType::BodyKey { api_key, key1 } => {
+ Ok::<Self, errors::ConnectorError>(Self::BodyKey {
+ client_id: api_key.to_owned(),
+ secret: key1.to_owned(),
+ })
+ }
+ _ => Err(errors::ConnectorError::FailedToObtainAuthType),
+ }
+ }
+}
diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs
index ce1717c9e93..ec718b2dde9 100644
--- a/crates/router/src/routes.rs
+++ b/crates/router/src/routes.rs
@@ -40,6 +40,8 @@ pub mod verify_connector;
pub mod webhooks;
pub mod locker_migration;
+#[cfg(any(feature = "olap", feature = "oltp"))]
+pub mod pm_auth;
#[cfg(feature = "dummy_connector")]
pub use self::app::DummyConnector;
#[cfg(any(feature = "olap", feature = "oltp"))]
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 6b72e69b9f4..a7c394b7b6c 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -20,6 +20,8 @@ use super::currency;
use super::dummy_connector::*;
#[cfg(feature = "payouts")]
use super::payouts::*;
+#[cfg(feature = "oltp")]
+use super::pm_auth;
#[cfg(feature = "olap")]
use super::routing as cloud_routing;
#[cfg(all(feature = "olap", feature = "kms"))]
@@ -555,6 +557,8 @@ impl PaymentMethods {
.route(web::post().to(payment_method_update_api))
.route(web::delete().to(payment_method_delete_api)),
)
+ .service(web::resource("/auth/link").route(web::post().to(pm_auth::link_token_create)))
+ .service(web::resource("/auth/exchange").route(web::post().to(pm_auth::exchange_token)))
}
}
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 88c35bb0a13..533d1d3a629 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -13,6 +13,7 @@ pub enum ApiIdentifier {
Ephemeral,
Mandates,
PaymentMethods,
+ PaymentMethodAuth,
Payouts,
Disputes,
CardsInfo,
@@ -86,6 +87,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::PaymentMethodsDelete
| Flow::ValidatePaymentMethod => Self::PaymentMethods,
+ Flow::PmAuthLinkTokenCreate | Flow::PmAuthExchangeToken => Self::PaymentMethodAuth,
+
Flow::PaymentsCreate
| Flow::PaymentsRetrieve
| Flow::PaymentsUpdate
diff --git a/crates/router/src/routes/pm_auth.rs b/crates/router/src/routes/pm_auth.rs
new file mode 100644
index 00000000000..cfadd787c31
--- /dev/null
+++ b/crates/router/src/routes/pm_auth.rs
@@ -0,0 +1,73 @@
+use actix_web::{web, HttpRequest, Responder};
+use api_models as api_types;
+use router_env::{instrument, tracing, types::Flow};
+
+use crate::{core::api_locking, routes::AppState, services::api as oss_api};
+
+#[instrument(skip_all, fields(flow = ?Flow::PmAuthLinkTokenCreate))]
+pub async fn link_token_create(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<api_types::pm_auth::LinkTokenCreateRequest>,
+) -> impl Responder {
+ let payload = json_payload.into_inner();
+ let flow = Flow::PmAuthLinkTokenCreate;
+ let (auth, _) = match crate::services::authentication::check_client_secret_and_get_auth(
+ req.headers(),
+ &payload,
+ ) {
+ Ok((auth, _auth_flow)) => (auth, _auth_flow),
+ Err(e) => return oss_api::log_and_return_error_response(e),
+ };
+ Box::pin(oss_api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth, payload| {
+ crate::core::pm_auth::create_link_token(
+ state,
+ auth.merchant_account,
+ auth.key_store,
+ payload,
+ )
+ },
+ &*auth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[instrument(skip_all, fields(flow = ?Flow::PmAuthExchangeToken))]
+pub async fn exchange_token(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<api_types::pm_auth::ExchangeTokenCreateRequest>,
+) -> impl Responder {
+ let payload = json_payload.into_inner();
+ let flow = Flow::PmAuthExchangeToken;
+ let (auth, _) = match crate::services::authentication::check_client_secret_and_get_auth(
+ req.headers(),
+ &payload,
+ ) {
+ Ok((auth, _auth_flow)) => (auth, _auth_flow),
+ Err(e) => return oss_api::log_and_return_error_response(e),
+ };
+ Box::pin(oss_api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth, payload| {
+ crate::core::pm_auth::exchange_token_core(
+ state,
+ auth.merchant_account,
+ auth.key_store,
+ payload,
+ )
+ },
+ &*auth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs
index e46612b95df..57f3b802bd5 100644
--- a/crates/router/src/services.rs
+++ b/crates/router/src/services.rs
@@ -6,6 +6,7 @@ pub mod encryption;
pub mod jwt;
pub mod kafka;
pub mod logger;
+pub mod pm_auth;
#[cfg(feature = "email")]
pub mod email;
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 8a0cd7c729e..b48465ebd17 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -641,6 +641,18 @@ impl ClientSecretFetch for api_models::payments::RetrievePaymentLinkRequest {
}
}
+impl ClientSecretFetch for api_models::pm_auth::LinkTokenCreateRequest {
+ fn get_client_secret(&self) -> Option<&String> {
+ self.client_secret.as_ref()
+ }
+}
+
+impl ClientSecretFetch for api_models::pm_auth::ExchangeTokenCreateRequest {
+ fn get_client_secret(&self) -> Option<&String> {
+ self.client_secret.as_ref()
+ }
+}
+
pub fn get_auth_type_and_flow<A: AppStateInfo + Sync>(
headers: &HeaderMap,
) -> RouterResult<(
diff --git a/crates/router/src/services/pm_auth.rs b/crates/router/src/services/pm_auth.rs
new file mode 100644
index 00000000000..7487b12663b
--- /dev/null
+++ b/crates/router/src/services/pm_auth.rs
@@ -0,0 +1,95 @@
+use pm_auth::{
+ consts,
+ core::errors::ConnectorError,
+ types::{self as pm_auth_types, api::BoxedConnectorIntegration, PaymentAuthRouterData},
+};
+
+use crate::{
+ core::errors::{self},
+ logger,
+ routes::AppState,
+ services::{self},
+};
+
+pub async fn execute_connector_processing_step<
+ 'b,
+ 'a,
+ T: 'static,
+ Req: Clone + 'static,
+ Resp: Clone + 'static,
+>(
+ state: &'b AppState,
+ connector_integration: BoxedConnectorIntegration<'a, T, Req, Resp>,
+ req: &'b PaymentAuthRouterData<T, Req, Resp>,
+ connector: &pm_auth_types::PaymentMethodAuthConnectors,
+) -> errors::CustomResult<PaymentAuthRouterData<T, Req, Resp>, ConnectorError>
+where
+ T: Clone,
+ Req: Clone,
+ Resp: Clone,
+{
+ let mut router_data = req.clone();
+
+ let connector_request = connector_integration.build_request(req, connector)?;
+
+ match connector_request {
+ Some(request) => {
+ logger::debug!(connector_request=?request);
+ let response = services::api::call_connector_api(state, request).await;
+ logger::debug!(connector_response=?response);
+ match response {
+ Ok(body) => {
+ let response = match body {
+ Ok(body) => {
+ let body = pm_auth_types::Response {
+ headers: body.headers,
+ response: body.response,
+ status_code: body.status_code,
+ };
+ let connector_http_status_code = Some(body.status_code);
+ let mut data =
+ connector_integration.handle_response(&router_data, body)?;
+ data.connector_http_status_code = connector_http_status_code;
+
+ data
+ }
+ Err(body) => {
+ let body = pm_auth_types::Response {
+ headers: body.headers,
+ response: body.response,
+ status_code: body.status_code,
+ };
+ router_data.connector_http_status_code = Some(body.status_code);
+
+ let error = match body.status_code {
+ 500..=511 => connector_integration.get_5xx_error_response(body)?,
+ _ => connector_integration.get_error_response(body)?,
+ };
+
+ router_data.response = Err(error);
+
+ router_data
+ }
+ };
+ Ok(response)
+ }
+ Err(error) => {
+ if error.current_context().is_upstream_timeout() {
+ let error_response = pm_auth_types::ErrorResponse {
+ code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(),
+ message: consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string(),
+ reason: Some(consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string()),
+ status_code: 504,
+ };
+ router_data.response = Err(error_response);
+ router_data.connector_http_status_code = Some(504);
+ Ok(router_data)
+ } else {
+ Err(error.change_context(ConnectorError::ProcessingStepFailed(None)))
+ }
+ }
+ }
+ }
+ None => Ok(router_data),
+ }
+}
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index de28c1a3188..aa563c647ea 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -10,6 +10,8 @@ pub mod api;
pub mod domain;
#[cfg(feature = "frm")]
pub mod fraud_check;
+pub mod pm_auth;
+
pub mod storage;
pub mod transformers;
diff --git a/crates/router/src/types/pm_auth.rs b/crates/router/src/types/pm_auth.rs
new file mode 100644
index 00000000000..e2d08c6afea
--- /dev/null
+++ b/crates/router/src/types/pm_auth.rs
@@ -0,0 +1,38 @@
+use std::str::FromStr;
+
+use error_stack::{IntoReport, ResultExt};
+use pm_auth::{
+ connector::plaid,
+ types::{
+ self as pm_auth_types,
+ api::{BoxedPaymentAuthConnector, PaymentAuthConnectorData},
+ },
+};
+
+use crate::core::{
+ errors::{self, ApiErrorResponse},
+ pm_auth::helpers::PaymentAuthConnectorDataExt,
+};
+
+impl PaymentAuthConnectorDataExt for PaymentAuthConnectorData {
+ fn get_connector_by_name(name: &str) -> errors::CustomResult<Self, ApiErrorResponse> {
+ let connector_name = pm_auth_types::PaymentMethodAuthConnectors::from_str(name)
+ .into_report()
+ .change_context(ApiErrorResponse::IncorrectConnectorNameGiven)
+ .attach_printable_lazy(|| {
+ format!("unable to parse connector: {:?}", name.to_string())
+ })?;
+ let connector = Self::convert_connector(connector_name.clone())?;
+ Ok(Self {
+ connector,
+ connector_name,
+ })
+ }
+ fn convert_connector(
+ connector_name: pm_auth_types::PaymentMethodAuthConnectors,
+ ) -> errors::CustomResult<BoxedPaymentAuthConnector, ApiErrorResponse> {
+ match connector_name {
+ pm_auth_types::PaymentMethodAuthConnectors::Plaid => Ok(Box::new(&plaid::Plaid)),
+ }
+ }
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 13ca344e9c5..b682bcb12e6 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -295,6 +295,10 @@ pub enum Flow {
UserMerchantAccountList,
/// Get users for merchant account
GetUserDetails,
+ /// PaymentMethodAuth Link token create
+ PmAuthLinkTokenCreate,
+ /// PaymentMethodAuth Exchange token create
+ PmAuthExchangeToken,
/// Get reset password link
ForgotPassword,
/// Reset password using link
|
feat
|
pm_auth service migration (#3047)
|
f30ba89884d3abf2356cf1870d833a97d2411f69
|
2024-01-05 16:21:40
|
Chethan Rao
|
feat: add deep health check (#3210)
| false
|
diff --git a/crates/api_models/src/health_check.rs b/crates/api_models/src/health_check.rs
new file mode 100644
index 00000000000..d7bb120d017
--- /dev/null
+++ b/crates/api_models/src/health_check.rs
@@ -0,0 +1,6 @@
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct RouterHealthCheckResponse {
+ pub database: String,
+ pub redis: String,
+ pub locker: String,
+}
diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs
index 935944cf74c..459443747e3 100644
--- a/crates/api_models/src/lib.rs
+++ b/crates/api_models/src/lib.rs
@@ -16,6 +16,7 @@ pub mod errors;
pub mod events;
pub mod files;
pub mod gsm;
+pub mod health_check;
pub mod locker_migration;
pub mod mandates;
pub mod organization;
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 4a2d2831d10..eff42c0cd7c 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -70,3 +70,5 @@ pub const EMAIL_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day
pub const VERIFY_CONNECTOR_ID_PREFIX: &str = "conn_verify";
#[cfg(feature = "olap")]
pub const VERIFY_CONNECTOR_MERCHANT_ID: &str = "test_merchant";
+
+pub const LOCKER_HEALTH_CALL_PATH: &str = "/health";
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index 0cd4cb21881..5beace9cbb8 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -14,6 +14,7 @@ pub mod events;
pub mod file;
pub mod fraud_check;
pub mod gsm;
+pub mod health_check;
mod kafka_store;
pub mod locker_mock_up;
pub mod mandate;
@@ -103,6 +104,7 @@ pub trait StorageInterface:
+ user_role::UserRoleInterface
+ authorization::AuthorizationInterface
+ user::sample_data::BatchSampleDataInterface
+ + health_check::HealthCheckInterface
+ 'static
{
fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>;
diff --git a/crates/router/src/db/health_check.rs b/crates/router/src/db/health_check.rs
new file mode 100644
index 00000000000..73bc2a4321d
--- /dev/null
+++ b/crates/router/src/db/health_check.rs
@@ -0,0 +1,147 @@
+use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl};
+use diesel_models::ConfigNew;
+use error_stack::ResultExt;
+use router_env::logger;
+
+use super::{MockDb, StorageInterface, Store};
+use crate::{
+ connection,
+ consts::LOCKER_HEALTH_CALL_PATH,
+ core::errors::{self, CustomResult},
+ routes,
+ services::api as services,
+ types::storage,
+};
+
+#[async_trait::async_trait]
+pub trait HealthCheckInterface {
+ async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError>;
+ async fn health_check_redis(
+ &self,
+ db: &dyn StorageInterface,
+ ) -> CustomResult<(), errors::HealthCheckRedisError>;
+ async fn health_check_locker(
+ &self,
+ state: &routes::AppState,
+ ) -> CustomResult<(), errors::HealthCheckLockerError>;
+}
+
+#[async_trait::async_trait]
+impl HealthCheckInterface for Store {
+ async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> {
+ let conn = connection::pg_connection_write(self)
+ .await
+ .change_context(errors::HealthCheckDBError::DBError)?;
+
+ let _data = conn
+ .transaction_async(|conn| {
+ Box::pin(async move {
+ let query =
+ diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>("1 + 1"));
+ let _x: i32 = query.get_result_async(&conn).await.map_err(|err| {
+ logger::error!(read_err=?err,"Error while reading element in the database");
+ errors::HealthCheckDBError::DBReadError
+ })?;
+
+ logger::debug!("Database read was successful");
+
+ let config = ConfigNew {
+ key: "test_key".to_string(),
+ config: "test_value".to_string(),
+ };
+
+ config.insert(&conn).await.map_err(|err| {
+ logger::error!(write_err=?err,"Error while writing to database");
+ errors::HealthCheckDBError::DBWriteError
+ })?;
+
+ logger::debug!("Database write was successful");
+
+ storage::Config::delete_by_key(&conn, "test_key").await.map_err(|err| {
+ logger::error!(delete_err=?err,"Error while deleting element in the database");
+ errors::HealthCheckDBError::DBDeleteError
+ })?;
+
+ logger::debug!("Database delete was successful");
+
+ Ok::<_, errors::HealthCheckDBError>(())
+ })
+ })
+ .await?;
+
+ Ok(())
+ }
+
+ async fn health_check_redis(
+ &self,
+ db: &dyn StorageInterface,
+ ) -> CustomResult<(), errors::HealthCheckRedisError> {
+ let redis_conn = db
+ .get_redis_conn()
+ .change_context(errors::HealthCheckRedisError::RedisConnectionError)?;
+
+ redis_conn
+ .serialize_and_set_key_with_expiry("test_key", "test_value", 30)
+ .await
+ .change_context(errors::HealthCheckRedisError::SetFailed)?;
+
+ logger::debug!("Redis set_key was successful");
+
+ redis_conn
+ .get_key("test_key")
+ .await
+ .change_context(errors::HealthCheckRedisError::GetFailed)?;
+
+ logger::debug!("Redis get_key was successful");
+
+ redis_conn
+ .delete_key("test_key")
+ .await
+ .change_context(errors::HealthCheckRedisError::DeleteFailed)?;
+
+ logger::debug!("Redis delete_key was successful");
+
+ Ok(())
+ }
+
+ async fn health_check_locker(
+ &self,
+ state: &routes::AppState,
+ ) -> CustomResult<(), errors::HealthCheckLockerError> {
+ let locker = &state.conf.locker;
+ if !locker.mock_locker {
+ let mut url = locker.host_rs.to_owned();
+ url.push_str(LOCKER_HEALTH_CALL_PATH);
+ let request = services::Request::new(services::Method::Get, &url);
+ services::call_connector_api(state, request)
+ .await
+ .change_context(errors::HealthCheckLockerError::FailedToCallLocker)?
+ .ok();
+ }
+
+ logger::debug!("Locker call was successful");
+
+ Ok(())
+ }
+}
+
+#[async_trait::async_trait]
+impl HealthCheckInterface for MockDb {
+ async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> {
+ Ok(())
+ }
+
+ async fn health_check_redis(
+ &self,
+ _: &dyn StorageInterface,
+ ) -> CustomResult<(), errors::HealthCheckRedisError> {
+ Ok(())
+ }
+
+ async fn health_check_locker(
+ &self,
+ _: &routes::AppState,
+ ) -> CustomResult<(), errors::HealthCheckLockerError> {
+ Ok(())
+ }
+}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index db94c1bcbca..1184992a8f7 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -43,6 +43,7 @@ use crate::{
events::EventInterface,
file::FileMetadataInterface,
gsm::GsmInterface,
+ health_check::HealthCheckInterface,
locker_mock_up::LockerMockUpInterface,
mandate::MandateInterface,
merchant_account::MerchantAccountInterface,
@@ -57,6 +58,7 @@ use crate::{
routing_algorithm::RoutingAlgorithmInterface,
MasterKeyInterface, StorageInterface,
},
+ routes,
services::{authentication, kafka::KafkaProducer, Store},
types::{
domain,
@@ -2131,3 +2133,24 @@ impl AuthorizationInterface for KafkaStore {
.await
}
}
+
+#[async_trait::async_trait]
+impl HealthCheckInterface for KafkaStore {
+ async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> {
+ self.diesel_store.health_check_db().await
+ }
+
+ async fn health_check_redis(
+ &self,
+ db: &dyn StorageInterface,
+ ) -> CustomResult<(), errors::HealthCheckRedisError> {
+ self.diesel_store.health_check_redis(db).await
+ }
+
+ async fn health_check_locker(
+ &self,
+ state: &routes::AppState,
+ ) -> CustomResult<(), errors::HealthCheckLockerError> {
+ self.diesel_store.health_check_locker(state).await
+ }
+}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 0357cedd443..6625a206be2 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -253,9 +253,10 @@ pub struct Health;
impl Health {
pub fn server(state: AppState) -> Scope {
- web::scope("")
+ web::scope("health")
.app_data(web::Data::new(state))
- .service(web::resource("/health").route(web::get().to(health)))
+ .service(web::resource("").route(web::get().to(health)))
+ .service(web::resource("/deep_check").route(web::post().to(deep_health_check)))
}
}
diff --git a/crates/router/src/routes/health.rs b/crates/router/src/routes/health.rs
index 7c7f29bd181..f07b744f7f5 100644
--- a/crates/router/src/routes/health.rs
+++ b/crates/router/src/routes/health.rs
@@ -1,7 +1,9 @@
+use actix_web::web;
+use api_models::health_check::RouterHealthCheckResponse;
use router_env::{instrument, logger, tracing};
-use crate::routes::metrics;
-
+use super::app;
+use crate::{routes::metrics, services};
/// .
// #[logger::instrument(skip_all, name = "name1", level = "warn", fields( key1 = "val1" ))]
#[instrument(skip_all)]
@@ -11,3 +13,59 @@ pub async fn health() -> impl actix_web::Responder {
logger::info!("Health was called");
actix_web::HttpResponse::Ok().body("health is good")
}
+
+#[instrument(skip_all)]
+pub async fn deep_health_check(state: web::Data<app::AppState>) -> impl actix_web::Responder {
+ metrics::HEALTH_METRIC.add(&metrics::CONTEXT, 1, &[]);
+ let db = &*state.store;
+ let mut status_code = 200;
+ logger::info!("Deep health check was called");
+
+ logger::debug!("Database health check begin");
+
+ let db_status = match db.health_check_db().await {
+ Ok(_) => "Health is good".to_string(),
+ Err(err) => {
+ status_code = 500;
+ err.to_string()
+ }
+ };
+ logger::debug!("Database health check end");
+
+ logger::debug!("Redis health check begin");
+
+ let redis_status = match db.health_check_redis(db).await {
+ Ok(_) => "Health is good".to_string(),
+ Err(err) => {
+ status_code = 500;
+ err.to_string()
+ }
+ };
+
+ logger::debug!("Redis health check end");
+
+ logger::debug!("Locker health check begin");
+
+ let locker_status = match db.health_check_locker(&state).await {
+ Ok(_) => "Health is good".to_string(),
+ Err(err) => {
+ status_code = 500;
+ err.to_string()
+ }
+ };
+
+ logger::debug!("Locker health check end");
+
+ let response = serde_json::to_string(&RouterHealthCheckResponse {
+ database: db_status,
+ redis: redis_status,
+ locker: locker_status,
+ })
+ .unwrap_or_default();
+
+ if status_code == 200 {
+ services::http_response_json(response)
+ } else {
+ services::http_server_error_json_response(response)
+ }
+}
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 92fda578727..71687e02c12 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -1138,6 +1138,14 @@ pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpRe
.body(response)
}
+pub fn http_server_error_json_response<T: body::MessageBody + 'static>(
+ response: T,
+) -> HttpResponse {
+ HttpResponse::InternalServerError()
+ .content_type(mime::APPLICATION_JSON)
+ .body(response)
+}
+
pub fn http_response_json_with_headers<T: body::MessageBody + 'static>(
response: T,
mut headers: Vec<(String, String)>,
diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs
index cc7353dcda6..fca85c41699 100644
--- a/crates/router/src/services/api/client.rs
+++ b/crates/router/src/services/api/client.rs
@@ -10,6 +10,7 @@ use router_env::tracing_actix_web::RequestId;
use super::{request::Maskable, Request};
use crate::{
configs::settings::{Locker, Proxy},
+ consts::LOCKER_HEALTH_CALL_PATH,
core::{
errors::{ApiClientError, CustomResult},
payments,
@@ -119,6 +120,7 @@ pub fn proxy_bypass_urls(locker: &Locker) -> Vec<String> {
format!("{locker_host_rs}/cards/add"),
format!("{locker_host_rs}/cards/retrieve"),
format!("{locker_host_rs}/cards/delete"),
+ format!("{locker_host_rs}{}", LOCKER_HEALTH_CALL_PATH),
format!("{locker_host}/card/addCard"),
format!("{locker_host}/card/getCard"),
format!("{locker_host}/card/deleteCard"),
diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs
index f0cbebf78c5..50173bb1c73 100644
--- a/crates/storage_impl/src/errors.rs
+++ b/crates/storage_impl/src/errors.rs
@@ -376,3 +376,53 @@ pub enum ConnectorError {
#[error("Missing 3DS redirection payload: {field_name}")]
MissingConnectorRedirectionPayload { field_name: &'static str },
}
+
+#[derive(Debug, thiserror::Error)]
+pub enum HealthCheckDBError {
+ #[error("Error while connecting to database")]
+ DBError,
+ #[error("Error while writing to database")]
+ DBWriteError,
+ #[error("Error while reading element in the database")]
+ DBReadError,
+ #[error("Error while deleting element in the database")]
+ DBDeleteError,
+ #[error("Unpredictable error occurred")]
+ UnknownError,
+ #[error("Error in database transaction")]
+ TransactionError,
+}
+
+impl From<diesel::result::Error> for HealthCheckDBError {
+ fn from(error: diesel::result::Error) -> Self {
+ match error {
+ diesel::result::Error::DatabaseError(_, _) => Self::DBError,
+
+ diesel::result::Error::RollbackErrorOnCommit { .. }
+ | diesel::result::Error::RollbackTransaction
+ | diesel::result::Error::AlreadyInTransaction
+ | diesel::result::Error::NotInTransaction
+ | diesel::result::Error::BrokenTransactionManager => Self::TransactionError,
+
+ _ => Self::UnknownError,
+ }
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum HealthCheckRedisError {
+ #[error("Failed to establish Redis connection")]
+ RedisConnectionError,
+ #[error("Failed to set key value in Redis")]
+ SetFailed,
+ #[error("Failed to get key value in Redis")]
+ GetFailed,
+ #[error("Failed to delete key value in Redis")]
+ DeleteFailed,
+}
+
+#[derive(Debug, Clone, thiserror::Error)]
+pub enum HealthCheckLockerError {
+ #[error("Failed to establish Locker connection")]
+ FailedToCallLocker,
+}
|
feat
|
add deep health check (#3210)
|
295d3dde7749e7576dbdee4675528bb6dd6ffb70
|
2024-12-26 17:17:36
|
Pa1NarK
|
ci: add tests that make use of locker (#6735)
| false
|
diff --git a/cypress-tests/cypress/e2e/PaymentTest/00003-ConnectorCreate.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00003-ConnectorCreate.cy.js
index 9c9e757598b..3d002740e60 100644
--- a/cypress-tests/cypress/e2e/PaymentTest/00003-ConnectorCreate.cy.js
+++ b/cypress-tests/cypress/e2e/PaymentTest/00003-ConnectorCreate.cy.js
@@ -1,6 +1,7 @@
import * as fixtures from "../../fixtures/imports";
import State from "../../utils/State";
import { payment_methods_enabled } from "../PaymentUtils/Commons";
+import * as utils from "../PaymentUtils/Utils";
let globalState;
describe("Connector Account Create flow test", () => {
@@ -14,7 +15,7 @@ describe("Connector Account Create flow test", () => {
cy.task("setGlobalState", globalState.data);
});
- it("connector-create-call-test", () => {
+ it("Create merchant connector account", () => {
cy.createConnectorCallTest(
"payment_processor",
fixtures.createConnectorBody,
@@ -23,31 +24,27 @@ describe("Connector Account Create flow test", () => {
);
});
- it("check and create multiple connectors", () => {
- const multiple_connectors = Cypress.env("MULTIPLE_CONNECTORS");
- // multiple_connectors will be undefined if not set in the env
- if (multiple_connectors?.status) {
- // Create multiple connectors based on the count
- // The first connector is already created when creating merchant account, so start from 1
- for (let i = 1; i < multiple_connectors.count; i++) {
- cy.createBusinessProfileTest(
+ // subsequent profile and mca ids should check for the existence of multiple connectors
+ context(
+ "Create another business profile and merchant connector account if MULTIPLE_CONNECTORS flag is true",
+ () => {
+ it("Create business profile", () => {
+ utils.createBusinessProfile(
fixtures.businessProfile.bpCreate,
globalState,
- "profile" + i
+ { nextConnector: true }
);
- cy.createConnectorCallTest(
+ });
+
+ it("Create merchant connector account", () => {
+ utils.createMerchantConnectorAccount(
"payment_processor",
fixtures.createConnectorBody,
- payment_methods_enabled,
globalState,
- `profile${i}`,
- `merchantConnector${i}`
+ payment_methods_enabled,
+ { nextConnector: true }
);
- }
- } else {
- cy.log(
- "Multiple connectors not enabled. Skipping creation of multiple profiles and respective MCAs"
- );
+ });
}
- });
+ );
});
diff --git a/cypress-tests/cypress/e2e/PaymentTest/00020-MandatesUsingNTID.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00020-MandatesUsingNTIDProxy.cy.js
similarity index 100%
rename from cypress-tests/cypress/e2e/PaymentTest/00020-MandatesUsingNTID.cy.js
rename to cypress-tests/cypress/e2e/PaymentTest/00020-MandatesUsingNTIDProxy.cy.js
diff --git a/cypress-tests/cypress/e2e/PaymentTest/00023-PaymentMethods.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00023-PaymentMethods.cy.js
index 9dc73f6223e..28262d025c4 100644
--- a/cypress-tests/cypress/e2e/PaymentTest/00023-PaymentMethods.cy.js
+++ b/cypress-tests/cypress/e2e/PaymentTest/00023-PaymentMethods.cy.js
@@ -82,4 +82,23 @@ describe("Payment Methods Tests", () => {
cy.setDefaultPaymentMethodTest(globalState);
});
});
+
+ context("Delete payment method for customer", () => {
+ it("Create customer", () => {
+ cy.createCustomerCallTest(fixtures.customerCreateBody, globalState);
+ });
+
+ it("Create Payment Method", () => {
+ const data = getConnectorDetails("commons")["card_pm"]["PaymentMethod"];
+ cy.createPaymentMethodTest(globalState, data);
+ });
+
+ it("List PM for customer", () => {
+ cy.listCustomerPMCallTest(globalState);
+ });
+
+ it("Delete Payment Method for a customer", () => {
+ cy.deletePaymentMethodTest(globalState);
+ });
+ });
});
diff --git a/cypress-tests/cypress/e2e/PaymentTest/00024-ConnectorAgnostic.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00024-ConnectorAgnosticNTID.cy.js
similarity index 54%
rename from cypress-tests/cypress/e2e/PaymentTest/00024-ConnectorAgnostic.cy.js
rename to cypress-tests/cypress/e2e/PaymentTest/00024-ConnectorAgnosticNTID.cy.js
index c5fddfdd5bf..db5757e464c 100644
--- a/cypress-tests/cypress/e2e/PaymentTest/00024-ConnectorAgnostic.cy.js
+++ b/cypress-tests/cypress/e2e/PaymentTest/00024-ConnectorAgnosticNTID.cy.js
@@ -5,6 +5,32 @@ import getConnectorDetails, * as utils from "../PaymentUtils/Utils";
let globalState;
+/*
+Flow:
+- Create Business Profile with connector agnostic feature disabled
+- Create Merchant Connector Account and Customer
+- Make a Payment
+- List Payment Method for Customer using Client Secret (will get PMID)
+
+- Create Business Profile with connector agnostic feature enabled
+- Create Merchant Connector Account
+- Create Payment Intent
+- List Payment Method for Customer -- Empty list; i.e., no payment method should be listed
+- Confirm Payment with PMID from previous step (should fail as Connector Mandate ID is not present in the newly created Profile)
+
+
+- Create Business Profile with connector agnostic feature enabled
+- Create Merchant Connector Account and Customer
+- Make a Payment
+- List Payment Method for Customer using Client Secret (will get PMID)
+
+- Create Business Profile with connector agnostic feature enabled
+- Create Merchant Connector Account
+- Create Payment Intent
+- List Payment Method for Customer using Client Secret (will get PMID which is same as the one from previous step along with Payment Token)
+- Confirm Payment with PMID from previous step (should pass as NTID is present in the DB)
+*/
+
describe("Connector Agnostic Tests", () => {
before("seed global state", () => {
cy.task("getGlobalState").then((state) => {
@@ -26,19 +52,19 @@ describe("Connector Agnostic Tests", () => {
}
});
- it("Create Business Profile", () => {
- cy.createBusinessProfileTest(
+ it("Create business profile", () => {
+ utils.createBusinessProfile(
fixtures.businessProfile.bpCreate,
globalState
);
});
- it("connector-create-call-test", () => {
- cy.createConnectorCallTest(
+ it("Create merchant connector account", () => {
+ utils.createMerchantConnectorAccount(
"payment_processor",
fixtures.createConnectorBody,
- payment_methods_enabled,
- globalState
+ globalState,
+ payment_methods_enabled
);
});
@@ -78,24 +104,24 @@ describe("Connector Agnostic Tests", () => {
cy.listCustomerPMByClientSecret(globalState);
});
- it("Create Business Profile", () => {
- cy.createBusinessProfileTest(
+ it("Create business profile", () => {
+ utils.createBusinessProfile(
fixtures.businessProfile.bpCreate,
globalState
);
});
- it("connector-create-call-test", () => {
- cy.createConnectorCallTest(
+ it("Create merchant connector account", () => {
+ utils.createMerchantConnectorAccount(
"payment_processor",
fixtures.createConnectorBody,
- payment_methods_enabled,
- globalState
+ globalState,
+ payment_methods_enabled
);
});
it("Enable Connector Agnostic for Business Profile", () => {
- cy.UpdateBusinessProfileTest(
+ utils.updateBusinessProfile(
fixtures.businessProfile.bpUpdate,
true, // is_connector_agnostic_enabled
false, // collect_billing_address_from_wallet_connector
@@ -126,6 +152,80 @@ describe("Connector Agnostic Tests", () => {
it("List Payment Method for Customer", () => {
cy.listCustomerPMByClientSecret(globalState);
});
+
+ it("Confirm No 3DS MIT (PMID)", () => {
+ const data = getConnectorDetails(globalState.get("connectorId"))[
+ "card_pm"
+ ]["MITAutoCapture"];
+ const commonData = getConnectorDetails(globalState.get("commons"))[
+ "card_pm"
+ ]["MITAutoCapture"];
+
+ const newData = {
+ ...data,
+ Response: utils.getConnectorFlowDetails(
+ data,
+ commonData,
+ "ResponseCustom"
+ ),
+ };
+
+ cy.mitUsingPMId(
+ fixtures.pmIdConfirmBody,
+ newData,
+ 7000,
+ true,
+ "automatic",
+ globalState
+ );
+ });
+
+ it("Create Payment Intent", () => {
+ const data = getConnectorDetails(globalState.get("connectorId"))[
+ "card_pm"
+ ]["PaymentIntentOffSession"];
+
+ cy.createPaymentIntentTest(
+ fixtures.createPaymentBody,
+ data,
+ "no_three_ds",
+ "automatic",
+ globalState
+ );
+
+ if (shouldContinue)
+ shouldContinue = utils.should_continue_further(data);
+ });
+
+ it("List Payment Method for Customer", () => {
+ cy.listCustomerPMByClientSecret(globalState);
+ });
+
+ it("Confirm No 3DS MIT (Token)", () => {
+ const data = getConnectorDetails(globalState.get("connectorId"))[
+ "card_pm"
+ ]["SaveCardConfirmAutoCaptureOffSession"];
+ const commonData = getConnectorDetails(globalState.get("commons"))[
+ "card_pm"
+ ]["SaveCardConfirmAutoCaptureOffSession"];
+
+ const newData = {
+ ...data,
+ Response: utils.getConnectorFlowDetails(
+ data,
+ commonData,
+ "ResponseCustom"
+ ),
+ };
+ cy.saveCardConfirmCallTest(
+ fixtures.saveCardConfirmBody,
+ newData,
+ globalState
+ );
+
+ if (shouldContinue)
+ shouldContinue = utils.should_continue_further(data);
+ });
}
);
@@ -138,19 +238,19 @@ describe("Connector Agnostic Tests", () => {
}
});
- it("Create Business Profile", () => {
- cy.createBusinessProfileTest(
+ it("Create business profile", () => {
+ utils.createBusinessProfile(
fixtures.businessProfile.bpCreate,
globalState
);
});
- it("connector-create-call-test", () => {
- cy.createConnectorCallTest(
+ it("Create merchant connector account", () => {
+ utils.createMerchantConnectorAccount(
"payment_processor",
fixtures.createConnectorBody,
- payment_methods_enabled,
- globalState
+ globalState,
+ payment_methods_enabled
);
});
@@ -159,7 +259,7 @@ describe("Connector Agnostic Tests", () => {
});
it("Enable Connector Agnostic for Business Profile", () => {
- cy.UpdateBusinessProfileTest(
+ utils.updateBusinessProfile(
fixtures.businessProfile.bpUpdate,
true, // is_connector_agnostic_enabled
false, // collect_billing_address_from_wallet_connector
@@ -200,24 +300,24 @@ describe("Connector Agnostic Tests", () => {
cy.listCustomerPMByClientSecret(globalState);
});
- it("Create Business Profile", () => {
- cy.createBusinessProfileTest(
+ it("Create business profile", () => {
+ utils.createBusinessProfile(
fixtures.businessProfile.bpCreate,
globalState
);
});
- it("connector-create-call-test", () => {
- cy.createConnectorCallTest(
+ it("Create merchant connector account", () => {
+ utils.createMerchantConnectorAccount(
"payment_processor",
fixtures.createConnectorBody,
- payment_methods_enabled,
- globalState
+ globalState,
+ payment_methods_enabled
);
});
it("Enable Connector Agnostic for Business Profile", () => {
- cy.UpdateBusinessProfileTest(
+ utils.updateBusinessProfile(
fixtures.businessProfile.bpUpdate,
true, // is_connector_agnostic_enabled
false, // collect_billing_address_from_wallet_connector
@@ -247,5 +347,54 @@ describe("Connector Agnostic Tests", () => {
it("List Payment Method for Customer", () => {
cy.listCustomerPMByClientSecret(globalState);
});
+
+ it("Confirm No 3DS MIT (PMID)", () => {
+ const data = getConnectorDetails(globalState.get("connectorId"))[
+ "card_pm"
+ ]["MITAutoCapture"];
+
+ cy.mitUsingPMId(
+ fixtures.pmIdConfirmBody,
+ data,
+ 7000,
+ true,
+ "automatic",
+ globalState
+ );
+ });
+
+ it("Create Payment Intent", () => {
+ const data = getConnectorDetails(globalState.get("connectorId"))[
+ "card_pm"
+ ]["PaymentIntentOffSession"];
+
+ cy.createPaymentIntentTest(
+ fixtures.createPaymentBody,
+ data,
+ "no_three_ds",
+ "automatic",
+ globalState
+ );
+
+ if (shouldContinue) shouldContinue = utils.should_continue_further(data);
+ });
+
+ it("List Payment Method for Customer", () => {
+ cy.listCustomerPMByClientSecret(globalState);
+ });
+
+ it("Confirm No 3DS MIT (Token)", () => {
+ const data = getConnectorDetails(globalState.get("connectorId"))[
+ "card_pm"
+ ]["SaveCardConfirmAutoCaptureOffSession"];
+
+ cy.saveCardConfirmCallTest(
+ fixtures.saveCardConfirmBody,
+ data,
+ globalState
+ );
+
+ if (shouldContinue) shouldContinue = utils.should_continue_further(data);
+ });
});
});
diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js b/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js
index 4ac15ec28bd..56efbf1f6f2 100644
--- a/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js
+++ b/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js
@@ -242,7 +242,7 @@ export const connectorDetails = {
},
},
},
- VoidAfterConfirm: {
+ VoidAfterConfirm: getCustomExchange({
Request: {},
Response: {
status: 200,
@@ -256,7 +256,7 @@ export const connectorDetails = {
status: "cancelled",
},
},
- },
+ }),
Refund: {
Request: {
currency: "USD",
@@ -789,7 +789,7 @@ export const connectorDetails = {
},
},
bank_redirect_pm: {
- PaymentIntent: getCustomExchange({
+ PaymentIntent: {
Request: {
currency: "EUR",
},
@@ -799,7 +799,7 @@ export const connectorDetails = {
status: "requires_payment_method",
},
},
- }),
+ },
Ideal: {
Request: {
payment_method: "bank_redirect",
diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Commons.js b/cypress-tests/cypress/e2e/PaymentUtils/Commons.js
index 86e41c07639..85718d8f9ba 100644
--- a/cypress-tests/cypress/e2e/PaymentUtils/Commons.js
+++ b/cypress-tests/cypress/e2e/PaymentUtils/Commons.js
@@ -149,9 +149,7 @@ with `getCustomExchange`, if 501 response is expected, there is no need to pass
// Const to get default PaymentExchange object
const getDefaultExchange = () => ({
- Request: {
- currency: "EUR",
- },
+ Request: {},
Response: {
status: 501,
body: {
@@ -1012,6 +1010,16 @@ export const connectorDetails = {
Request: {
setup_future_usage: "off_session",
},
+ ResponseCustom: {
+ status: 400,
+ body: {
+ error: {
+ message:
+ "No eligible connector was found for the current payment method configuration",
+ type: "invalid_request",
+ },
+ },
+ },
}),
SaveCardConfirmManualCaptureOffSession: getCustomExchange({
Request: {
@@ -1465,6 +1473,25 @@ export const connectorDetails = {
},
},
}),
+ MITAutoCapture: getCustomExchange({
+ Request: {},
+ Response: {
+ status: 200,
+ body: {
+ status: "succeeded",
+ },
+ },
+ ResponseCustom: {
+ status: 400,
+ body: {
+ error: {
+ message:
+ "No eligible connector was found for the current payment method configuration",
+ type: "invalid_request",
+ },
+ },
+ },
+ }),
PaymentWithoutBilling: {
Request: {
currency: "USD",
diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js b/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js
index 98d8e4c1acb..b98973250e9 100644
--- a/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js
+++ b/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js
@@ -1,3 +1,8 @@
+import {
+ connectorDetails as commonConnectorDetails,
+ getCustomExchange,
+} from "./Commons";
+
const successfulNo3DSCardDetails = {
card_number: "4242424242424242",
card_exp_month: "01",
@@ -631,20 +636,14 @@ export const connectorDetails = {
},
},
},
- MITAutoCapture: {
+ MITAutoCapture: getCustomExchange({
Configs: {
CONNECTOR_CREDENTIAL: {
value: "connector_1",
},
},
- Request: {},
- Response: {
- status: 200,
- body: {
- status: "succeeded",
- },
- },
- },
+ ...commonConnectorDetails.card_pm.MITAutoCapture,
+ }),
MITManualCapture: {
Configs: {
CONNECTOR_CREDENTIAL: {
diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Stripe.js b/cypress-tests/cypress/e2e/PaymentUtils/Stripe.js
index d75fcf6877b..b8dd275afae 100644
--- a/cypress-tests/cypress/e2e/PaymentUtils/Stripe.js
+++ b/cypress-tests/cypress/e2e/PaymentUtils/Stripe.js
@@ -1,4 +1,8 @@
-import { cardRequiredField, getCustomExchange } from "./Commons";
+import {
+ cardRequiredField,
+ connectorDetails as commonConnectorDetails,
+ getCustomExchange,
+} from "./Commons";
const successfulNo3DSCardDetails = {
card_number: "4242424242424242",
@@ -118,6 +122,10 @@ const requiredFields = {
};
export const connectorDetails = {
+ multi_credential_config: {
+ specName: ["connectorAgnostic"],
+ value: "connector_2",
+ },
card_pm: {
PaymentIntent: {
Request: {
@@ -134,6 +142,12 @@ export const connectorDetails = {
},
},
PaymentIntentOffSession: {
+ Configs: {
+ CONNECTOR_CREDENTIAL: {
+ specName: ["connectorAgnostic"],
+ value: "connector_2",
+ },
+ },
Request: {
currency: "USD",
customer_acceptance: null,
@@ -530,15 +544,15 @@ export const connectorDetails = {
},
},
},
- MITAutoCapture: {
- Request: {},
- Response: {
- status: 200,
- body: {
- status: "succeeded",
+ MITAutoCapture: getCustomExchange({
+ Configs: {
+ CONNECTOR_CREDENTIAL: {
+ specName: ["connectorAgnostic"],
+ value: "connector_2",
},
},
- },
+ ...commonConnectorDetails.card_pm.MITAutoCapture,
+ }),
MITManualCapture: {
Request: {},
Response: {
@@ -668,6 +682,12 @@ export const connectorDetails = {
},
},
SaveCardUseNo3DSAutoCaptureOffSession: {
+ Configs: {
+ CONNECTOR_CREDENTIAL: {
+ specName: ["connectorAgnostic"],
+ value: "connector_2",
+ },
+ },
Request: {
payment_method: "card",
payment_method_type: "debit",
@@ -715,6 +735,12 @@ export const connectorDetails = {
},
},
SaveCardConfirmAutoCaptureOffSession: {
+ Configs: {
+ CONNECTOR_CREDENTIAL: {
+ specName: ["connectorAgnostic"],
+ value: "connector_2",
+ },
+ },
Request: {
setup_future_usage: "off_session",
},
diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Utils.js b/cypress-tests/cypress/e2e/PaymentUtils/Utils.js
index 3b4c9e5decf..72bd6451347 100644
--- a/cypress-tests/cypress/e2e/PaymentUtils/Utils.js
+++ b/cypress-tests/cypress/e2e/PaymentUtils/Utils.js
@@ -1,4 +1,4 @@
-import { validateConfig } from "../../utils/featureFlags.js";
+import { execConfig, validateConfig } from "../../utils/featureFlags.js";
import { connectorDetails as adyenConnectorDetails } from "./Adyen.js";
import { connectorDetails as bankOfAmericaConnectorDetails } from "./BankOfAmerica.js";
@@ -65,8 +65,11 @@ export function getConnectorFlowDetails(connectorData, commonData, key) {
}
function mergeDetails(connectorId) {
- const connectorData = getValueByKey(connectorDetails, connectorId);
- const fallbackData = getValueByKey(connectorDetails, "commons");
+ const connectorData = getValueByKey(
+ connectorDetails,
+ connectorId
+ ).authDetails;
+ const fallbackData = getValueByKey(connectorDetails, "commons").authDetails;
// Merge data, prioritizing connectorData and filling missing data from fallbackData
const mergedDetails = mergeConnectorDetails(connectorData, fallbackData);
return mergedDetails;
@@ -99,7 +102,16 @@ function mergeConnectorDetails(source, fallback) {
return merged;
}
-export function getValueByKey(jsonObject, key) {
+export function handleMultipleConnectors(keys) {
+ return {
+ MULTIPLE_CONNECTORS: {
+ status: true,
+ count: keys.length,
+ },
+ };
+}
+
+export function getValueByKey(jsonObject, key, keyNumber = 0) {
const data =
typeof jsonObject === "string" ? JSON.parse(jsonObject) : jsonObject;
@@ -108,7 +120,7 @@ export function getValueByKey(jsonObject, key) {
if (typeof data[key].connector_account_details === "undefined") {
const keys = Object.keys(data[key]);
- for (let i = 0; i < keys.length; i++) {
+ for (let i = keyNumber; i < keys.length; i++) {
const currentItem = data[key][keys[i]];
if (
@@ -117,20 +129,23 @@ export function getValueByKey(jsonObject, key) {
"connector_account_details"
)
) {
- Cypress.env("MULTIPLE_CONNECTORS", {
- status: true,
- count: keys.length,
- });
-
- return currentItem;
+ // Return state update instead of setting directly
+ return {
+ authDetails: currentItem,
+ stateUpdate: handleMultipleConnectors(keys),
+ };
}
}
}
-
- return data[key];
- } else {
- return null;
+ return {
+ authDetails: data[key],
+ stateUpdate: null,
+ };
}
+ return {
+ authDetails: null,
+ stateUpdate: null,
+ };
}
export const should_continue_further = (data) => {
@@ -183,3 +198,114 @@ export function defaultErrorHandler(response, response_data) {
}
}
}
+
+export function extractIntegerAtEnd(str) {
+ // Match one or more digits at the end of the string
+ const match = str.match(/(\d+)$/);
+ return match ? parseInt(match[0], 10) : 0;
+}
+
+// Common helper function to check if operation should proceed
+function shouldProceedWithOperation(multipleConnector, multipleConnectors) {
+ return !(
+ multipleConnector?.nextConnector === true &&
+ (multipleConnectors?.status === false ||
+ typeof multipleConnectors === "undefined")
+ );
+}
+
+// Helper to get connector configuration
+function getConnectorConfig(
+ globalState,
+ multipleConnector = { nextConnector: false }
+) {
+ const multipleConnectors = globalState.get("MULTIPLE_CONNECTORS");
+ const mcaConfig = getConnectorDetails(globalState.get("connectorId"));
+
+ return {
+ config: {
+ CONNECTOR_CREDENTIAL:
+ multipleConnector?.nextConnector && multipleConnectors?.status
+ ? multipleConnector
+ : mcaConfig?.multi_credential_config || multipleConnector,
+ },
+ multipleConnectors,
+ };
+}
+
+// Simplified createBusinessProfile
+export function createBusinessProfile(
+ createBusinessProfileBody,
+ globalState,
+ multipleConnector = { nextConnector: false }
+) {
+ const { config, multipleConnectors } = getConnectorConfig(
+ globalState,
+ multipleConnector
+ );
+ const { profilePrefix } = execConfig(config);
+
+ if (shouldProceedWithOperation(multipleConnector, multipleConnectors)) {
+ cy.createBusinessProfileTest(
+ createBusinessProfileBody,
+ globalState,
+ profilePrefix
+ );
+ }
+}
+
+// Simplified createMerchantConnectorAccount
+export function createMerchantConnectorAccount(
+ paymentType,
+ createMerchantConnectorAccountBody,
+ globalState,
+ paymentMethodsEnabled,
+ multipleConnector = { nextConnector: false }
+) {
+ const { config, multipleConnectors } = getConnectorConfig(
+ globalState,
+ multipleConnector
+ );
+ const { profilePrefix, merchantConnectorPrefix } = execConfig(config);
+
+ if (shouldProceedWithOperation(multipleConnector, multipleConnectors)) {
+ cy.createConnectorCallTest(
+ paymentType,
+ createMerchantConnectorAccountBody,
+ paymentMethodsEnabled,
+ globalState,
+ profilePrefix,
+ merchantConnectorPrefix
+ );
+ }
+}
+
+export function updateBusinessProfile(
+ updateBusinessProfileBody,
+ is_connector_agnostic_enabled,
+ collect_billing_address_from_wallet_connector,
+ collect_shipping_address_from_wallet_connector,
+ always_collect_billing_address_from_wallet_connector,
+ always_collect_shipping_address_from_wallet_connector,
+ globalState
+) {
+ const multipleConnectors = globalState.get("MULTIPLE_CONNECTORS");
+ cy.log(`MULTIPLE_CONNECTORS: ${JSON.stringify(multipleConnectors)}`);
+
+ // Get MCA config
+ const mcaConfig = getConnectorDetails(globalState.get("connectorId"));
+ const { profilePrefix } = execConfig({
+ CONNECTOR_CREDENTIAL: mcaConfig?.multi_credential_config,
+ });
+
+ cy.UpdateBusinessProfileTest(
+ updateBusinessProfileBody,
+ is_connector_agnostic_enabled,
+ collect_billing_address_from_wallet_connector,
+ collect_shipping_address_from_wallet_connector,
+ always_collect_billing_address_from_wallet_connector,
+ always_collect_shipping_address_from_wallet_connector,
+ globalState,
+ profilePrefix
+ );
+}
diff --git a/cypress-tests/cypress/e2e/PaymentUtils/WorldPay.js b/cypress-tests/cypress/e2e/PaymentUtils/WorldPay.js
index 557e4b23ee4..a58bbb22f81 100644
--- a/cypress-tests/cypress/e2e/PaymentUtils/WorldPay.js
+++ b/cypress-tests/cypress/e2e/PaymentUtils/WorldPay.js
@@ -1,3 +1,5 @@
+import { getCustomExchange } from "./Commons";
+
const billing = {
address: {
line1: "1467",
@@ -195,7 +197,7 @@ export const connectorDetails = {
},
},
},
- Void: {
+ Void: getCustomExchange({
Request: {},
Response: {
status: 200,
@@ -211,7 +213,7 @@ export const connectorDetails = {
code: "IR_16",
},
},
- },
+ }),
VoidAfterConfirm: {
Request: {},
Response: {
diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.js
index 28590abd8b6..6135f26934e 100644
--- a/cypress-tests/cypress/support/commands.js
+++ b/cypress-tests/cypress/support/commands.js
@@ -25,7 +25,11 @@
// Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... })
// commands.js or your custom support file
-import { defaultErrorHandler, getValueByKey } from "../e2e/PaymentUtils/Utils";
+import {
+ defaultErrorHandler,
+ extractIntegerAtEnd,
+ getValueByKey,
+} from "../e2e/PaymentUtils/Utils";
import { execConfig, validateConfig } from "../utils/featureFlags";
import * as RequestBodyUtils from "../utils/RequestBodyUtils";
import { handleRedirection } from "./redirectionHandler";
@@ -197,15 +201,15 @@ Cypress.Commands.add(
Cypress.Commands.add(
"createBusinessProfileTest",
- (createBusinessProfile, globalState, profile_prefix = "profile") => {
- const api_key = globalState.get("adminApiKey");
- const base_url = globalState.get("baseUrl");
- const connector_id = globalState.get("connectorId");
- const merchant_id = globalState.get("merchantId");
- const profile_name = `${connector_id}_${profile_prefix}_${Math.random().toString(36).substring(7)}`;
- const url = `${base_url}/account/${merchant_id}/business_profile`;
+ (createBusinessProfile, globalState, profilePrefix = "profile") => {
+ const apiKey = globalState.get("adminApiKey");
+ const baseUrl = globalState.get("baseUrl");
+ const connectorId = globalState.get("connectorId");
+ const merchantId = globalState.get("merchantId");
+ const profileName = `${profilePrefix}_${RequestBodyUtils.generateRandomString(connectorId)}`;
+ const url = `${baseUrl}/account/${merchantId}/business_profile`;
- createBusinessProfile.profile_name = profile_name;
+ createBusinessProfile.profile_name = profileName;
cy.request({
method: "POST",
@@ -213,13 +217,14 @@ Cypress.Commands.add(
headers: {
Accept: "application/json",
"Content-Type": "application/json",
- "api-key": api_key,
+ "api-key": apiKey,
},
body: createBusinessProfile,
failOnStatusCode: false,
}).then((response) => {
logRequestId(response.headers["x-request-id"]);
- globalState.set(`${profile_prefix}Id`, response.body.profile_id);
+
+ globalState.set(`${profilePrefix}Id`, response.body.profile_id);
if (response.status === 200) {
expect(response.body.profile_id).to.not.to.be.null;
@@ -235,35 +240,39 @@ Cypress.Commands.add(
Cypress.Commands.add(
"UpdateBusinessProfileTest",
(
- updateBusinessProfile,
+ updateBusinessProfileBody,
is_connector_agnostic_mit_enabled,
collect_billing_details_from_wallet_connector,
collect_shipping_details_from_wallet_connector,
always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector,
- globalState
+ globalState,
+ profilePrefix = "profile"
) => {
- updateBusinessProfile.is_connector_agnostic_mit_enabled =
+ updateBusinessProfileBody.is_connector_agnostic_mit_enabled =
is_connector_agnostic_mit_enabled;
- updateBusinessProfile.collect_shipping_details_from_wallet_connector =
+ updateBusinessProfileBody.collect_shipping_details_from_wallet_connector =
collect_shipping_details_from_wallet_connector;
- updateBusinessProfile.collect_billing_details_from_wallet_connector =
+ updateBusinessProfileBody.collect_billing_details_from_wallet_connector =
collect_billing_details_from_wallet_connector;
- updateBusinessProfile.always_collect_billing_details_from_wallet_connector =
+ updateBusinessProfileBody.always_collect_billing_details_from_wallet_connector =
always_collect_billing_details_from_wallet_connector;
- updateBusinessProfile.always_collect_shipping_details_from_wallet_connector =
+ updateBusinessProfileBody.always_collect_shipping_details_from_wallet_connector =
always_collect_shipping_details_from_wallet_connector;
- const merchant_id = globalState.get("merchantId");
- const profile_id = globalState.get("profileId");
+
+ const apiKey = globalState.get("adminApiKey");
+ const merchantId = globalState.get("merchantId");
+ const profileId = globalState.get(`${profilePrefix}Id`);
+
cy.request({
method: "POST",
- url: `${globalState.get("baseUrl")}/account/${merchant_id}/business_profile/${profile_id}`,
+ url: `${globalState.get("baseUrl")}/account/${merchantId}/business_profile/${profileId}`,
headers: {
Accept: "application/json",
"Content-Type": "application/json",
- "api-key": globalState.get("adminApiKey"),
+ "api-key": apiKey,
},
- body: updateBusinessProfile,
+ body: updateBusinessProfileBody,
failOnStatusCode: false,
}).then((response) => {
logRequestId(response.headers["x-request-id"]);
@@ -433,7 +442,7 @@ Cypress.Commands.add(
// it is best to use then() to handle the response within the same block of code
cy.readFile(globalState.get("connectorAuthFilePath")).then(
(jsonContent) => {
- const authDetails = getValueByKey(
+ const { authDetails } = getValueByKey(
JSON.stringify(jsonContent),
connectorName
);
@@ -481,14 +490,14 @@ Cypress.Commands.add(
createConnectorBody,
payment_methods_enabled,
globalState,
- profile_prefix = "profile",
- mca_prefix = "merchantConnector"
+ profilePrefix = "profile",
+ mcaPrefix = "merchantConnector"
) => {
const api_key = globalState.get("adminApiKey");
const base_url = globalState.get("baseUrl");
const connector_id = globalState.get("connectorId");
const merchant_id = globalState.get("merchantId");
- const profile_id = globalState.get(`${profile_prefix}Id`);
+ const profile_id = globalState.get(`${profilePrefix}Id`);
const url = `${base_url}/account/${merchant_id}/connectors`;
createConnectorBody.connector_type = connectorType;
@@ -500,11 +509,20 @@ Cypress.Commands.add(
// it is best to use then() to handle the response within the same block of code
cy.readFile(globalState.get("connectorAuthFilePath")).then(
(jsonContent) => {
- const authDetails = getValueByKey(
+ const { authDetails, stateUpdate } = getValueByKey(
JSON.stringify(jsonContent),
- connector_id
+ connector_id,
+ extractIntegerAtEnd(profilePrefix)
);
+ if (stateUpdate) {
+ // cy.task("setGlobalState", stateUpdate);
+ globalState.set(
+ "MULTIPLE_CONNECTORS",
+ stateUpdate.MULTIPLE_CONNECTORS
+ );
+ }
+
createConnectorBody.connector_account_details =
authDetails.connector_account_details;
@@ -533,7 +551,7 @@ Cypress.Commands.add(
response.body.connector_name
);
globalState.set(
- `${mca_prefix}Id`,
+ `${mcaPrefix}Id`,
response.body.merchant_connector_id
);
} else {
@@ -566,7 +584,7 @@ Cypress.Commands.add(
// it is best to use then() to handle the response within the same block of code
cy.readFile(globalState.get("connectorAuthFilePath")).then(
(jsonContent) => {
- const authDetails = getValueByKey(
+ const { authDetails } = getValueByKey(
JSON.stringify(jsonContent),
`${connectorName}_payout`
);
@@ -678,9 +696,11 @@ Cypress.Commands.add(
const connector_id = globalState.get("connectorId");
const merchant_id = globalState.get("merchantId");
const merchant_connector_id = globalState.get("merchantConnectorId");
+ const connectorLabel = `updated_${RequestBodyUtils.generateRandomString(connector_id)}`;
const url = `${base_url}/account/${merchant_id}/connectors/${merchant_connector_id}`;
updateConnectorBody.connector_type = connectorType;
+ updateConnectorBody.connector_label = connectorLabel;
cy.request({
method: "POST",
@@ -700,7 +720,7 @@ Cypress.Commands.add(
expect(response.body.merchant_connector_id).to.equal(
merchant_connector_id
);
- expect(response.body.connector_label).to.equal("updated_connector_label");
+ expect(response.body.connector_label).to.equal(connectorLabel);
});
}
);
@@ -1037,8 +1057,8 @@ Cypress.Commands.add(
);
}
- const config_info = execConfig(validateConfig(configs));
- const profile_id = globalState.get(config_info.profile_id);
+ const configInfo = execConfig(validateConfig(configs));
+ const profile_id = globalState.get(`${configInfo.profilePrefix}Id`);
for (const key in reqData) {
createPaymentBody[key] = reqData[key];
@@ -1245,14 +1265,18 @@ Cypress.Commands.add("createPaymentMethodTest", (globalState, data) => {
});
});
-Cypress.Commands.add("deletePaymentMethodTest", (globalState, resData) => {
- const payment_method_id = globalState.get("paymentMethodId");
+Cypress.Commands.add("deletePaymentMethodTest", (globalState) => {
+ const apiKey = globalState.get("apiKey");
+ const baseUrl = globalState.get("baseUrl");
+ const paymentMethodId = globalState.get("paymentMethodId");
+ const url = `${baseUrl}/payment_methods/${paymentMethodId}`;
+
cy.request({
method: "DELETE",
- url: `${globalState.get("baseUrl")}/payment_methods/${payment_method_id}`,
+ url: url,
headers: {
Accept: "application/json",
- "api-key": globalState.get("apiKey"),
+ "api-key": apiKey,
},
failOnStatusCode: false,
}).then((response) => {
@@ -1260,10 +1284,16 @@ Cypress.Commands.add("deletePaymentMethodTest", (globalState, resData) => {
expect(response.headers["content-type"]).to.include("application/json");
if (response.status === 200) {
- expect(response.body.payment_method_id).to.equal(payment_method_id);
+ expect(response.body.payment_method_id).to.equal(paymentMethodId);
expect(response.body.deleted).to.be.true;
+ } else if (response.status === 500 && baseUrl.includes("localhost")) {
+ // delete payment method api endpoint requires tartarus (hyperswitch card vault) to be set up since it makes a call to the locker service to delete the payment method
+ expect(response.body.error.code).to.include("HE_00");
+ expect(response.body.error.message).to.include("Something went wrong");
} else {
- defaultErrorHandler(response, resData);
+ throw new Error(
+ `Payment Method Delete Call Failed with error message: ${response.body.error.message}`
+ );
}
});
});
@@ -1271,6 +1301,7 @@ Cypress.Commands.add("deletePaymentMethodTest", (globalState, resData) => {
Cypress.Commands.add("setDefaultPaymentMethodTest", (globalState) => {
const payment_method_id = globalState.get("paymentMethodId");
const customer_id = globalState.get("customerId");
+
cy.request({
method: "POST",
url: `${globalState.get("baseUrl")}/customers/${customer_id}/payment_methods/${payment_method_id}/default`,
@@ -1306,10 +1337,10 @@ Cypress.Commands.add(
const baseUrl = globalState.get("baseUrl");
const configInfo = execConfig(validateConfig(configs));
const merchantConnectorId = globalState.get(
- configInfo.merchant_connector_id
+ `${configInfo.merchantConnectorPrefix}Id`
);
const paymentIntentID = globalState.get("paymentID");
- const profileId = globalState.get(configInfo.profile_id);
+ const profileId = globalState.get(`${configInfo.profilePrefix}Id`);
const url = `${baseUrl}/payments/${paymentIntentID}/confirm`;
confirmBody.client_secret = globalState.get("clientSecret");
@@ -1424,10 +1455,10 @@ Cypress.Commands.add(
Response: resData,
} = data || {};
- const config_info = execConfig(validateConfig(configs));
+ const configInfo = execConfig(validateConfig(configs));
const connectorId = globalState.get("connectorId");
const paymentIntentId = globalState.get("paymentID");
- const profile_id = globalState.get(config_info.profile_id);
+ const profile_id = globalState.get(`${configInfo.profilePrefix}Id`);
for (const key in reqData) {
confirmBody[key] = reqData[key];
@@ -1532,9 +1563,9 @@ Cypress.Commands.add(
Response: resData,
} = data || {};
- const config_info = execConfig(validateConfig(configs));
+ const configInfo = execConfig(validateConfig(configs));
const paymentIntentID = globalState.get("paymentID");
- const profile_id = globalState.get(config_info.profile_id);
+ const profile_id = globalState.get(`${configInfo.profilePrefix}Id`);
for (const key in reqData) {
confirmBody[key] = reqData[key];
@@ -1616,9 +1647,9 @@ Cypress.Commands.add(
Response: resData,
} = data || {};
- const config_info = execConfig(validateConfig(configs));
+ const configInfo = execConfig(validateConfig(configs));
const paymentId = globalState.get("paymentID");
- const profile_id = globalState.get(config_info.profile_id);
+ const profile_id = globalState.get(`${configInfo.profilePrefix}Id`);
for (const key in reqData) {
confirmBody[key] = reqData[key];
@@ -1692,11 +1723,11 @@ Cypress.Commands.add(
Response: resData,
} = data || {};
- const config_info = execConfig(validateConfig(configs));
+ const configInfo = execConfig(validateConfig(configs));
const merchant_connector_id = globalState.get(
- config_info.merchant_connector_id
+ `${configInfo.merchantConnectorPrefix}Id`
);
- const profile_id = globalState.get(config_info.profile_id);
+ const profile_id = globalState.get(`${configInfo.profilePrefix}Id`);
createConfirmPaymentBody.authentication_type = authentication_type;
createConfirmPaymentBody.capture_method = capture_method;
@@ -1811,12 +1842,12 @@ Cypress.Commands.add(
Response: resData,
} = data || {};
- const config_info = execConfig(validateConfig(configs));
+ const configInfo = execConfig(validateConfig(configs));
const merchant_connector_id = globalState.get(
- config_info.merchant_connector_id
+ `${configInfo.merchantConnectorPrefix}Id`
);
const paymentIntentID = globalState.get("paymentID");
- const profile_id = globalState.get(config_info.profile_id);
+ const profile_id = globalState.get(`${configInfo.profilePrefix}Id`);
if (reqData.setup_future_usage === "on_session") {
saveCardConfirmBody.card_cvc = reqData.payment_method_data.card.card_cvc;
@@ -1920,9 +1951,9 @@ Cypress.Commands.add(
(requestBody, data, amount_to_capture, globalState) => {
const { Configs: configs = {}, Response: resData } = data || {};
- const config_info = execConfig(validateConfig(configs));
+ const configInfo = execConfig(validateConfig(configs));
const payment_id = globalState.get("paymentID");
- const profile_id = globalState.get(config_info.profile_id);
+ const profile_id = globalState.get(`${configInfo.profilePrefix}Id`);
requestBody.amount_to_capture = amount_to_capture;
requestBody.profile_id = profile_id;
@@ -1955,9 +1986,9 @@ Cypress.Commands.add(
Cypress.Commands.add("voidCallTest", (requestBody, data, globalState) => {
const { Configs: configs = {}, Response: resData } = data || {};
- const config_info = execConfig(validateConfig(configs));
+ const configInfo = execConfig(validateConfig(configs));
const payment_id = globalState.get("paymentID");
- const profile_id = globalState.get(config_info.profile_id);
+ const profile_id = globalState.get(`${configInfo.profilePrefix}Id`);
requestBody.profile_id = profile_id;
@@ -1989,9 +2020,9 @@ Cypress.Commands.add(
(globalState, data, autoretries = false, attempt = 1) => {
const { Configs: configs = {} } = data || {};
- const config_info = execConfig(validateConfig(configs));
+ const configInfo = execConfig(validateConfig(configs));
const merchant_connector_id = globalState.get(
- config_info.merchant_connector_id
+ `${configInfo.merchantConnectorPrefix}Id`
);
const payment_id = globalState.get("paymentID");
@@ -2138,10 +2169,10 @@ Cypress.Commands.add(
Response: resData,
} = data || {};
- const config_info = execConfig(validateConfig(configs));
- const profile_id = globalState.get(config_info.profile_id);
+ const configInfo = execConfig(validateConfig(configs));
+ const profile_id = globalState.get(`${configInfo.profilePrefix}Id`);
const merchant_connector_id = globalState.get(
- config_info.merchant_connector_id
+ `${configInfo.merchantConnectorPrefix}Id`
);
for (const key in reqData) {
@@ -2261,15 +2292,15 @@ Cypress.Commands.add(
Request: reqData,
Response: resData,
} = data || {};
- const config_info = execConfig(validateConfig(configs));
- const profile_id = globalState.get(config_info.profile_id);
+ const configInfo = execConfig(validateConfig(configs));
+ const profile_id = globalState.get(`${configInfo.profilePrefix}Id`);
for (const key in reqData) {
requestBody[key] = reqData[key];
}
const merchant_connector_id = globalState.get(
- config_info.merchant_connector_id
+ `${configInfo.merchantConnectorPrefix}Id`
);
requestBody.amount = amount;
@@ -2375,34 +2406,54 @@ Cypress.Commands.add(
Response: resData,
} = data || {};
+ const configInfo = execConfig(validateConfig(configs));
+ const profileId = globalState.get(`${configInfo.profilePrefix}Id`);
+
+ const apiKey = globalState.get("apiKey");
+ const baseUrl = globalState.get("baseUrl");
+ const customerId = globalState.get("customerId");
+ const paymentMethodId = globalState.get("paymentMethodId");
+ const url = `${baseUrl}/payments`;
+
for (const key in reqData) {
requestBody[key] = reqData[key];
}
- const configInfo = execConfig(validateConfig(configs));
- const profileId = globalState.get(configInfo.profile_id);
-
requestBody.amount = amount;
requestBody.capture_method = capture_method;
requestBody.confirm = confirm;
- requestBody.customer_id = globalState.get("customerId");
+ requestBody.customer_id = customerId;
requestBody.profile_id = profileId;
- requestBody.recurring_details.data = globalState.get("paymentMethodId");
+ requestBody.recurring_details.data = paymentMethodId;
cy.request({
method: "POST",
- url: `${globalState.get("baseUrl")}/payments`,
+ url: url,
headers: {
"Content-Type": "application/json",
- "api-key": globalState.get("apiKey"),
+ "api-key": apiKey,
},
failOnStatusCode: false,
body: requestBody,
}).then((response) => {
logRequestId(response.headers["x-request-id"]);
expect(response.headers["content-type"]).to.include("application/json");
+
if (response.status === 200) {
globalState.set("paymentID", response.body.payment_id);
+
+ expect(response.body.payment_method_id, "payment_method_id").to.include(
+ "pm_"
+ ).and.to.not.be.null;
+ expect(
+ response.body.connector_transaction_id,
+ "connector_transaction_id"
+ ).to.not.be.null;
+ expect(
+ response.body.payment_method_status,
+ "payment_method_status"
+ ).to.equal("active");
+
if (response.body.capture_method === "automatic") {
if (response.body.authentication_type === "three_ds") {
expect(response.body)
@@ -2462,7 +2513,7 @@ Cypress.Commands.add(
Response: resData,
} = data || {};
const configInfo = execConfig(validateConfig(configs));
- const profileId = globalState.get(configInfo.profile_id);
+ const profileId = globalState.get(`${configInfo.profilePrefix}Id`);
for (const key in reqData) {
requestBody[key] = reqData[key];
@@ -2710,6 +2761,7 @@ Cypress.Commands.add("listCustomerPMCallTest", (globalState) => {
Cypress.Commands.add("listCustomerPMByClientSecret", (globalState) => {
const clientSecret = globalState.get("clientSecret");
+
cy.request({
method: "GET",
url: `${globalState.get("baseUrl")}/customers/payment_methods?client_secret=${clientSecret}`,
diff --git a/cypress-tests/cypress/utils/RequestBodyUtils.js b/cypress-tests/cypress/utils/RequestBodyUtils.js
index 69edff05ca7..9b9015cad83 100644
--- a/cypress-tests/cypress/utils/RequestBodyUtils.js
+++ b/cypress-tests/cypress/utils/RequestBodyUtils.js
@@ -10,7 +10,7 @@ export const setApiKey = (requestBody, apiKey) => {
requestBody["connector_account_details"]["api_key"] = apiKey;
};
-export const generateRandomString = (prefix = "cypress_merchant_GHAction_") => {
+export const generateRandomString = (prefix = "cyMerchant") => {
const uuidPart = "xxxxxxxx";
const randomString = uuidPart.replace(/[xy]/g, function (c) {
@@ -19,7 +19,7 @@ export const generateRandomString = (prefix = "cypress_merchant_GHAction_") => {
return v.toString(16);
});
- return prefix + randomString;
+ return `${prefix}_${randomString}`;
};
export const setMerchantId = (merchantCreateBody, merchantId) => {
diff --git a/cypress-tests/cypress/utils/featureFlags.js b/cypress-tests/cypress/utils/featureFlags.js
index 7140aee3af7..6d8599820f7 100644
--- a/cypress-tests/cypress/utils/featureFlags.js
+++ b/cypress-tests/cypress/utils/featureFlags.js
@@ -2,14 +2,6 @@
const config_fields = ["CONNECTOR_CREDENTIAL", "DELAY", "TRIGGER_SKIP"];
const DEFAULT_CONNECTOR = "connector_1";
-const DEFAULT_CREDENTIALS = {
- profile_id: "profileId",
- merchant_connector_id: "merchantConnectorId",
-};
-const CONNECTOR_2_CREDENTIALS = {
- profile_id: "profile1Id",
- merchant_connector_id: "merchantConnector1Id",
-};
// Helper function for type and range validation
function validateType(value, type) {
@@ -53,6 +45,23 @@ function validateConfigValue(key, value) {
console.error("CONNECTOR_CREDENTIAL must be an object.");
return false;
}
+ // Validate nextConnector and multipleConnectors if present
+ if (
+ value?.nextConnector !== undefined &&
+ typeof value.nextConnector !== "boolean"
+ ) {
+ console.error("nextConnector must be a boolean");
+ return false;
+ }
+
+ if (
+ value?.multipleConnectors &&
+ typeof value.multipleConnectors.status !== "boolean"
+ ) {
+ console.error("multipleConnectors.status must be a boolean");
+ return false;
+ }
+
// Validate structure
if (
!value.value ||
@@ -103,54 +112,78 @@ export function validateConfig(configObject) {
return configObject;
}
-export function execConfig(configs) {
- // Handle delay if present
- if (configs?.DELAY?.STATUS) {
- cy.wait(configs.DELAY.TIMEOUT);
+export function getProfileAndConnectorId(connectorType) {
+ const credentials = {
+ connector_1: {
+ profileId: "profile",
+ connectorId: "merchantConnector",
+ },
+ connector_2: {
+ profileId: "profile1",
+ connectorId: "merchantConnector1",
+ },
+ };
+
+ return credentials[connectorType] || credentials.connector_1;
+}
+
+function getSpecName() {
+ return Cypress.spec.name.toLowerCase() === "__all"
+ ? String(
+ Cypress.mocha.getRunner().suite.ctx.test.invocationDetails.relativeFile
+ )
+ .split("/")
+ .pop()
+ .toLowerCase()
+ : Cypress.spec.name.toLowerCase();
+}
+
+function matchesSpecName(specName) {
+ if (!specName || !Array.isArray(specName) || specName.length === 0) {
+ return false;
}
+
+ const currentSpec = getSpecName();
+ return specName.some(
+ (name) => name && currentSpec.includes(name.toLowerCase())
+ );
+}
+
+export function determineConnectorConfig(connectorConfig) {
+ // Case 1: Multiple connectors configuration
if (
- typeof configs?.CONNECTOR_CREDENTIAL === "undefined" ||
- configs?.CONNECTOR_CREDENTIAL.value === "null"
+ connectorConfig?.nextConnector &&
+ connectorConfig?.multipleConnectors?.status
) {
- return DEFAULT_CREDENTIALS;
+ return "connector_2";
}
- // Get connector configuration
- const connectorType = determineConnectorConfig(configs.CONNECTOR_CREDENTIAL);
-
- // Return credentials based on connector type
- return connectorType === "connector_2"
- ? CONNECTOR_2_CREDENTIALS
- : DEFAULT_CREDENTIALS;
-}
-
-function determineConnectorConfig(connectorConfig) {
- // Return default if config is undefined or null
+ // Case 2: Invalid or null configuration
if (!connectorConfig || connectorConfig.value === "null") {
return DEFAULT_CONNECTOR;
}
- const { specName = null, value } = connectorConfig;
+ const { specName, value } = connectorConfig;
- // If value is not provided, return default
- if (!value) {
- return DEFAULT_CONNECTOR;
- }
-
- // If no specName or not an array, return value directly
- if (!specName || !Array.isArray(specName) || specName.length === 0) {
+ // Case 3: No spec name matching needed
+ if (!specName) {
return value;
}
- // Check if current spec matches any in specName
- const currentSpec = Cypress.spec.name.toLowerCase();
- try {
- const matchesSpec = specName.some(
- (name) => name && currentSpec.includes(name.toLowerCase())
- );
- return matchesSpec ? value : DEFAULT_CONNECTOR;
- } catch (error) {
- console.error("Error matching spec names:", error);
- return DEFAULT_CONNECTOR;
+ // Case 4: Match spec name and return appropriate connector
+ return matchesSpecName(specName) ? value : DEFAULT_CONNECTOR;
+}
+
+export function execConfig(configs) {
+ if (configs?.DELAY?.STATUS) {
+ cy.wait(configs.DELAY.TIMEOUT);
}
+
+ const connectorType = determineConnectorConfig(configs?.CONNECTOR_CREDENTIAL);
+ const { profileId, connectorId } = getProfileAndConnectorId(connectorType);
+
+ return {
+ profilePrefix: profileId,
+ merchantConnectorPrefix: connectorId,
+ };
}
|
ci
|
add tests that make use of locker (#6735)
|
b967d232519b106d88d79da2d6baec550c9256df
|
2023-07-03 12:56:01
|
Sai Harsha Vardhan
|
feat(router): add requeue support for payments and fix duplicate entry error in process tracker for requeued payments (#1567)
| false
|
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 26e96165ba4..10aabb0b592 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -973,3 +973,23 @@ pub struct UnresolvedResponseReason {
/// A message to merchant to give hint on next action he/she should do to resolve
pub message: String,
}
+
+#[derive(
+ Debug,
+ serde::Deserialize,
+ serde::Serialize,
+ strum::Display,
+ strum::EnumString,
+ Clone,
+ PartialEq,
+ Eq,
+ ToSchema,
+)]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum RetryAction {
+ /// Payment can be retried from the client side until the payment is successful or payment expires or the attempts(configured by the merchant) for payment are exhausted
+ ManualRetry,
+ /// Denotes that the payment is requeued
+ Requeue,
+}
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 95f38356204..cacff51844a 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -278,9 +278,9 @@ pub struct PaymentsRequest {
/// Business sub label for the payment
pub business_sub_label: Option<String>,
- /// If enabled payment can be retried from the client side until the payment is successful or payment expires or the attempts(configured by the merchant) for payment are exhausted.
- #[serde(default)]
- pub manual_retry: bool,
+ /// Denotes the retry action
+ #[schema(value_type = Option<RetryAction>)]
+ pub retry_action: Option<api_enums::RetryAction>,
/// Any user defined fields can be passed here.
#[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)]
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 1a3057bb972..37f11e93ba7 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -40,7 +40,7 @@ use crate::{
services::{self, api::Authenticate},
types::{
self, api, domain,
- storage::{self, enums as storage_enums},
+ storage::{self, enums as storage_enums, ProcessTrackerExt},
},
utils::{Encode, OptionExt, ValueExt},
};
@@ -137,7 +137,11 @@ where
if should_add_task_to_process_tracker(&payment_data) {
operation
.to_domain()?
- .add_task_to_process_tracker(state, &payment_data.payment_attempt)
+ .add_task_to_process_tracker(
+ state,
+ &payment_data.payment_attempt,
+ validate_result.requeue,
+ )
.await
.map_err(|error| logger::error!(process_tracker_error=?error))
.ok();
@@ -1234,19 +1238,39 @@ pub async fn add_process_sync_task(
&payment_attempt.attempt_id,
&payment_attempt.merchant_id,
);
- let process_tracker_entry =
- <storage::ProcessTracker as storage::ProcessTrackerExt>::make_process_tracker_new(
- process_tracker_id,
- task,
- runner,
- tracking_data,
- schedule_time,
- )?;
+ let process_tracker_entry = <storage::ProcessTracker>::make_process_tracker_new(
+ process_tracker_id,
+ task,
+ runner,
+ tracking_data,
+ schedule_time,
+ )?;
db.insert_process(process_tracker_entry).await?;
Ok(())
}
+pub async fn reset_process_sync_task(
+ db: &dyn StorageInterface,
+ payment_attempt: &storage::PaymentAttempt,
+ schedule_time: time::PrimitiveDateTime,
+) -> Result<(), errors::ProcessTrackerError> {
+ let runner = "PAYMENTS_SYNC_WORKFLOW";
+ let task = "PAYMENTS_SYNC";
+ let process_tracker_id = pt_utils::get_process_tracker_id(
+ runner,
+ task,
+ &payment_attempt.attempt_id,
+ &payment_attempt.merchant_id,
+ );
+ let psync_process = db
+ .find_process_by_id(&process_tracker_id)
+ .await?
+ .ok_or(errors::ProcessTrackerError::ProcessFetchingFailed)?;
+ psync_process.reset(db, schedule_time).await?;
+ Ok(())
+}
+
pub fn update_straight_through_routing<F>(
payment_data: &mut PaymentData<F>,
request_straight_through: serde_json::Value,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 9752aa44fa4..aaaeaba0a38 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -763,6 +763,7 @@ pub async fn add_domain_task_to_pt<Op>(
operation: &Op,
state: &AppState,
payment_attempt: &storage::PaymentAttempt,
+ requeue: bool,
) -> CustomResult<(), errors::ApiErrorResponse>
where
Op: std::fmt::Debug,
@@ -786,12 +787,21 @@ where
match schedule_time {
Some(stime) => {
- scheduler_metrics::TASKS_ADDED_COUNT.add(&metrics::CONTEXT, 1, &[]); // Metrics
- super::add_process_sync_task(&*state.store, payment_attempt, stime)
- .await
- .into_report()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed while adding task to process tracker")
+ if !requeue {
+ scheduler_metrics::TASKS_ADDED_COUNT.add(&metrics::CONTEXT, 1, &[]); // Metrics
+ super::add_process_sync_task(&*state.store, payment_attempt, stime)
+ .await
+ .into_report()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while adding task to process tracker")
+ } else {
+ scheduler_metrics::TASKS_RESET_COUNT.add(&metrics::CONTEXT, 1, &[]); // Metrics
+ super::reset_process_sync_task(&*state.store, payment_attempt, stime)
+ .await
+ .into_report()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while updating task in process tracker")
+ }
}
None => Ok(()),
}
@@ -2155,7 +2165,10 @@ pub fn get_attempt_type(
) -> RouterResult<AttemptType> {
match payment_intent.status {
enums::IntentStatus::Failed => {
- if request.manual_retry {
+ if matches!(
+ request.retry_action,
+ Some(api_models::enums::RetryAction::ManualRetry)
+ ) {
match payment_attempt.status {
enums::AttemptStatus::Started
| enums::AttemptStatus::AuthenticationPending
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index 7b39d6e4477..b0e362280fb 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -71,6 +71,7 @@ pub struct ValidateResult<'a> {
pub payment_id: api::PaymentIdType,
pub mandate_type: Option<api::MandateTransactionType>,
pub storage_scheme: enums::MerchantStorageScheme,
+ pub requeue: bool,
}
#[allow(clippy::type_complexity)]
@@ -119,6 +120,7 @@ pub trait Domain<F: Clone, R>: Send + Sync {
&'a self,
_db: &'a AppState,
_payment_attempt: &storage::PaymentAttempt,
+ _requeue: bool,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs
index b522be80651..435c5684fb2 100644
--- a/crates/router/src/core/payments/operations/payment_cancel.rs
+++ b/crates/router/src/core/payments/operations/payment_cancel.rs
@@ -235,6 +235,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsCancelRequest> for Payment
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
mandate_type: None,
storage_scheme: merchant_account.storage_scheme,
+ requeue: false,
},
))
}
diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs
index 82f6b895db1..ceafe457035 100644
--- a/crates/router/src/core/payments/operations/payment_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_capture.rs
@@ -215,6 +215,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsCaptureRequest> for Paymen
payment_id: api::PaymentIdType::PaymentIntentId(payment_id.to_owned()),
mandate_type: None,
storage_scheme: merchant_account.storage_scheme,
+ requeue: false,
},
))
}
diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
index 9f52c471456..1d71f4ba31b 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -271,6 +271,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for CompleteAuthorize {
&'a self,
_state: &'a AppState,
_payment_attempt: &storage::PaymentAttempt,
+ _requeue: bool,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
@@ -347,6 +348,10 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for CompleteAutho
payment_id: api::PaymentIdType::PaymentIntentId(payment_id),
mandate_type,
storage_scheme: merchant_account.storage_scheme,
+ requeue: matches!(
+ request.retry_action,
+ Some(api_models::enums::RetryAction::Requeue)
+ ),
},
))
}
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 91809e1415c..01800b70177 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -325,8 +325,9 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm {
&'a self,
state: &'a AppState,
payment_attempt: &storage::PaymentAttempt,
+ requeue: bool,
) -> CustomResult<(), errors::ApiErrorResponse> {
- helpers::add_domain_task_to_pt(self, state, payment_attempt).await
+ helpers::add_domain_task_to_pt(self, state, payment_attempt, requeue).await
}
async fn get_connector<'a>(
@@ -525,6 +526,10 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentConfir
payment_id: api::PaymentIdType::PaymentIntentId(payment_id),
mandate_type,
storage_scheme: merchant_account.storage_scheme,
+ requeue: matches!(
+ request.retry_action,
+ Some(api_models::enums::RetryAction::Requeue)
+ ),
},
))
}
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 2ea7fa1e123..861fc5f18ab 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -312,6 +312,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentCreate {
&'a self,
_state: &'a AppState,
_payment_attempt: &storage::PaymentAttempt,
+ _requeue: bool,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
@@ -488,6 +489,10 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate
payment_id: api::PaymentIdType::PaymentIntentId(payment_id),
mandate_type,
storage_scheme: merchant_account.storage_scheme,
+ requeue: matches!(
+ request.retry_action,
+ Some(api_models::enums::RetryAction::Requeue)
+ ),
},
))
}
diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs
index f2bc4abb8f0..f0bee3fe4e7 100644
--- a/crates/router/src/core/payments/operations/payment_method_validate.rs
+++ b/crates/router/src/core/payments/operations/payment_method_validate.rs
@@ -56,6 +56,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::VerifyRequest> for PaymentMethodVa
payment_id: api::PaymentIdType::PaymentIntentId(validation_id),
mandate_type,
storage_scheme: merchant_account.storage_scheme,
+ requeue: false,
},
))
}
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 5589fca3f98..096cf297d01 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -237,6 +237,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsSessionRequest> for Paymen
payment_id: api::PaymentIdType::PaymentIntentId(given_payment_id),
mandate_type: None,
storage_scheme: merchant_account.storage_scheme,
+ requeue: false,
},
))
}
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index 5cd2d11c081..9490213a39a 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -202,6 +202,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsStartRequest> for PaymentS
payment_id: api::PaymentIdType::PaymentIntentId(payment_id),
mandate_type: None,
storage_scheme: merchant_account.storage_scheme,
+ requeue: false,
},
))
}
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index 5d22bd3b0a8..90e655f3032 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -93,8 +93,9 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus {
&'a self,
state: &'a AppState,
payment_attempt: &storage::PaymentAttempt,
+ requeue: bool,
) -> CustomResult<(), errors::ApiErrorResponse> {
- helpers::add_domain_task_to_pt(self, state, payment_attempt).await
+ helpers::add_domain_task_to_pt(self, state, payment_attempt, requeue).await
}
async fn get_connector<'a>(
@@ -333,6 +334,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRetrieveRequest> for Payme
payment_id: request.resource_id.clone(),
mandate_type: None,
storage_scheme: merchant_account.storage_scheme,
+ requeue: false,
},
))
}
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 507f4034e6f..f2868a2ede4 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -358,6 +358,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentUpdate {
&'a self,
_state: &'a AppState,
_payment_attempt: &storage::PaymentAttempt,
+ _requeue: bool,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
@@ -575,6 +576,10 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentUpdate
payment_id: api::PaymentIdType::PaymentIntentId(payment_id),
mandate_type,
storage_scheme: merchant_account.storage_scheme,
+ requeue: matches!(
+ request.retry_action,
+ Some(api_models::enums::RetryAction::Requeue)
+ ),
},
))
}
diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs
index 726d2295c91..40e7d32a1be 100644
--- a/crates/router/src/openapi.rs
+++ b/crates/router/src/openapi.rs
@@ -152,6 +152,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::enums::CountryAlpha2,
api_models::enums::FrmAction,
api_models::enums::FrmPreferredFlowTypes,
+ api_models::enums::RetryAction,
api_models::admin::MerchantConnectorCreate,
api_models::admin::MerchantConnectorUpdate,
api_models::admin::PrimaryBusinessDetails,
diff --git a/crates/router/src/scheduler/metrics.rs b/crates/router/src/scheduler/metrics.rs
index 6fae07bba9d..7337e3ab4f5 100644
--- a/crates/router/src/scheduler/metrics.rs
+++ b/crates/router/src/scheduler/metrics.rs
@@ -7,6 +7,7 @@ histogram_metric!(CONSUMER_STATS, PT_METER, "CONSUMER_OPS");
counter_metric!(PAYMENT_COUNT, PT_METER); // No. of payments created
counter_metric!(TASKS_ADDED_COUNT, PT_METER); // Tasks added to process tracker
+counter_metric!(TASKS_RESET_COUNT, PT_METER); // Tasks reset in process tracker for requeue flow
counter_metric!(TASKS_PICKED_COUNT, PT_METER); // Tasks picked by
counter_metric!(BATCHES_CREATED, PT_METER); // Batches added to stream
counter_metric!(BATCHES_CONSUMED, PT_METER); // Batches consumed by consumer
diff --git a/crates/router/src/types/storage/process_tracker.rs b/crates/router/src/types/storage/process_tracker.rs
index 98b2fa2b20c..9e1120745e5 100644
--- a/crates/router/src/types/storage/process_tracker.rs
+++ b/crates/router/src/types/storage/process_tracker.rs
@@ -24,6 +24,12 @@ pub trait ProcessTrackerExt {
where
T: Serialize;
+ async fn reset(
+ self,
+ db: &dyn StorageInterface,
+ schedule_time: PrimitiveDateTime,
+ ) -> Result<(), errors::ProcessTrackerError>;
+
async fn retry(
self,
db: &dyn StorageInterface,
@@ -72,6 +78,23 @@ impl ProcessTrackerExt for ProcessTracker {
})
}
+ async fn reset(
+ self,
+ db: &dyn StorageInterface,
+ schedule_time: PrimitiveDateTime,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ db.update_process_tracker(
+ self.clone(),
+ ProcessTrackerUpdate::StatusRetryUpdate {
+ status: storage_enums::ProcessTrackerStatus::New,
+ retry_count: 0,
+ schedule_time,
+ },
+ )
+ .await?;
+ Ok(())
+ }
+
async fn retry(
self,
db: &dyn StorageInterface,
|
feat
|
add requeue support for payments and fix duplicate entry error in process tracker for requeued payments (#1567)
|
84decd8126d306a5e1cf22b36e1378a73dc963f5
|
2023-12-06 14:47:40
|
Pa1NarK
|
fix(config): parse kafka brokers from env variable as sequence (#3066)
| false
|
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 6cbffc186d2..7b469a2165f 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -785,6 +785,7 @@ impl Settings {
.list_separator(",")
.with_list_parse_key("log.telemetry.route_to_trace")
.with_list_parse_key("redis.cluster_urls")
+ .with_list_parse_key("events.kafka.brokers")
.with_list_parse_key("connectors.supported.wallets")
.with_list_parse_key("connector_request_reference_id_config.merchant_ids_send_payment_id_as_connector_request_id"),
|
fix
|
parse kafka brokers from env variable as sequence (#3066)
|
75ec96b6131d470b39171415058106b3464de75a
|
2024-11-20 17:26:49
|
Swangi Kumari
|
fix(connector): [Volt] handle 5xx error for Volt payments webhooks (#6576)
| false
|
diff --git a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
index b8e1e99054a..61cf91c87cb 100644
--- a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
@@ -518,6 +518,7 @@ pub enum VoltWebhookObjectResource {
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPaymentWebhookObjectResource {
+ #[serde(alias = "id")]
pub payment: String,
pub merchant_internal_reference: Option<String>,
pub status: VoltWebhookPaymentStatus,
|
fix
|
[Volt] handle 5xx error for Volt payments webhooks (#6576)
|
eef1aeb0f53661088fd512033080aa12f60991dd
|
2025-02-26 01:04:45
|
Swangi Kumari
|
feat(connector): [DLOCAL, MOLLIE, MIFINITY, RAZORPAY, VOLT] add in feature matrix api (#7290)
| false
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 78ec91dd7c0..341ff3e613b 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -614,6 +614,17 @@ mifinity = { country = "BR,CN,SG,MY,DE,CH,DK,GB,ES,AD,GI,FI,FR,GR,HR,IT,JP,MX,AR
[pm_filters.fiuu]
duit_now = { country = "MY", currency = "MYR" }
+[pm_filters.dlocal]
+credit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"}
+debit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"}
+
+[pm_filters.mollie]
+credit = { not_available_flows = { capture_method = "manual" } }
+debit = { not_available_flows = { capture_method = "manual" } }
+eps = { country = "AT", currency = "EUR" }
+ideal = { country = "NL", currency = "EUR" }
+przelewy24 = { country = "PL", currency = "PLN,EUR" }
+
[connector_customer]
connector_list = "gocardless,stax,stripe"
payout_connector_list = "stripe,wise"
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 4cc67d0dafd..fb405385702 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -404,6 +404,17 @@ duit_now = { country = "MY", currency = "MYR" }
apple_pay = { country = "MY", currency = "MYR" }
google_pay = { country = "MY", currency = "MYR" }
+[pm_filters.dlocal]
+credit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"}
+debit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"}
+
+[pm_filters.mollie]
+credit = { not_available_flows = { capture_method = "manual" } }
+debit = { not_available_flows = { capture_method = "manual" } }
+eps = { country = "AT", currency = "EUR" }
+ideal = { country = "NL", currency = "EUR" }
+przelewy24 = { country = "PL", currency = "PLN,EUR" }
+
[payout_method_filters.adyenplatform]
sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT,CZ,DE,HU,NO,PL,SE,GB,CH" , currency = "EUR,CZK,DKK,HUF,NOK,PLN,SEK,GBP,CHF" }
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 7b5f0aba309..70a532b5ca9 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -420,6 +420,17 @@ duit_now = { country = "MY", currency = "MYR" }
apple_pay = { country = "MY", currency = "MYR" }
google_pay = { country = "MY", currency = "MYR" }
+[pm_filters.dlocal]
+credit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"}
+debit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"}
+
+[pm_filters.mollie]
+credit = { not_available_flows = { capture_method = "manual" } }
+debit = { not_available_flows = { capture_method = "manual" } }
+eps = { country = "AT", currency = "EUR" }
+ideal = { country = "NL", currency = "EUR" }
+przelewy24 = { country = "PL", currency = "PLN,EUR" }
+
[payout_method_filters.adyenplatform]
sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT,CZ,DE,HU,NO,PL,SE,GB,CH" , currency = "EUR,CZK,DKK,HUF,NOK,PLN,SEK,GBP,CHF" }
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index e0b04ca0575..0de2bd26f20 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -421,6 +421,17 @@ duit_now = { country = "MY", currency = "MYR" }
apple_pay = { country = "MY", currency = "MYR" }
google_pay = { country = "MY", currency = "MYR" }
+[pm_filters.dlocal]
+credit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"}
+debit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"}
+
+[pm_filters.mollie]
+credit = { not_available_flows = { capture_method = "manual" } }
+debit = { not_available_flows = { capture_method = "manual" } }
+eps = { country = "AT", currency = "EUR" }
+ideal = { country = "NL", currency = "EUR" }
+przelewy24 = { country = "PL", currency = "PLN,EUR" }
+
[payout_method_filters.adyenplatform]
sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT,CZ,DE,HU,NO,PL,SE,GB,CH" , currency = "EUR,CZK,DKK,HUF,NOK,PLN,SEK,GBP,CHF" }
diff --git a/config/development.toml b/config/development.toml
index 5a06b022c32..ddd1a8bc966 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -597,6 +597,9 @@ debit = { not_available_flows = { capture_method = "manual" } }
[pm_filters.mollie]
credit = { not_available_flows = { capture_method = "manual" } }
debit = { not_available_flows = { capture_method = "manual" } }
+eps = { country = "AT", currency = "EUR" }
+ideal = { country = "NL", currency = "EUR" }
+przelewy24 = { country = "PL", currency = "PLN,EUR" }
[pm_filters.multisafepay]
credit = { not_available_flows = { capture_method = "manual" } }
@@ -637,6 +640,11 @@ duit_now = { country = "MY", currency = "MYR" }
apple_pay = { country = "MY", currency = "MYR" }
google_pay = { country = "MY", currency = "MYR" }
+[pm_filters.dlocal]
+credit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"}
+debit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"}
+
+
[pm_filters.inespay]
sepa = { currency = "EUR" }
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 6d2e20d1a3d..4a1931632cb 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -537,6 +537,17 @@ apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,D
[pm_filters.fiuu]
duit_now = { country = "MY", currency = "MYR" }
+[pm_filters.dlocal]
+credit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"}
+debit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"}
+
+[pm_filters.mollie]
+credit = { not_available_flows = { capture_method = "manual" } }
+debit = { not_available_flows = { capture_method = "manual" } }
+eps = { country = "AT", currency = "EUR" }
+ideal = { country = "NL", currency = "EUR" }
+przelewy24 = { country = "PL", currency = "PLN,EUR" }
+
[bank_config.online_banking_fpx]
adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank"
fiuu.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_of_china,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank"
diff --git a/crates/hyperswitch_connectors/src/connectors/dlocal.rs b/crates/hyperswitch_connectors/src/connectors/dlocal.rs
index 0aefd65e4a0..60813a4ea08 100644
--- a/crates/hyperswitch_connectors/src/connectors/dlocal.rs
+++ b/crates/hyperswitch_connectors/src/connectors/dlocal.rs
@@ -25,7 +25,10 @@ use hyperswitch_domain_models::{
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
- router_response_types::{PaymentsResponseData, RefundsResponseData},
+ router_response_types::{
+ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
+ SupportedPaymentMethods, SupportedPaymentMethodsExt,
+ },
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
@@ -42,14 +45,11 @@ use hyperswitch_interfaces::{
types::{self, Response},
webhooks,
};
+use lazy_static::lazy_static;
use masking::{Mask, Maskable, PeekInterface};
use transformers as dlocal;
-use crate::{
- constants::headers,
- types::ResponseRouterData,
- utils::{self},
-};
+use crate::{constants::headers, types::ResponseRouterData};
#[derive(Debug, Clone)]
pub struct Dlocal;
@@ -156,24 +156,7 @@ impl ConnectorCommon for Dlocal {
}
}
-impl ConnectorValidation for Dlocal {
- fn validate_connector_against_payment_request(
- &self,
- capture_method: Option<enums::CaptureMethod>,
- _payment_method: enums::PaymentMethod,
- _pmt: Option<enums::PaymentMethodType>,
- ) -> CustomResult<(), errors::ConnectorError> {
- let capture_method = capture_method.unwrap_or_default();
- match capture_method {
- enums::CaptureMethod::Automatic
- | enums::CaptureMethod::Manual
- | enums::CaptureMethod::SequentialAutomatic => Ok(()),
- enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- utils::construct_not_supported_error_report(capture_method, self.id()),
- ),
- }
- }
-}
+impl ConnectorValidation for Dlocal {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Dlocal
@@ -693,4 +676,90 @@ impl webhooks::IncomingWebhook for Dlocal {
}
}
-impl ConnectorSpecifications for Dlocal {}
+lazy_static! {
+ static ref DLOCAL_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
+ let supported_capture_methods = vec![
+ enums::CaptureMethod::Automatic,
+ enums::CaptureMethod::Manual,
+ enums::CaptureMethod::SequentialAutomatic,
+ ];
+
+ let supported_card_network = vec![
+ common_enums::CardNetwork::Visa,
+ common_enums::CardNetwork::Mastercard,
+ common_enums::CardNetwork::AmericanExpress,
+ common_enums::CardNetwork::Discover,
+ common_enums::CardNetwork::JCB,
+ common_enums::CardNetwork::DinersClub,
+ common_enums::CardNetwork::UnionPay,
+ common_enums::CardNetwork::Interac,
+ common_enums::CardNetwork::CartesBancaires,
+
+ ];
+
+ let mut dlocal_supported_payment_methods = SupportedPaymentMethods::new();
+
+ dlocal_supported_payment_methods.add(
+ enums::PaymentMethod::Card,
+ enums::PaymentMethodType::Credit,
+ PaymentMethodDetails{
+ mandates: common_enums::FeatureStatus::NotSupported,
+ refunds: common_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::Supported,
+ no_three_ds: common_enums::FeatureStatus::Supported,
+ supported_card_networks: supported_card_network.clone(),
+ }
+ }),
+ ),
+ },
+ );
+ dlocal_supported_payment_methods.add(
+ enums::PaymentMethod::Card,
+ enums::PaymentMethodType::Debit,
+ PaymentMethodDetails{
+ mandates: common_enums::FeatureStatus::NotSupported,
+ refunds: common_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::Supported,
+ no_three_ds: common_enums::FeatureStatus::Supported,
+ supported_card_networks: supported_card_network.clone(),
+ }
+ }),
+ ),
+ },
+ );
+
+ dlocal_supported_payment_methods
+ };
+
+ static ref DLOCAL_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
+ display_name: "DLOCAL",
+ description:
+ "Dlocal is a cross-border payment processor enabling businesses to accept and send payments in emerging markets worldwide.",
+ connector_type: enums::PaymentConnectorCategory::PaymentGateway,
+ };
+
+ static ref DLOCAL_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new();
+
+}
+
+impl ConnectorSpecifications for Dlocal {
+ fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
+ Some(&*DLOCAL_CONNECTOR_INFO)
+ }
+
+ fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
+ Some(&*DLOCAL_SUPPORTED_PAYMENT_METHODS)
+ }
+
+ fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
+ Some(&*DLOCAL_SUPPORTED_WEBHOOK_FLOWS)
+ }
+}
diff --git a/crates/hyperswitch_connectors/src/connectors/mifinity.rs b/crates/hyperswitch_connectors/src/connectors/mifinity.rs
index 618e9874303..3b597597e38 100644
--- a/crates/hyperswitch_connectors/src/connectors/mifinity.rs
+++ b/crates/hyperswitch_connectors/src/connectors/mifinity.rs
@@ -1,6 +1,7 @@
pub mod transformers;
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
+use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
@@ -20,7 +21,10 @@ use hyperswitch_domain_models::{
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
- router_response_types::{PaymentsResponseData, RefundsResponseData},
+ router_response_types::{
+ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
+ SupportedPaymentMethods, SupportedPaymentMethodsExt,
+ },
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundsRouterData,
@@ -38,6 +42,7 @@ use hyperswitch_interfaces::{
types::{self, Response},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
+use lazy_static::lazy_static;
use masking::{ExposeInterface, Mask};
use router_env::logger;
use transformers::{self as mifinity, auth_headers};
@@ -500,4 +505,46 @@ impl IncomingWebhook for Mifinity {
}
}
-impl ConnectorSpecifications for Mifinity {}
+lazy_static! {
+ static ref MIFINITY_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
+ let supported_capture_methods = vec![enums::CaptureMethod::Automatic];
+
+ let mut mifinity_supported_payment_methods = SupportedPaymentMethods::new();
+ mifinity_supported_payment_methods.add(
+ enums::PaymentMethod::Wallet,
+ enums::PaymentMethodType::Mifinity,
+ PaymentMethodDetails{
+ mandates: common_enums::FeatureStatus::NotSupported,
+ refunds: common_enums::FeatureStatus::NotSupported,
+ supported_capture_methods,
+ specific_features: None,
+ },
+ );
+
+ mifinity_supported_payment_methods
+ };
+
+ static ref MIFINITY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
+ display_name: "MIFINITY",
+ description:
+ "Mifinity is a payment gateway empowering you to pay online, receive funds, and send money globally, the MiFinity eWallet supports super-low fees, offering infinite possibilities to do more of the things you love.",
+ connector_type: enums::PaymentConnectorCategory::PaymentGateway,
+ };
+
+ static ref MIFINITY_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new();
+
+}
+
+impl ConnectorSpecifications for Mifinity {
+ fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
+ Some(&*MIFINITY_CONNECTOR_INFO)
+ }
+
+ fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
+ Some(&*MIFINITY_SUPPORTED_PAYMENT_METHODS)
+ }
+
+ fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
+ Some(&*MIFINITY_SUPPORTED_WEBHOOK_FLOWS)
+ }
+}
diff --git a/crates/hyperswitch_connectors/src/connectors/mollie.rs b/crates/hyperswitch_connectors/src/connectors/mollie.rs
index 8cdf4f03a70..325c031c33f 100644
--- a/crates/hyperswitch_connectors/src/connectors/mollie.rs
+++ b/crates/hyperswitch_connectors/src/connectors/mollie.rs
@@ -21,7 +21,10 @@ use hyperswitch_domain_models::{
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
- router_response_types::{PaymentsResponseData, RefundsResponseData},
+ router_response_types::{
+ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
+ SupportedPaymentMethods, SupportedPaymentMethodsExt,
+ },
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, TokenizationRouterData,
@@ -38,10 +41,11 @@ use hyperswitch_interfaces::{
types::{self, Response},
webhooks,
};
+use lazy_static::lazy_static;
use masking::{Mask, PeekInterface};
use transformers as mollie;
-// use self::mollie::{webhook_headers, VoltWebhookBodyEventType};
+// use self::mollie::{webhook_headers, MollieWebhookBodyEventType};
use crate::{constants::headers, types::ResponseRouterData, utils::convert_amount};
#[derive(Clone)]
@@ -635,4 +639,178 @@ impl ConnectorRedirectResponse for Mollie {
}
}
-impl ConnectorSpecifications for Mollie {}
+// impl ConnectorSpecifications for Mollie {}
+lazy_static! {
+ static ref MOLLIE_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
+ let supported_capture_methods = vec![
+ enums::CaptureMethod::Automatic,
+ enums::CaptureMethod::SequentialAutomatic,
+ ];
+ let supported_card_network = vec![
+ common_enums::CardNetwork::Visa,
+ common_enums::CardNetwork::Mastercard,
+ common_enums::CardNetwork::AmericanExpress,
+ common_enums::CardNetwork::Discover,
+ common_enums::CardNetwork::JCB,
+ common_enums::CardNetwork::DinersClub,
+ common_enums::CardNetwork::UnionPay,
+ common_enums::CardNetwork::Interac,
+ common_enums::CardNetwork::CartesBancaires,
+
+ ];
+
+ let mut mollie_supported_payment_methods = SupportedPaymentMethods::new();
+ mollie_supported_payment_methods.add(
+ enums::PaymentMethod::Card,
+ enums::PaymentMethodType::Credit,
+ PaymentMethodDetails{
+ mandates: common_enums::FeatureStatus::NotSupported,
+ refunds: common_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::Supported,
+ no_three_ds: common_enums::FeatureStatus::Supported,
+ supported_card_networks: supported_card_network.clone(),
+ }
+ }),
+ ),
+ },
+ );
+ mollie_supported_payment_methods.add(
+ enums::PaymentMethod::Card,
+ enums::PaymentMethodType::Debit,
+ PaymentMethodDetails{
+ mandates: common_enums::FeatureStatus::NotSupported,
+ refunds: common_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::Supported,
+ no_three_ds: common_enums::FeatureStatus::Supported,
+ supported_card_networks: supported_card_network.clone(),
+ }
+ }),
+ ),
+ },
+ );
+ mollie_supported_payment_methods.add(
+ enums::PaymentMethod::BankRedirect,
+ enums::PaymentMethodType::Eps,
+ PaymentMethodDetails{
+ mandates: common_enums::FeatureStatus::NotSupported,
+ refunds: common_enums::FeatureStatus::Supported,
+ supported_capture_methods: supported_capture_methods.clone(),
+ specific_features: None,
+ },
+ );
+ mollie_supported_payment_methods.add(
+ enums::PaymentMethod::BankRedirect,
+ enums::PaymentMethodType::Giropay,
+ PaymentMethodDetails{
+ mandates: common_enums::FeatureStatus::NotSupported,
+ refunds: common_enums::FeatureStatus::Supported,
+ supported_capture_methods: supported_capture_methods.clone(),
+ specific_features: None,
+ },
+ );
+ mollie_supported_payment_methods.add(
+ enums::PaymentMethod::BankRedirect,
+ enums::PaymentMethodType::Ideal,
+ PaymentMethodDetails{
+ mandates: common_enums::FeatureStatus::NotSupported,
+ refunds: common_enums::FeatureStatus::Supported,
+ supported_capture_methods: supported_capture_methods.clone(),
+ specific_features: None,
+ },
+ );
+ mollie_supported_payment_methods.add(
+ enums::PaymentMethod::BankRedirect,
+ enums::PaymentMethodType::Sofort,
+ PaymentMethodDetails{
+ mandates: common_enums::FeatureStatus::NotSupported,
+ refunds: common_enums::FeatureStatus::Supported,
+ supported_capture_methods: supported_capture_methods.clone(),
+ specific_features: None,
+ },
+ );
+ mollie_supported_payment_methods.add(
+ enums::PaymentMethod::BankRedirect,
+ enums::PaymentMethodType::Przelewy24,
+ PaymentMethodDetails{
+ mandates: common_enums::FeatureStatus::NotSupported,
+ refunds: common_enums::FeatureStatus::Supported,
+ supported_capture_methods: supported_capture_methods.clone(),
+ specific_features: None,
+ },
+ );
+ mollie_supported_payment_methods.add(
+ enums::PaymentMethod::BankRedirect,
+ enums::PaymentMethodType::BancontactCard,
+ PaymentMethodDetails{
+ mandates: common_enums::FeatureStatus::NotSupported,
+ refunds: common_enums::FeatureStatus::Supported,
+ supported_capture_methods: supported_capture_methods.clone(),
+ specific_features: None,
+ },
+ );
+ mollie_supported_payment_methods.add(
+ enums::PaymentMethod::Wallet,
+ enums::PaymentMethodType::Paypal,
+ PaymentMethodDetails{
+ mandates: common_enums::FeatureStatus::NotSupported,
+ refunds: common_enums::FeatureStatus::Supported,
+ supported_capture_methods: supported_capture_methods.clone(),
+ specific_features: None,
+ },
+ );
+ mollie_supported_payment_methods.add(
+ enums::PaymentMethod::Wallet,
+ enums::PaymentMethodType::ApplePay,
+ PaymentMethodDetails{
+ mandates: common_enums::FeatureStatus::NotSupported,
+ refunds: common_enums::FeatureStatus::Supported,
+ supported_capture_methods: supported_capture_methods.clone(),
+ specific_features: None,
+ },
+ );
+ mollie_supported_payment_methods.add(
+ enums::PaymentMethod::BankDebit,
+ enums::PaymentMethodType::Sepa,
+ PaymentMethodDetails{
+ mandates: common_enums::FeatureStatus::NotSupported,
+ refunds: common_enums::FeatureStatus::Supported,
+ supported_capture_methods: supported_capture_methods.clone(),
+ specific_features: None,
+ },
+ );
+
+ mollie_supported_payment_methods
+ };
+
+ static ref MOLLIE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
+ display_name: "MOLLIE",
+ description:
+ "Mollie is a Developer-friendly processor providing simple and customizable payment solutions for businesses of all sizes.",
+ connector_type: enums::PaymentConnectorCategory::PaymentGateway,
+ };
+
+ static ref MOLLIE_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new();
+
+}
+
+impl ConnectorSpecifications for Mollie {
+ fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
+ Some(&*MOLLIE_CONNECTOR_INFO)
+ }
+
+ fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
+ Some(&*MOLLIE_SUPPORTED_PAYMENT_METHODS)
+ }
+
+ fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
+ Some(&*MOLLIE_SUPPORTED_WEBHOOK_FLOWS)
+ }
+}
diff --git a/crates/hyperswitch_connectors/src/connectors/razorpay.rs b/crates/hyperswitch_connectors/src/connectors/razorpay.rs
index f5f3aa85e89..435ff983c8b 100644
--- a/crates/hyperswitch_connectors/src/connectors/razorpay.rs
+++ b/crates/hyperswitch_connectors/src/connectors/razorpay.rs
@@ -1,6 +1,7 @@
pub mod transformers;
use api_models::webhooks::{self, IncomingWebhookEvent};
+use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::{ByteSliceExt, BytesExt},
@@ -20,7 +21,10 @@ use hyperswitch_domain_models::{
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
- router_response_types::{PaymentsResponseData, RefundsResponseData},
+ router_response_types::{
+ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
+ SupportedPaymentMethods, SupportedPaymentMethodsExt,
+ },
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
@@ -38,6 +42,7 @@ use hyperswitch_interfaces::{
types::{self, Response},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
+use lazy_static::lazy_static;
use masking::{ExposeInterface, Mask};
use router_env::logger;
use transformers as razorpay;
@@ -676,4 +681,46 @@ fn get_webhook_object_from_body(
Ok(details.payload)
}
-impl ConnectorSpecifications for Razorpay {}
+lazy_static! {
+ static ref RAZORPAY_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
+ let supported_capture_methods = vec![enums::CaptureMethod::Automatic];
+
+ let mut razorpay_supported_payment_methods = SupportedPaymentMethods::new();
+ razorpay_supported_payment_methods.add(
+ enums::PaymentMethod::Upi,
+ enums::PaymentMethodType::UpiCollect,
+ PaymentMethodDetails{
+ mandates: common_enums::FeatureStatus::NotSupported,
+ refunds: common_enums::FeatureStatus::Supported,
+ supported_capture_methods,
+ specific_features: None,
+ },
+ );
+
+ razorpay_supported_payment_methods
+ };
+
+ static ref RAZORPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
+ display_name: "RAZORPAY",
+ description:
+ "Razorpay helps you accept online payments from customers across Desktop, Mobile web, Android & iOS. Additionally by using Razorpay Payment Links, you can collect payments across multiple channels like SMS, Email, Whatsapp, Chatbots & Messenger.",
+ connector_type: enums::PaymentConnectorCategory::PaymentGateway,
+ };
+
+ static ref RAZORPAY_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = vec![enums::EventClass::Payments, enums::EventClass::Refunds];
+
+}
+
+impl ConnectorSpecifications for Razorpay {
+ fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
+ Some(&*RAZORPAY_CONNECTOR_INFO)
+ }
+
+ fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
+ Some(&*RAZORPAY_SUPPORTED_PAYMENT_METHODS)
+ }
+
+ fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
+ Some(&*RAZORPAY_SUPPORTED_WEBHOOK_FLOWS)
+ }
+}
diff --git a/crates/hyperswitch_connectors/src/connectors/volt.rs b/crates/hyperswitch_connectors/src/connectors/volt.rs
index 63021881443..cec1194f281 100644
--- a/crates/hyperswitch_connectors/src/connectors/volt.rs
+++ b/crates/hyperswitch_connectors/src/connectors/volt.rs
@@ -1,6 +1,7 @@
pub mod transformers;
use api_models::webhooks::IncomingWebhookEvent;
+use common_enums::enums;
use common_utils::{
crypto,
errors::CustomResult,
@@ -21,7 +22,10 @@ use hyperswitch_domain_models::{
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
- router_response_types::{PaymentsResponseData, RefundsResponseData},
+ router_response_types::{
+ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
+ SupportedPaymentMethods, SupportedPaymentMethodsExt,
+ },
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefreshTokenRouterData, RefundsRouterData,
@@ -38,6 +42,7 @@ use hyperswitch_interfaces::{
types::{self, PaymentsAuthorizeType, RefreshTokenType, Response},
webhooks,
};
+use lazy_static::lazy_static;
use masking::{ExposeInterface, Mask, PeekInterface};
use transformers as volt;
@@ -731,4 +736,46 @@ impl webhooks::IncomingWebhook for Volt {
}
}
-impl ConnectorSpecifications for Volt {}
+lazy_static! {
+ static ref VOLT_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
+ let supported_capture_methods = vec![enums::CaptureMethod::Automatic];
+
+ let mut volt_supported_payment_methods = SupportedPaymentMethods::new();
+ volt_supported_payment_methods.add(
+ enums::PaymentMethod::BankRedirect,
+ enums::PaymentMethodType::OpenBankingUk,
+ PaymentMethodDetails{
+ mandates: common_enums::FeatureStatus::NotSupported,
+ refunds: common_enums::FeatureStatus::Supported,
+ supported_capture_methods,
+ specific_features: None,
+ },
+ );
+
+ volt_supported_payment_methods
+ };
+
+ static ref VOLT_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
+ display_name: "VOLT",
+ description:
+ "Volt is a payment gateway operating in China, specializing in facilitating local bank transfers",
+ connector_type: enums::PaymentConnectorCategory::PaymentGateway,
+ };
+
+ static ref VOLT_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new();
+
+}
+
+impl ConnectorSpecifications for Volt {
+ fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
+ Some(&*VOLT_CONNECTOR_INFO)
+ }
+
+ fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
+ Some(&*VOLT_SUPPORTED_PAYMENT_METHODS)
+ }
+
+ fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
+ Some(&*VOLT_SUPPORTED_WEBHOOK_FLOWS)
+ }
+}
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 6766d7cb7e6..7c999401f63 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -271,6 +271,20 @@ cards = [
"zsl",
]
+[pm_filters.dlocal]
+credit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"}
+debit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"}
+
+[pm_filters.mollie]
+credit = { not_available_flows = { capture_method = "manual" } }
+debit = { not_available_flows = { capture_method = "manual" } }
+eps = { country = "AT", currency = "EUR" }
+ideal = { country = "NL", currency = "EUR" }
+przelewy24 = { country = "PL", currency = "PLN,EUR" }
+
+[pm_filters.mifinity]
+mifinity = { country = "BR,CN,SG,MY,DE,CH,DK,GB,ES,AD,GI,FI,FR,GR,HR,IT,JP,MX,AR,CO,CL,PE,VE,UY,PY,BO,EC,GT,HN,SV,NI,CR,PA,DO,CU,PR,NL,NO,PL,PT,SE,RU,TR,TW,HK,MO,AX,AL,DZ,AS,AO,AI,AG,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BE,BZ,BJ,BM,BT,BQ,BA,BW,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CX,CC,KM,CG,CK,CI,CW,CY,CZ,DJ,DM,EG,GQ,ER,EE,ET,FK,FO,FJ,GF,PF,TF,GA,GM,GE,GH,GL,GD,GP,GU,GG,GN,GW,GY,HT,HM,VA,IS,IN,ID,IE,IM,IL,JE,JO,KZ,KE,KI,KW,KG,LA,LV,LB,LS,LI,LT,LU,MK,MG,MW,MV,ML,MT,MH,MQ,MR,MU,YT,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NC,NZ,NE,NG,NU,NF,MP,OM,PK,PW,PS,PG,PH,PN,QA,RE,RO,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SX,SK,SI,SB,SO,ZA,GS,KR,LK,SR,SJ,SZ,TH,TL,TG,TK,TO,TT,TN,TM,TC,TV,UG,UA,AE,UZ,VU,VN,VG,VI,WF,EH,ZM", currency = "AUD,CAD,CHF,CNY,CZK,DKK,EUR,GBP,INR,JPY,NOK,NZD,PLN,RUB,SEK,ZAR,USD,EGP,UYU,UZS" }
+
[pm_filters.volt]
open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL"}
|
feat
|
[DLOCAL, MOLLIE, MIFINITY, RAZORPAY, VOLT] add in feature matrix api (#7290)
|
081545e9121861ac7c1867a5e3f4c59ef848eeeb
|
2023-09-20 13:11:17
|
DEEPANSHU BANSAL
|
fix(connector): [SQUARE] Fix payments cancel issue (#2162)
| false
|
diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs
index 69e5c52f9b5..ff33914c4fd 100644
--- a/crates/router/src/connector/square/transformers.rs
+++ b/crates/router/src/connector/square/transformers.rs
@@ -341,8 +341,14 @@ impl<F, T>
fn try_from(
item: types::ResponseRouterData<F, SquarePaymentsResponse, T, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
+ //Since this try_from is being used in Authorize, Sync, Capture & Void flow. Field amount_captured should only be updated in case of Charged status.
+ let status = enums::AttemptStatus::from(item.response.payment.status);
+ let mut amount_captured = None;
+ if status == enums::AttemptStatus::Charged {
+ amount_captured = Some(item.response.payment.amount_money.amount)
+ };
Ok(Self {
- status: enums::AttemptStatus::from(item.response.payment.status),
+ status,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.payment.id),
redirection_data: None,
@@ -351,7 +357,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: None,
}),
- amount_captured: Some(item.response.payment.amount_money.amount),
+ amount_captured,
..item.data
})
}
|
fix
|
[SQUARE] Fix payments cancel issue (#2162)
|
550377a6c3943d9fec4ca6a8be5a5f3aafe109ab
|
2023-10-12 02:38:54
|
Rutam Prita Mishra
|
feat(connector): [Tsys] Use `connector_response_reference_id` as reference to the connector (#2546)
| false
|
diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs
index 5aa4574c91e..d8516c8293b 100644
--- a/crates/router/src/connector/tsys/transformers.rs
+++ b/crates/router/src/connector/tsys/transformers.rs
@@ -192,12 +192,14 @@ fn get_error_response(
fn get_payments_response(connector_response: TsysResponse) -> types::PaymentsResponseData {
types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(connector_response.transaction_id),
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ connector_response.transaction_id.clone(),
+ ),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(connector_response.transaction_id),
}
}
@@ -215,7 +217,12 @@ fn get_payments_sync_response(
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(
+ connector_response
+ .transaction_details
+ .transaction_id
+ .clone(),
+ ),
}
}
|
feat
|
[Tsys] Use `connector_response_reference_id` as reference to the connector (#2546)
|
e94930cf5cf4219b967a0b447d3c7503c6a7363d
|
2024-02-16 05:46:19
|
github-actions
|
chore(postman): update Postman collection files
| false
|
diff --git a/postman/collection-json/cybersource.postman_collection.json b/postman/collection-json/cybersource.postman_collection.json
new file mode 100644
index 00000000000..60c4287e17e
--- /dev/null
+++ b/postman/collection-json/cybersource.postman_collection.json
@@ -0,0 +1,19152 @@
+{
+ "event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ "pm.request.headers.add({",
+ " key: 'x-feature',",
+ " value: 'router_custom'",
+ "});",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"[LOG]::payment_id - \" + jsonData.payment_id);",
+ "}",
+ "",
+ "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "item": [
+ {
+ "name": "Health check",
+ "item": [
+ {
+ "name": "New Request",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/accounts - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "x-feature",
+ "value": "router-custom",
+ "type": "text",
+ "disabled": true
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/health",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "health"
+ ]
+ }
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Flow Testcases",
+ "item": [
+ {
+ "name": "QuickStart",
+ "item": [
+ {
+ "name": "Merchant Account - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/accounts - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/accounts - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set merchant_id as variable for jsonData.merchant_id",
+ "if (jsonData?.merchant_id) {",
+ " pm.collectionVariables.set(\"merchant_id\", jsonData.merchant_id);",
+ " console.log(",
+ " \"- use {{merchant_id}} as collection variable for value\",",
+ " jsonData.merchant_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{merchant_id}}, as jsonData.merchant_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "/*",
+ "// pm.collectionVariables - Set api_key as variable for jsonData.api_key",
+ "if (jsonData?.api_key) {",
+ " pm.collectionVariables.set(\"api_key\", jsonData.api_key);",
+ " console.log(\"- use {{api_key}} as collection variable for value\",jsonData.api_key);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.');",
+ "};",
+ "*/",
+ "",
+ "// pm.collectionVariables - Set publishable_key as variable for jsonData.publishable_key",
+ "if (jsonData?.publishable_key) {",
+ " pm.collectionVariables.set(\"publishable_key\", jsonData.publishable_key);",
+ " console.log(",
+ " \"- use {{publishable_key}} as collection variable for value\",",
+ " jsonData.publishable_key,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{publishable_key}}, as jsonData.publishable_key is undefined.\",",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{admin_api_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ },
+ {
+ "key": "x-feature",
+ "value": "router-custom",
+ "type": "text",
+ "disabled": true
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"merchant_id\":\"postman_merchant_GHAction_{{$guid}}\",\"locker_id\":\"m0010\",\"merchant_name\":\"NewAge Retailer\",\"merchant_details\":{\"primary_contact_person\":\"John Test\",\"primary_email\":\"[email protected]\",\"primary_phone\":\"sunt laborum\",\"secondary_contact_person\":\"John Test2\",\"secondary_email\":\"[email protected]\",\"secondary_phone\":\"cillum do dolor id\",\"website\":\"www.example.com\",\"about_business\":\"Online Retail with a wide selection of organic products for North America\",\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\"}},\"return_url\":\"https://duck.com/success\",\"webhook_details\":{\"webhook_version\":\"1.0.1\",\"webhook_username\":\"ekart_retail\",\"webhook_password\":\"password_ekart@123\",\"payment_created_enabled\":true,\"payment_succeeded_enabled\":true,\"payment_failed_enabled\":true},\"sub_merchants_enabled\":false,\"metadata\":{\"city\":\"NY\",\"unit\":\"245\"},\"primary_business_details\":[{\"country\":\"US\",\"business\":\"default\"}]}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/accounts",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "accounts"
+ ]
+ },
+ "description": "Create a new account for a merchant. The merchant could be a seller or retailer or client who likes to receive and send payments."
+ },
+ "response": []
+ },
+ {
+ "name": "API Key - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/api_keys/:merchant_id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/api_keys/:merchant_id - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set api_key_id as variable for jsonData.key_id",
+ "if (jsonData?.key_id) {",
+ " pm.collectionVariables.set(\"api_key_id\", jsonData.key_id);",
+ " console.log(",
+ " \"- use {{api_key_id}} as collection variable for value\",",
+ " jsonData.key_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{api_key_id}}, as jsonData.key_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set api_key as variable for jsonData.api_key",
+ "if (jsonData?.api_key) {",
+ " pm.collectionVariables.set(\"api_key\", jsonData.api_key);",
+ " console.log(",
+ " \"- use {{api_key}} as collection variable for value\",",
+ " jsonData.api_key,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.\",",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{admin_api_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": "{\"name\":\"API Key 1\",\"description\":null,\"expiration\":\"2069-09-23T01:02:03.000Z\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/api_keys/:merchant_id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api_keys",
+ ":merchant_id"
+ ],
+ "variable": [
+ {
+ "key": "merchant_id",
+ "value": "{{merchant_id}}"
+ }
+ ]
+ }
+ },
+ "response": []
+ },
+ {
+ "name": "Payment Connector - Create",
+ "event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(",
+ " \"[POST]::/account/:account_id/connectors - Status code is 2xx\",",
+ " function () {",
+ " pm.response.to.be.success;",
+ " },",
+ ");",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/account/:account_id/connectors - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set merchant_connector_id as variable for jsonData.merchant_connector_id",
+ "if (jsonData?.merchant_connector_id) {",
+ " pm.collectionVariables.set(",
+ " \"merchant_connector_id\",",
+ " jsonData.merchant_connector_id,",
+ " );",
+ " console.log(",
+ " \"- use {{merchant_connector_id}} as collection variable for value\",",
+ " jsonData.merchant_connector_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{merchant_connector_id}}, as jsonData.merchant_connector_id is undefined.\",",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{admin_api_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"connector_type\":\"payment_processor\",\"connector_name\":\"cybersource\",\"connector_account_details\":{\"auth_type\":\"SignatureKey\",\"api_secret\":\"{{connector_api_secret}}\",\"api_key\":\"{{connector_api_key}}\",\"key1\":\"{{connector_key1}}\"},\"test_mode\":false,\"disabled\":false,\"payment_methods_enabled\":[{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"credit\",\"card_networks\":[\"AmericanExpress\",\"Discover\",\"Interac\",\"JCB\",\"Mastercard\",\"Visa\",\"DinersClub\",\"UnionPay\",\"RuPay\"],\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true},{\"payment_method_type\":\"debit\",\"card_networks\":[\"AmericanExpress\",\"Discover\",\"Interac\",\"JCB\",\"Mastercard\",\"Visa\",\"DinersClub\",\"UnionPay\",\"RuPay\"],\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}]}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/account/:account_id/connectors",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "account",
+ ":account_id",
+ "connectors"
+ ],
+ "variable": [
+ {
+ "key": "account_id",
+ "value": "{{merchant_id}}",
+ "description": "(Required) The unique identifier for the merchant account"
+ }
+ ]
+ },
+ "description": "Create a new Payment Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialised services like Fraud / Accounting etc."
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set customer_id as variable for jsonData.customer_id",
+ "if (jsonData?.customer_id) {",
+ " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
+ " console.log(",
+ " \"- use {{customer_id}} as collection variable for value\",",
+ " jsonData.customer_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"succeeded\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have an error message",
+ "if (jsonData?.error_message) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'error_message' is not 'null'\",",
+ " function () {",
+ " pm.expect(jsonData.error_message).is.not.null;",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"connector_transaction_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":12345,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":12345,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// Response body should have \"profile_id\" and not \"null\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'profile_id' exists and is not 'null'\",",
+ " function () {",
+ " pm.expect(typeof jsonData.profile_id !== \"undefined\").to.be.true;",
+ " pm.expect(jsonData.profile_id).is.not.null;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":600,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/refunds",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds"
+ ]
+ },
+ "description": "To create a refund against an already processed payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/refunds/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{refund_id}}",
+ "description": "(Required) unique refund id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Happy Cases",
+ "item": [
+ {
+ "name": "Scenario12- Zero auth mandates",
+ "item": [
+ {
+ "name": "Mandate Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Validate if response has JSON Body ",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
+ "",
+ "",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
+ "if (jsonData?.status) {",
+ "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\", function() {",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ "})};",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(\"[POST]::/payments - Content check if 'mandate_id' exists\", function() {",
+ " pm.expect((typeof jsonData.mandate_id !== \"undefined\")).to.be.true;",
+ "});",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(\"[POST]::/payments - Content check if 'mandate_data' exists\", function() {",
+ " pm.expect((typeof jsonData.mandate_data !== \"undefined\")).to.be.true;",
+ "});",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{api_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":0,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"order_details\":[{\"product_name\":\"Apple iphone 15\",\"quantity\":1,\"amount\":0,\"account_name\":\"transaction_processing\"}],\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Confirm",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Validate if response has JSON Body ",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\", function() {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ "})};",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(\"[POST]::/payments - Content check if 'mandate_id' exists\", function() {",
+ " pm.expect((typeof jsonData.mandate_id !== \"undefined\")).to.be.true;",
+ "});",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(\"[POST]::/payments - Content check if 'mandate_data' exists\", function() {",
+ " pm.expect((typeof jsonData.mandate_data !== \"undefined\")).to.be.true;",
+ "});",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{api_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ },
+ {
+ "key": "x-feature",
+ "value": "router-custom",
+ "type": "text",
+ "disabled": true
+ },
+ {
+ "key": "publishable_key",
+ "value": "pk_snd_8798c6a9114646f8b970b93ad5765ddf",
+ "type": "text",
+ "disabled": true
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"03\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"CLBRW1\",\"card_cvc\":\"737\"}},\"setup_future_usage\":\"off_session\",\"payment_type\":\"setup_mandate\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"125.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":1000,\"currency\":\"USD\",\"start_date\":\"2023-04-21T00:00:00Z\",\"end_date\":\"2023-05-21T00:00:00Z\",\"metadata\":{\"frequency\":\"13\"}}}}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/confirm",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}"
+ }
+ ]
+ },
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ },
+ "response": []
+ },
+ {
+ "name": "Recurring Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Validate if response has JSON Body ",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
+ "",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\", function() {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ "})};",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(\"[POST]::/payments - Content check if 'mandate_id' exists\", function() {",
+ " pm.expect((typeof jsonData.mandate_id !== \"undefined\")).to.be.true;",
+ "});",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(\"[POST]::/payments - Content check if 'mandate_data' exists\", function() {",
+ " pm.expect((typeof jsonData.mandate_data !== \"undefined\")).to.be.true;",
+ "});",
+ "",
+ "// Response body should have \"payment_method_data\"",
+ "pm.test(\"[POST]::/payments - Content check if 'payment_method_data' exists\", function() {",
+ " pm.expect((typeof jsonData.payment_method_data !== \"undefined\")).to.be.true;",
+ "});",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{api_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":1000,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://google.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"billing\":{\"address\":{\"first_name\":\"John\",\"last_name\":\"Doe\",\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"first_name\":\"John\",\"last_name\":\"Doe\",\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"},\"order_details\":[{\"product_name\":\"Apple iphone 15\",\"quantity\":1,\"amount\":1000,\"account_name\":\"transaction_processing\"}]}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario13 Incremental auth",
+ "item": [
+ {
+ "name": "Payments-Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Validate if response has JSON Body ",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ },
+ {
+ "key": "x-feature",
+ "value": "router-custom",
+ "type": "text",
+ "disabled": true
+ },
+ {
+ "key": "Authorization",
+ "value": "",
+ "type": "text",
+ "disabled": true
+ },
+ {
+ "key": "x-feature",
+ "value": "integ-custom",
+ "type": "text",
+ "disabled": true
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":1000,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"amount_to_capture\":1000,\"description\":\"Its my first payment request\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"return_url\":\"https://google.com\",\"name\":\"Preetam\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"authentication_type\":\"no_three_ds\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"09\",\"card_exp_year\":\"2027\",\"card_holder_name\":\"\",\"card_cvc\":\"975\"}},\"connector_metadata\":{\"noon\":{\"order_category\":\"pay\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"128.0.0.1\"},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"PL\",\"first_name\":\"preetam\",\"last_name\":\"revankar\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"PL\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"order_details\":[{\"product_name\":\"Apple iphone 15\",\"quantity\":1,\"amount\":1000,\"account_name\":\"transaction_processing\"}],\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"request_incremental_authorization\":true,\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Incremental Authorization",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "pm.test(\"[POST]::/payments:id/incremental_authorizations - Content check if value for 'amount' matches '1001'\", function () {",
+ " // Parse the response JSON",
+ " var jsonData = pm.response.json();",
+ "",
+ " // Check if the 'amount' in the response matches the expected value",
+ " pm.expect(jsonData.incremental_authorizations[0].amount).to.eql(1001);",
+ "});",
+ "",
+ "pm.test(\"[POST]::/payments:id/incremental_authorizations - Content check if value for 'status' matches 'success'\", function () {",
+ " // Parse the response JSON",
+ " var jsonData = pm.response.json();",
+ "",
+ " // Check if the 'status' in the response matches the expected value",
+ " pm.expect(jsonData.incremental_authorizations[0].status).to.eql(\"success\");",
+ "});",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":1001}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/{{payment_id}}/incremental_authorization",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ "{{payment_id}}",
+ "incremental_authorization"
+ ]
+ }
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Validate if response has JSON Body ",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
+ "",
+ "",
+ "// Response body should have value \"requires_capture\" for \"status\"",
+ "if (jsonData?.status) {",
+ "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\", function() {",
+ " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
+ "})};"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ },
+ {
+ "key": "x-feature",
+ "value": "router-custom",
+ "type": "text",
+ "disabled": true
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?expand_attempts=true&force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "expand_attempts",
+ "value": "true"
+ },
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Capture",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/capture - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"1001\" for \"amount\"",
+ "if (jsonData?.amount) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '1001'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(1001);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"1001\" for \"amount_received\"",
+ "if (jsonData?.amount_received) {",
+ " pm.test(",
+ " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '1001'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_received).to.eql(1001);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount_to_capture\":1001,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/capture",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "capture"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To capture the funds for an uncaptured payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"pending\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"pending\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"1001\" for \"amount\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(1001);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":1001,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/refunds",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds"
+ ]
+ },
+ "description": "To create a refund against an already processed payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"pending\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"pending\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"1001\" for \"amount\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '1001'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(1001);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/refunds/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{refund_id}}",
+ "description": "(Required) unique refund id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario14 Incremental auth for mandates",
+ "item": [
+ {
+ "name": "Payments-Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Validate if response has JSON Body ",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ },
+ {
+ "key": "x-feature",
+ "value": "router-custom",
+ "type": "text",
+ "disabled": true
+ },
+ {
+ "key": "Authorization",
+ "value": "",
+ "type": "text",
+ "disabled": true
+ },
+ {
+ "key": "x-feature",
+ "value": "integ-custom",
+ "type": "text",
+ "disabled": true
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":1000,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"amount_to_capture\":1000,\"description\":\"Its my first payment request\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"return_url\":\"https://google.com\",\"name\":\"Preetam\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"authentication_type\":\"no_three_ds\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"09\",\"card_exp_year\":\"2027\",\"card_holder_name\":\"\",\"card_cvc\":\"975\"}},\"connector_metadata\":{\"noon\":{\"order_category\":\"pay\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"128.0.0.1\"},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"PL\",\"first_name\":\"preetam\",\"last_name\":\"revankar\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"PL\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"order_details\":[{\"product_name\":\"Apple iphone 15\",\"quantity\":1,\"amount\":1000,\"account_name\":\"transaction_processing\"}],\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"request_incremental_authorization\":true,\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Incremental Authorization",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "pm.test(\"[POST]::/payments:id/incremental_authorizations - Content check if value for 'amount' matches '1001'\", function () {",
+ " // Parse the response JSON",
+ " var jsonData = pm.response.json();",
+ "",
+ " // Check if the 'amount' in the response matches the expected value",
+ " pm.expect(jsonData.incremental_authorizations[0].amount).to.eql(1001);",
+ "});",
+ "",
+ "pm.test(\"[POST]::/payments:id/incremental_authorizations - Content check if value for 'status' matches 'success'\", function () {",
+ " // Parse the response JSON",
+ " var jsonData = pm.response.json();",
+ "",
+ " // Check if the 'status' in the response matches the expected value",
+ " pm.expect(jsonData.incremental_authorizations[0].status).to.eql(\"success\");",
+ "});",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":1001}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/{{payment_id}}/incremental_authorization",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ "{{payment_id}}",
+ "incremental_authorization"
+ ]
+ }
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Validate if response has JSON Body ",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
+ "",
+ "",
+ "// Response body should have value \"requires_capture\" for \"status\"",
+ "if (jsonData?.status) {",
+ "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\", function() {",
+ " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
+ "})};"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ },
+ {
+ "key": "x-feature",
+ "value": "router-custom",
+ "type": "text",
+ "disabled": true
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?expand_attempts=true&force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "expand_attempts",
+ "value": "true"
+ },
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Capture",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/capture - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"1001\" for \"amount\"",
+ "if (jsonData?.amount) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '1001'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(1001);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"1001\" for \"amount_received\"",
+ "if (jsonData?.amount_received) {",
+ " pm.test(",
+ " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '1001'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_received).to.eql(1001);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount_to_capture\":1001,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/capture",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "capture"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To capture the funds for an uncaptured payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario15 Incremental auth with partial capture",
+ "item": [
+ {
+ "name": "Payments-Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Validate if response has JSON Body ",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{api_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ },
+ {
+ "key": "Authorization",
+ "value": "",
+ "type": "text",
+ "disabled": true
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":1000,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"amount_to_capture\":1000,\"description\":\"Its my first payment request\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"return_url\":\"https://google.com\",\"name\":\"Preetam\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"authentication_type\":\"no_three_ds\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"09\",\"card_exp_year\":\"2027\",\"card_holder_name\":\"\",\"card_cvc\":\"975\"}},\"connector_metadata\":{\"noon\":{\"order_category\":\"pay\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"128.0.0.1\"},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"PL\",\"first_name\":\"preetam\",\"last_name\":\"revankar\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"PL\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"order_details\":[{\"product_name\":\"Apple iphone 15\",\"quantity\":1,\"amount\":1000,\"account_name\":\"transaction_processing\"}],\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"request_incremental_authorization\":true,\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Incremental Authorization",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "pm.test(\"[POST]::/payments:id/incremental_authorizations - Content check if value for 'amount' matches '1001'\", function () {",
+ " // Parse the response JSON",
+ " var jsonData = pm.response.json();",
+ "",
+ " // Check if the 'amount' in the response matches the expected value",
+ " pm.expect(jsonData.incremental_authorizations[0].amount).to.eql(1001);",
+ "});",
+ "",
+ "pm.test(\"[POST]::/payments:id/incremental_authorizations - Content check if value for 'status' matches 'success'\", function () {",
+ " // Parse the response JSON",
+ " var jsonData = pm.response.json();",
+ "",
+ " // Check if the 'status' in the response matches the expected value",
+ " pm.expect(jsonData.incremental_authorizations[0].status).to.eql(\"success\");",
+ "});",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":1001}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/{{payment_id}}/incremental_authorization",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ "{{payment_id}}",
+ "incremental_authorization"
+ ]
+ }
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Validate if response has JSON Body ",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
+ "",
+ "",
+ "// Response body should have value \"requires_capture\" for \"status\"",
+ "if (jsonData?.status) {",
+ "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\", function() {",
+ " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
+ "})};"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ },
+ {
+ "key": "x-feature",
+ "value": "router-custom",
+ "type": "text",
+ "disabled": true
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?expand_attempts=true&force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "expand_attempts",
+ "value": "true"
+ },
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Capture",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/capture - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"partially_captured\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'partially_captured'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"partially_captured\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"1001\" for \"amount\"",
+ "if (jsonData?.amount) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '1001'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(1001);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"500\" for \"amount_received\"",
+ "if (jsonData?.amount_received) {",
+ " pm.test(",
+ " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '500'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_received).to.eql(500);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount_to_capture\":500,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/capture",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "capture"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To capture the funds for an uncaptured payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"pending\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"pending\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"500\" for \"amount\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '500'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(500);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":500,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/refunds",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds"
+ ]
+ },
+ "description": "To create a refund against an already processed payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"pending\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"pending\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"500\" for \"amount\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '500'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(500);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/refunds/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{refund_id}}",
+ "description": "(Required) unique refund id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario17- Revoke mandates",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "List - Mandates",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "",
+ "// Response body should have value \"active\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'active'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"active\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/mandates/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "mandates",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{mandate_id}}",
+ "description": "(Required) Unique mandate id"
+ }
+ ]
+ },
+ "description": "To list the details of a mandate"
+ },
+ "response": []
+ },
+ {
+ "name": "Revoke - Mandates",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "",
+ "// Response body should have value \"revoked\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'revoked'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"revoked\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/mandates/revoke/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "mandates",
+ "revoke",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{mandate_id}}"
+ }
+ ]
+ },
+ "description": "To revoke a mandate registered against a customer"
+ },
+ "response": []
+ },
+ {
+ "name": "List - Mandates-copy",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "",
+ "// Response body should have value \"revoked\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'revoked'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"revoked\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/mandates/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "mandates",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{mandate_id}}",
+ "description": "(Required) Unique mandate id"
+ }
+ ]
+ },
+ "description": "To list the details of a mandate"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario18- Update mandate card details",
+ "item": [
+ {
+ "name": "Mandate -Update",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":0,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"12\",\"card_exp_year\":\"30\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"payment_type\":\"setup_mandate\",\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"update_mandate_id\":\"{{mandate_id}}\",\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "if (jsonData?.customer_id) {",
+ " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
+ " console.log(",
+ " \"- use {{customer_id}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.\",",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":0,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"customer_{{$randomAbbreviation}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"payment_type\":\"setup_mandate\",\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "List - Mandates",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "",
+ "// Response body should have value \"active\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'active'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"active\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "pm.test(\"[POST]::/payments - Verify last 4 digits of the card\", function () {",
+ " var jsonData = pm.response.json();",
+ " pm.expect(jsonData.card.last4_digits).to.eql(\"4242\");",
+ "});",
+ "",
+ "pm.test(\"[POST]::/payments - Verify card expiration month\", function () {",
+ " var jsonData = pm.response.json();",
+ " pm.expect(jsonData.card.card_exp_month).to.eql(\"10\");",
+ "});",
+ "",
+ "pm.test(\"[POST]::/payments - Verify card expiration year\", function () {",
+ " var jsonData = pm.response.json();",
+ " pm.expect(jsonData.card.card_exp_year).to.eql(\"25\");",
+ "});",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/mandates/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "mandates",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{mandate_id}}",
+ "description": "(Required) Unique mandate id"
+ }
+ ]
+ },
+ "description": "To list the details of a mandate"
+ },
+ "response": []
+ },
+ {
+ "name": "List - Mandates-copy",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "",
+ "// Response body should have value \"active\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'active'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"active\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "pm.test(\"[POST]::/payments - Verify last 4 digits of the card\", function () {",
+ " var jsonData = pm.response.json();",
+ " pm.expect(jsonData.card.last4_digits).to.eql(\"1111\");",
+ "});",
+ "",
+ "pm.test(\"[POST]::/payments - Verify card expiration month\", function () {",
+ " var jsonData = pm.response.json();",
+ " pm.expect(jsonData.card.card_exp_month).to.eql(\"12\");",
+ "});",
+ "",
+ "pm.test(\"[POST]::/payments - Verify card expiration year\", function () {",
+ " var jsonData = pm.response.json();",
+ " pm.expect(jsonData.card.card_exp_year).to.eql(\"30\");",
+ "});",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/mandates/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "mandates",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{mandate_id}}",
+ "description": "(Required) Unique mandate id"
+ }
+ ]
+ },
+ "description": "To list the details of a mandate"
+ },
+ "response": []
+ },
+ {
+ "name": "Recurring Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"payment_method_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'payment_method_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve-copy",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario19- Create 3ds payment",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_customer_action\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"connector_transaction_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ },
+ {
+ "key": "x-feature",
+ "value": "router-custom",
+ "type": "text"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"setup_future_usage\":\"on_session\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000001000\",\"card_exp_month\":\"01\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_customer_action\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_customer_action'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"connector_transaction_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario20- Create 3ds mandate",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_customer_action\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"connector_transaction_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ },
+ {
+ "key": "x-feature",
+ "value": "router-custom",
+ "type": "text"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000001000\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_customer_action\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_customer_action'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"connector_transaction_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario1-Create payment with confirm true",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"connector_transaction_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ },
+ {
+ "key": "x-feature",
+ "value": "router-custom",
+ "type": "text"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"connector_transaction_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario2-Create payment with confirm false",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Confirm",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"Joseph Doe\",\"card_cvc\":\"123\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/confirm",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario2a-Create payment with confirm false card holder name null",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Confirm",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":null,\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/confirm",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario2b-Create payment with confirm false card holder name empty",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Confirm",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}"
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"\",\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/confirm",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario3-Create payment without PMD",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Confirm",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments:id/confirm - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/confirm",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario4-Create payment with Manual capture",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_capture\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Capture",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/capture - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.amount) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6000\" for \"amount_received\"",
+ "if (jsonData?.amount_received) {",
+ " pm.test(",
+ " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_received).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount_to_capture\":6540,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/capture",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "capture"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To capture the funds for an uncaptured payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario4a-Create payment with partial capture",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_capture\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Capture",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/capture - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'partially_captured'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"partially_captured\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.amount) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6000\" for \"amount_received\"",
+ "if (jsonData?.amount_received) {",
+ " pm.test(",
+ " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6000'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_received).to.eql(6000);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount_to_capture\":6000,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/capture",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "capture"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To capture the funds for an uncaptured payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'partially_captured'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"partially_captured\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario5-Void the payment",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_capture\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Cancel",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/cancel - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/cancel - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/cancel - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"cancelled\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/cancel - Content check if value for 'status' matches 'cancelled'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"cancelled\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"cancellation_reason\":\"requested_by_customer\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/cancel",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "cancel"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "A Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"cancelled\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'cancelled'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"cancelled\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario6-Refund full payment",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"pending\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"pending\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":6540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/refunds",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds"
+ ]
+ },
+ "description": "To create a refund against an already processed payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"pending\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"pending\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/refunds/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{refund_id}}",
+ "description": "(Required) unique refund id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario6a-Partial refund",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"pending\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"pending\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"540\" for \"amount\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(540);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/refunds",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds"
+ ]
+ },
+ "description": "To create a refund against an already processed payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"pending\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"pending\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(540);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/refunds/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{refund_id}}",
+ "description": "(Required) unique refund id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Create-copy",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"pending\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"pending\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"1000\" for \"amount\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '1000'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(1000);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":1000,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/refunds",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds"
+ ]
+ },
+ "description": "To create a refund against an already processed payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Retrieve-copy",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"pending\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"pending\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '1000'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(1000);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/refunds/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{refund_id}}",
+ "description": "(Required) unique refund id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve-copy",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"refunds\"",
+ "pm.test(\"[POST]::/payments - Content check if 'refunds' exists\", function () {",
+ " pm.expect(typeof jsonData.refunds !== \"undefined\").to.be.true;",
+ "});",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario7-Create a mandate and recurring payment",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Confirm",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"Joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/confirm",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ },
+ "response": []
+ },
+ {
+ "name": "List payment methods for a Customer",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[GET]::/payment_methods/:customer_id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payment_methods/:customer_id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "if (jsonData?.customer_payment_methods[0]?.payment_token) {",
+ " pm.collectionVariables.set(\"payment_token\", jsonData.customer_payment_methods[0].payment_token);",
+ " console.log(\"- use {{payment_token}} as collection variable for value\", jsonData.customer_payment_methods[0].payment_token);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_token}}, as jsonData.customer_payment_methods[0].payment_token is undefined.');",
+ "}"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/customers/:customer_id/payment_methods",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "customers",
+ ":customer_id",
+ "payment_methods"
+ ],
+ "variable": [
+ {
+ "key": "customer_id",
+ "value": "{{customer_id}}",
+ "description": "//Pass the customer id"
+ }
+ ]
+ },
+ "description": "To filter and list the applicable payment methods for a particular Customer ID"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Recurring Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"payment_method_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'payment_method_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve-copy",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario7a-Manual capture for recurring payments",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Recurring Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_capture\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"payment_method_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'payment_method_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Capture",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/capture - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.amount) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6000\" for \"amount_received\"",
+ "if (jsonData?.amount_received) {",
+ " pm.test(",
+ " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_received).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount_to_capture\":6540,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/capture",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "capture"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To capture the funds for an uncaptured payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve-copy",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario8-Refund recurring payment",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Recurring Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"payment_method_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'payment_method_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6570,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6570,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve-copy",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"pending\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"pending\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":6540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/refunds",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds"
+ ]
+ },
+ "description": "To create a refund against an already processed payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"pending\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"pending\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/refunds/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{refund_id}}",
+ "description": "(Required) unique refund id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario9-Add card flow",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Validate if response has JSON Body ",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
+ "",
+ "if (jsonData?.customer_id) {",
+ " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
+ " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');",
+ "};",
+ "",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_payment_method'\", function() {",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ " })};"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"stripesavecard_{{random_number}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Confirm",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"03\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"737\"}},\"setup_future_usage\":\"on_session\",\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/confirm",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ },
+ "response": []
+ },
+ {
+ "name": "List payment methods for a Customer",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[GET]::/payment_methods/:customer_id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payment_methods/:customer_id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "if (jsonData?.customer_payment_methods[0]?.payment_token) {",
+ " pm.collectionVariables.set(\"payment_token\", jsonData.customer_payment_methods[0].payment_token);",
+ " console.log(\"- use {{payment_token}} as collection variable for value\", jsonData.customer_payment_methods[0].payment_token);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_token}}, as jsonData.customer_payment_methods[0].payment_token is undefined.');",
+ "}"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/customers/:customer_id/payment_methods",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "customers",
+ ":customer_id",
+ "payment_methods"
+ ],
+ "variable": [
+ {
+ "key": "customer_id",
+ "value": "{{customer_id}}",
+ "description": "//Pass the customer id"
+ }
+ ]
+ },
+ "description": "To filter and list the applicable payment methods for a particular Customer ID"
+ },
+ "response": []
+ },
+ {
+ "name": "Save card payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Validate if response has JSON Body ",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
+ "",
+ "if (jsonData?.customer_id) {",
+ " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
+ " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');",
+ "};"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Save card payments - Confirm",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "",
+ "// Response body should have value \"cybersource\" for \"connector\"",
+ "if (jsonData?.connector) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'cybersource'\",",
+ " function () {",
+ " pm.expect(jsonData.connector).to.eql(\"cybersource\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_token\":\"{{payment_token}}\",\"card_cvc\":\"737\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/confirm",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":600,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/refunds",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds"
+ ]
+ },
+ "description": "To create a refund against an already processed payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/refunds/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{refund_id}}",
+ "description": "(Required) unique refund id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario10-Don't Pass CVV for save card flow and verifysuccess payment",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Validate if response has JSON Body ",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
+ "",
+ "if (jsonData?.customer_id) {",
+ " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
+ " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');",
+ "};"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"stripesavecard_{{random_number}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"371449635398431\",\"card_exp_month\":\"03\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"7373\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "List payment methods for a Customer",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[GET]::/payment_methods/:customer_id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payment_methods/:customer_id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "if (jsonData?.customer_payment_methods[0]?.payment_token) {",
+ " pm.collectionVariables.set(\"payment_token\", jsonData.customer_payment_methods[0].payment_token);",
+ " console.log(\"- use {{payment_token}} as collection variable for value\", jsonData.customer_payment_methods[0].payment_token);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_token}}, as jsonData.customer_payment_methods[0].payment_token is undefined.');",
+ "}"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/customers/:customer_id/payment_methods",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "customers",
+ ":customer_id",
+ "payment_methods"
+ ],
+ "variable": [
+ {
+ "key": "customer_id",
+ "value": "{{customer_id}}",
+ "description": "//Pass the customer id"
+ }
+ ]
+ },
+ "description": "To filter and list the applicable payment methods for a particular Customer ID"
+ },
+ "response": []
+ },
+ {
+ "name": "Save card payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Validate if response has JSON Body ",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
+ "",
+ "if (jsonData?.customer_id) {",
+ " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
+ " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');",
+ "};"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Save card payments - Confirm",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"cybersource\" for \"connector\"",
+ "if (jsonData?.connector) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'cybersource'\",",
+ " function () {",
+ " pm.expect(jsonData.connector).to.eql(\"cybersource\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\", function() {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " })};"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_token\":\"{{payment_token}}\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/confirm",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario11-Save card payment with manual capture",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Validate if response has JSON Body ",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
+ "",
+ "if (jsonData?.customer_id) {",
+ " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
+ " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');",
+ "};",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"adyensavecard_{{random_number}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"371449635398431\",\"card_exp_month\":\"03\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"7373\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Validate the connector",
+ "pm.test(\"[POST]::/payments - connector\", function () {",
+ " pm.expect(jsonData.connector).to.eql(\"cybersource\");",
+ "});",
+ "",
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.amount) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6000\" for \"amount_received\"",
+ "if (jsonData?.amount_received) {",
+ " pm.test(",
+ " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6000'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_received).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"0\" for \"amount_capturable\"",
+ "if (jsonData?.amount) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount_capturable' matches 'amount - 0'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_capturable).to.eql(0);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "List payment methods for a Customer",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[GET]::/payment_methods/:customer_id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payment_methods/:customer_id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "if (jsonData?.customer_payment_methods[0]?.payment_token) {",
+ " pm.collectionVariables.set(\"payment_token\", jsonData.customer_payment_methods[0].payment_token);",
+ " console.log(\"- use {{payment_token}} as collection variable for value\", jsonData.customer_payment_methods[0].payment_token);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_token}}, as jsonData.customer_payment_methods[0].payment_token is undefined.');",
+ "}"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/customers/:customer_id/payment_methods",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "customers",
+ ":customer_id",
+ "payment_methods"
+ ],
+ "variable": [
+ {
+ "key": "customer_id",
+ "value": "{{customer_id}}",
+ "description": "//Pass the customer id"
+ }
+ ]
+ },
+ "description": "To filter and list the applicable payment methods for a particular Customer ID"
+ },
+ "response": []
+ },
+ {
+ "name": "Save card payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Validate if response has JSON Body ",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
+ "",
+ "if (jsonData?.customer_id) {",
+ " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
+ " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');",
+ "};"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Save card payments - Confirm",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_capture\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_capture'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "",
+ "// Response body should have value \"cybersource\" for \"connector\"",
+ "if (jsonData?.connector) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'cybersource'\",",
+ " function () {",
+ " pm.expect(jsonData.connector).to.eql(\"cybersource\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_token\":\"{{payment_token}}\",\"card_cvc\":\"7373\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/confirm",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Capture",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/capture - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Validate the connector",
+ "pm.test(\"[POST]::/payments - connector\", function () {",
+ " pm.expect(jsonData.connector).to.eql(\"cybersource\");",
+ "});",
+ "",
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.amount) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6000\" for \"amount_received\"",
+ "if (jsonData?.amount_received) {",
+ " pm.test(",
+ " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_received).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6540\" for \"amount_capturable\"",
+ "if (jsonData?.amount_capturable) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount_capturable' matches 'amount - 540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_capturable).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount_to_capture\":6540,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/capture",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "capture"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To capture the funds for an uncaptured payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve-copy",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Validate the connector",
+ "pm.test(\"[POST]::/payments - connector\", function () {",
+ " pm.expect(jsonData.connector).to.eql(\"cybersource\");",
+ "});",
+ "",
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.amount) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6000\" for \"amount_received\"",
+ "if (jsonData?.amount_received) {",
+ " pm.test(",
+ " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_received).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"0\" for \"amount_capturable\"",
+ "if (jsonData?.amount) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount_capturable' matches 'amount - 0'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_capturable).to.eql(0);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"pending\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"pending\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"540\" for \"amount\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(540);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Validate the connector",
+ "pm.test(\"[POST]::/payments - connector\", function () {",
+ " pm.expect(jsonData.connector).to.eql(\"cybersource\");",
+ "});",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/refunds",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds"
+ ]
+ },
+ "description": "To create a refund against an already processed payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"pending\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"pending\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(540);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/refunds/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{refund_id}}",
+ "description": "(Required) unique refund id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario16-Verify PML for mandate",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_confirmation\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "List payment methods for a Merchant",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(",
+ " \"[GET]::/payment_methods/:merchant_id - Status code is 2xx\",",
+ " function () {",
+ " pm.response.to.be.success;",
+ " },",
+ ");",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[GET]::/payment_methods/:merchant_id - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "",
+ "// Response body should have value \"new_mandate\" for \"payment_type\"",
+ "if (jsonData?.payment_type) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'payment_type' matches 'new_mandate'\",",
+ " function () {",
+ " pm.expect(jsonData.payment_type).to.eql(\"new_mandate\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/account/payment_methods?client_secret={{client_secret}}",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "account",
+ "payment_methods"
+ ],
+ "query": [
+ {
+ "key": "client_secret",
+ "value": "{{client_secret}}"
+ }
+ ]
+ },
+ "description": "To filter and list the applicable payment methods for a particular merchant id."
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Create-copy",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "if (jsonData?.customer_id) {",
+ " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
+ " console.log(",
+ " \"- use {{customer_id}} as collection variable for value\",",
+ " jsonData.customer_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.\",",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":0,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"payment_type\":\"setup_mandate\",\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "List payment methods for a Merchant-copy",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(",
+ " \"[GET]::/payment_methods/:merchant_id - Status code is 2xx\",",
+ " function () {",
+ " pm.response.to.be.success;",
+ " },",
+ ");",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[GET]::/payment_methods/:merchant_id - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "",
+ "// Response body should have value \"setup_mandate\" for \"payment_type\"",
+ "if (jsonData?.payment_type) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'payment_type' matches 'setup_mandate'\",",
+ " function () {",
+ " pm.expect(jsonData.payment_type).to.eql(\"setup_mandate\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/account/payment_methods?client_secret={{client_secret}}",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "account",
+ "payment_methods"
+ ],
+ "query": [
+ {
+ "key": "client_secret",
+ "value": "{{client_secret}}"
+ }
+ ]
+ },
+ "description": "To filter and list the applicable payment methods for a particular merchant id."
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario21-Create a mandate without customer acceptance",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set customer_id as variable for jsonData.customer_id",
+ "if (jsonData?.customer_id) {",
+ " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
+ " console.log(",
+ " \"- use {{customer_id}} as collection variable for value\",",
+ " jsonData.customer_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"customer{{$randomAlphaNumeric}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Confirm",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"Joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/confirm",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Recurring Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"payment_method_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'payment_method_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve-copy",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "Variation Cases",
+ "item": [
+ {
+ "name": "Scenario10- Manual multiple capture",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 5xx",
+ "pm.test(\"[POST]::/payments - Status code is 5xx\", function () {",
+ " pm.response.to.be.error;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "// Response body should have value \"connector error\" for \"error type\"",
+ "if (jsonData?.error?.type) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'error.type' matches 'invalid_request'\",",
+ " function () {",
+ " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");",
+ " },",
+ " );",
+ "",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual_multiple\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario13- Revoke for revoked mandates",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Revoke - Mandates",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "",
+ "// Response body should have value \"revoked\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'revoked'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"revoked\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/mandates/revoke/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "mandates",
+ "revoke",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{mandate_id}}"
+ }
+ ]
+ },
+ "description": "To revoke a mandate registered against a customer"
+ },
+ "response": []
+ },
+ {
+ "name": "Revoke - Mandates-copy",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 4xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 4xx\", function () {",
+ " pm.response.to.be.error;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// Response body should have value \"connector error\" for \"error type\"",
+ "if (jsonData?.error?.type) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'error.type' matches 'invalid_request'\",",
+ " function () {",
+ " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "pm.test(\"[POST]::/payments - Content check if value for 'error.reason' matches 'Mandate has already been revoked\", function () {",
+ " pm.expect(jsonData.error.reason).to.eql(\"Mandate has already been revoked\");",
+ "});",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/mandates/revoke/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "mandates",
+ "revoke",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{mandate_id}}"
+ }
+ ]
+ },
+ "description": "To revoke a mandate registered against a customer"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario14- Recurring payment for revoked mandates",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Revoke - Mandates",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "",
+ "// Response body should have value \"revoked\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'revoked'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"revoked\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/mandates/revoke/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "mandates",
+ "revoke",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{mandate_id}}"
+ }
+ ]
+ },
+ "description": "To revoke a mandate registered against a customer"
+ },
+ "response": []
+ },
+ {
+ "name": "Recurring Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 4xx",
+ "pm.test(\"[POST]::/payments - Status code is 4xx\", function () {",
+ " pm.response.to.be.error;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"connector error\" for \"error type\"",
+ "if (jsonData?.error?.type) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'error.type' matches 'invalid_request'\",",
+ " function () {",
+ " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "pm.test(\"[POST]::/payments - Content check if value for 'error.message' matches 'Mandate is not active\", function () {",
+ " pm.expect(jsonData.error.message).to.eql(\"mandate is not active\");",
+ "});",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario15- Setup_future_usage is off_session for normal payments",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 4xx",
+ "pm.test(\"[POST]::/payments - Status code is 4xx\", function () {",
+ " pm.response.to.be.error;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"connector error\" for \"error type\"",
+ "if (jsonData?.error?.type) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'error.type' matches 'invalid_request'\",",
+ " function () {",
+ " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "pm.test(\"[POST]::/payments - Content check if value for 'error.message' matches 'setup_future_usage` cannot be `off_session` for normal payments\", function () {",
+ " pm.expect(jsonData.error.message).to.eql(\"`setup_future_usage` cannot be `off_session` for normal payments\");",
+ "});",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"customer_{{$randomAlphaNumeric}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"setup_future_usage\":\"off_session\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario16- Setup_future_usage is on_session for mandates payments -confirm false",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set customer_id as variable for jsonData.customer_id",
+ "if (jsonData?.customer_id) {",
+ " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
+ " console.log(",
+ " \"- use {{customer_id}} as collection variable for value\",",
+ " jsonData.customer_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"customer{{$randomAlphaNumeric}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Confirm",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 4xx",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 4xx\", function () {",
+ " pm.response.to.be.error;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"connector error\" for \"error type\"",
+ "if (jsonData?.error?.type) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'error.type' matches 'invalid_request'\",",
+ " function () {",
+ " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "pm.test(\"[POST]::/payments - Content check if value for 'error.message' matches 'setup_future_usage` cannot be `off_session` for normal payments\", function () {",
+ " pm.expect(jsonData.error.message).to.eql(\"`setup_future_usage` must be `off_session` for mandates\");",
+ "});",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"Joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"setup_future_usage\":\"on_session\",\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/confirm",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario17- Setup_future_usage is null for normal payments",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set customer_id as variable for jsonData.customer_id",
+ "if (jsonData?.customer_id) {",
+ " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
+ " console.log(",
+ " \"- use {{customer_id}} as collection variable for value\",",
+ " jsonData.customer_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"customer{{$randomAlphaNumeric}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Confirm",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}"
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"Joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":null,\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"125.0.0.1\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/confirm",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ },
+ "response": []
+ },
+ {
+ "name": "List payment methods for a Customer",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[GET]::/payment_methods/:customer_id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payment_methods/:customer_id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "pm.test(\"[GET]::/payment_methods/:customer_id Check if card not stored in the locker \", function () {",
+ " var jsonData = pm.response.json();",
+ " pm.expect(jsonData.customer_payment_methods).to.be.an('array').that.is.empty;",
+ "});"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/customers/:customer_id/payment_methods",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "customers",
+ ":customer_id",
+ "payment_methods"
+ ],
+ "variable": [
+ {
+ "key": "customer_id",
+ "value": "{{customer_id}}",
+ "description": "//Pass the customer id"
+ }
+ ]
+ },
+ "description": "To filter and list the applicable payment methods for a particular Customer ID"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario1-Create payment with Invalid card details",
+ "item": [
+ {
+ "name": "Payments - Create(Invalid card number)",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 4xx",
+ "pm.test(\"[POST]::/payments - Status code is 4xx\", function () {",
+ " pm.response.to.be.error;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"error\"",
+ "pm.test(\"[POST]::/payments - Content check if 'error' exists\", function () {",
+ " pm.expect(typeof jsonData.error !== \"undefined\").to.be.true;",
+ "});",
+ "",
+ "// Response body should have value \"connector error\" for \"error type\"",
+ "if (jsonData?.error?.type) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'error.type' matches 'connector_error'\",",
+ " function () {",
+ " pm.expect(jsonData.error.type).to.eql(\"connector_error\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"123456\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"united states\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"united states\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Create(Invalid Exp month)",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 4xx",
+ "pm.test(\"[POST]::/payments - Status code is 4xx\", function () {",
+ " pm.response.to.be.error;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"next_action.redirect_to_url\"",
+ "pm.test(\"[POST]::/payments - Content check if 'error' exists\", function () {",
+ " pm.expect(typeof jsonData.error !== \"undefined\").to.be.true;",
+ "});",
+ "",
+ "// Response body should have value \"connector error\" for \"error type\"",
+ "if (jsonData?.error?.type) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'error.type' matches 'invalid_request'\",",
+ " function () {",
+ " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"2023\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Create(Invalid Exp Year)",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 4xx",
+ "pm.test(\"[POST]::/payments - Status code is 4xx\", function () {",
+ " pm.response.to.be.error;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"next_action.redirect_to_url\"",
+ "pm.test(\"[POST]::/payments - Content check if 'error' exists\", function () {",
+ " pm.expect(typeof jsonData.error !== \"undefined\").to.be.true;",
+ "});",
+ "",
+ "// Response body should have value \"connector error\" for \"error type\"",
+ "if (jsonData?.error?.type) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'error.type' matches 'invalid_request'\",",
+ " function () {",
+ " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"connector error\" for \"error message\"",
+ "if (jsonData?.error?.message) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'error.message' matches 'Invalid Expiry Year'\",",
+ " function () {",
+ " pm.expect(jsonData.error.message).to.eql(\"Invalid Expiry Year\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"2022\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Create(invalid CVV)",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 4xx",
+ "pm.test(\"[POST]::/payments - Status code is 4xx\", function () {",
+ " pm.response.to.be.error;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"error\"",
+ "pm.test(\"[POST]::/payments - Content check if 'error' exists\", function () {",
+ " pm.expect(typeof jsonData.error !== \"undefined\").to.be.true;",
+ "});",
+ "",
+ "// Response body should have value \"connector error\" for \"error type\"",
+ "if (jsonData?.error?.type) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'error.type' matches 'connector'\",",
+ " function () {",
+ " pm.expect(jsonData.error.type).to.eql(\"connector\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"123456\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"12345\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario2-Confirming the payment without PMD",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Confirm",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 4xx",
+ "pm.test(\"[POST]::/payments - Status code is 4xx\", function () {",
+ " pm.response.to.be.error;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"error\"",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if 'error' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.error !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have value \"connector error\" for \"error type\"",
+ "if (jsonData?.error?.type) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\",",
+ " function () {",
+ " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"client_secret\":\"{{client_secret}}\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/confirm",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario3-Capture greater amount",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_capture\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Capture",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 4xx",
+ "pm.test(\"[POST]::/payments/:id/capture - Status code is 4xx\", function () {",
+ " pm.response.to.be.error;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/capture - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"error\"",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if 'error' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.error !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have value \"connector error\" for \"error type\"",
+ "if (jsonData?.error?.type) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\",",
+ " function () {",
+ " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount_to_capture\":7000,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/capture",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "capture"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To capture the funds for an uncaptured payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_capture\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario4-Capture the succeeded payment",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Capture",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 4xx",
+ "pm.test(\"[POST]::/payments/:id/capture - Status code is 4xx\", function () {",
+ " pm.response.to.be.error;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/capture - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"error\"",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if 'error' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.error !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have value \"connector error\" for \"error type\"",
+ "if (jsonData?.error?.type) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\",",
+ " function () {",
+ " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount_to_capture\":7000,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/capture",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "capture"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To capture the funds for an uncaptured payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario5-Void the success_slash_failure payment",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Cancel",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 4xx",
+ "pm.test(\"[POST]::/payments/:id/cancel - Status code is 4xx\", function () {",
+ " pm.response.to.be.error;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/cancel - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/cancel - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"error\"",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if 'error' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.error !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have value \"connector error\" for \"error type\"",
+ "if (jsonData?.error?.type) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\",",
+ " function () {",
+ " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"cancellation_reason\":\"requested_by_customer\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/cancel",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "cancel"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "A Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario7-Refund exceeds amount",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 4xx",
+ "pm.test(\"[POST]::/refunds - Status code is 4xx\", function () {",
+ " pm.response.to.be.error;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"error\"",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if 'error' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.error !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have value \"connector error\" for \"error type\"",
+ "if (jsonData?.error?.type) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\",",
+ " function () {",
+ " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":7000,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/refunds",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds"
+ ]
+ },
+ "description": "To create a refund against an already processed payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario8-Refund for unsuccessful payment",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_confirmation\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_confirmation\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_confirmation'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 4xx",
+ "pm.test(\"[POST]::/refunds - Status code is 4xx\", function () {",
+ " pm.response.to.be.error;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"error\"",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if 'error' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.error !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have value \"invalid_request\" for \"error type\"",
+ "if (jsonData?.error?.type) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\",",
+ " function () {",
+ " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/refunds",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds"
+ ]
+ },
+ "description": "To create a refund against an already processed payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario9-Create a recurring payment with greater mandate amount",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Recurring Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 4xx",
+ "pm.test(\"[POST]::/payments - Status code is 4xx\", function () {",
+ " pm.response.to.be.error;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"error\"",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if 'error' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.error !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have value \"invalid_request\" for \"error type\"",
+ "if (jsonData?.error?.type) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\",",
+ " function () {",
+ " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":8040,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario11-Failure card",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"failed\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'failed'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"failed\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Check if error code exists",
+ "pm.test(\"[POST]::/payments - Content check if error code exists\", function () {",
+ " pm.expect(jsonData.error_code).to.not.equal(null);;",
+ "});",
+ "",
+ "// Check if error message exists",
+ "pm.test(\"[POST]::/payments - Content check if error message exists\", function () {",
+ " pm.expect(jsonData.error_message).to.not.equal(null);;",
+ "});",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ },
+ {
+ "key": "x-feature",
+ "value": "router-custom",
+ "type": "text"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"setup_future_usage\":\"on_session\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"412345678912345678914\",\"card_exp_month\":\"01\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"failed\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'failed'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"failed\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Check if error code exists",
+ "pm.test(\"[POST]::/payments - Content check if error code exists\", function () {",
+ " pm.expect(jsonData.error_code).to.not.equal(null);;",
+ "});",
+ "",
+ "// Check if error message exists",
+ "pm.test(\"[POST]::/payments - Content check if error message exists\", function () {",
+ " pm.expect(jsonData.error_message).to.not.equal(null);;",
+ "});",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario12-Refund exceeds amount captured",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_capture\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"{{customer_id}}\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"likhin\",\"last_name\":\"bopanna\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"count_tickets\":1,\"transaction_number\":\"5590045\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Capture",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/capture - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'partially_captured'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"partially_captured\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.amount) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6000\" for \"amount_received\"",
+ "if (jsonData?.amount_received) {",
+ " pm.test(",
+ " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6000'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_received).to.eql(6000);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount_to_capture\":6000,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/capture",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "capture"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To capture the funds for an uncaptured payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'partially_captured'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"partially_captured\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 4xx",
+ "pm.test(\"[POST]::/refunds - Status code is 4xx\", function () {",
+ " pm.response.to.be.error;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"error\"",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if 'error' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.error !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have value \"invalid_request\" for \"error type\"",
+ "if (jsonData?.error?.type) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'error.type' matches 'invalid_request'\",",
+ " function () {",
+ " pm.expect(jsonData.error.type).to.eql(\"invalid_request\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"The refund amount exceeds the amount captured\" for \"error message\"",
+ "if (jsonData?.error?.type) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'error.message' matches 'The refund amount exceeds the amount captured'\",",
+ " function () {",
+ " pm.expect(jsonData.error.message).to.eql(\"The refund amount exceeds the amount captured\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":6540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/refunds",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds"
+ ]
+ },
+ "description": "To create a refund against an already processed payment"
+ },
+ "response": []
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{api_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "info": {
+ "_postman_id": "def65b5c-dc11-4917-a1bb-508988011eff",
+ "name": "cybersource",
+ "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [[email protected]](mailto:[email protected])",
+ "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
+ "_exporter_id": "24206034"
+ },
+ "variable": [
+ {
+ "key": "baseUrl",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "admin_api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "merchant_id",
+ "value": ""
+ },
+ {
+ "key": "payment_id",
+ "value": ""
+ },
+ {
+ "key": "customer_id",
+ "value": "cybersourcecustomer"
+ },
+ {
+ "key": "mandate_id",
+ "value": ""
+ },
+ {
+ "key": "payment_method_id",
+ "value": ""
+ },
+ {
+ "key": "refund_id",
+ "value": ""
+ },
+ {
+ "key": "merchant_connector_id",
+ "value": ""
+ },
+ {
+ "key": "client_secret",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "publishable_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "api_key_id",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "payment_token",
+ "value": ""
+ },
+ {
+ "key": "gateway_merchant_id",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "certificate",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "certificate_keys",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_key1",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_api_secret",
+ "value": "",
+ "type": "string"
+ }
+ ]
+}
|
chore
|
update Postman collection files
|
44dc45b8bd686a0d35fb2c02866e118adc8314e7
|
2025-02-27 18:29:06
|
Amisha Prabhat
|
feat(core): create a process_tracker workflow for PCR (#7124)
| false
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index c94193831ff..59ea6e97fbb 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -325,7 +325,7 @@ impl PaymentsCreateIntentRequest {
}
// This struct is only used internally, not visible in API Reference
-#[derive(Debug, Clone, serde::Serialize)]
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[cfg(feature = "v2")]
pub struct PaymentsGetIntentRequest {
pub id: id_type::GlobalPaymentId,
diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs
index 1ee1a090ffa..7fda63fb6a5 100644
--- a/crates/diesel_models/src/enums.rs
+++ b/crates/diesel_models/src/enums.rs
@@ -103,6 +103,8 @@ pub enum ProcessTrackerStatus {
ProcessStarted,
// Finished by consumer
Finish,
+ // Review the task
+ Review,
}
// Refund
diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs
index cd2c429c55e..f998ca5d237 100644
--- a/crates/diesel_models/src/process_tracker.rs
+++ b/crates/diesel_models/src/process_tracker.rs
@@ -210,6 +210,7 @@ pub enum ProcessTrackerRunner {
OutgoingWebhookRetryWorkflow,
AttachPayoutAccountWorkflow,
PaymentMethodStatusUpdateWorkflow,
+ PassiveRecoveryWorkflow,
}
#[cfg(test)]
@@ -265,4 +266,19 @@ pub mod business_status {
/// Business status set for newly created tasks.
pub const PENDING: &str = "Pending";
+
+ /// For the PCR Workflow
+ ///
+ /// This status indicates the completion of a execute task
+ pub const EXECUTE_WORKFLOW_COMPLETE: &str = "COMPLETED_EXECUTE_TASK";
+
+ /// This status indicates that the execute task was completed to trigger the psync task
+ pub const EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC: &str = "COMPLETED_EXECUTE_TASK_TO_TRIGGER_PSYNC";
+
+ /// This status indicates that the execute task was completed to trigger the review task
+ pub const EXECUTE_WORKFLOW_COMPLETE_FOR_REVIEW: &str =
+ "COMPLETED_EXECUTE_TASK_TO_TRIGGER_REVIEW";
+
+ /// This status indicates the completion of a psync task
+ pub const PSYNC_WORKFLOW_COMPLETE: &str = "COMPLETED_PSYNC_TASK";
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index cc1a7054ded..fb08d7a7191 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -318,7 +318,7 @@ pub enum PaymentIntentUpdate {
/// PreUpdate tracker of ConfirmIntent
ConfirmIntent {
status: common_enums::IntentStatus,
- active_attempt_id: id_type::GlobalAttemptId,
+ active_attempt_id: Option<id_type::GlobalAttemptId>,
updated_by: String,
},
/// PostUpdate tracker of ConfirmIntent
@@ -397,7 +397,7 @@ impl From<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal {
updated_by,
} => Self {
status: Some(status),
- active_attempt_id: Some(active_attempt_id),
+ active_attempt_id,
modified_at: common_utils::date_time::now(),
amount: None,
amount_captured: None,
diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs
index 63dc9a58632..a997d062bc8 100644
--- a/crates/router/src/bin/scheduler.rs
+++ b/crates/router/src/bin/scheduler.rs
@@ -252,7 +252,6 @@ pub async fn deep_health_check_func(
#[derive(Debug, Copy, Clone)]
pub struct WorkflowRunner;
-#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner {
async fn trigger_workflow<'a>(
@@ -322,6 +321,9 @@ impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner {
storage::ProcessTrackerRunner::PaymentMethodStatusUpdateWorkflow => Ok(Box::new(
workflows::payment_method_status_update::PaymentMethodStatusUpdateWorkflow,
)),
+ storage::ProcessTrackerRunner::PassiveRecoveryWorkflow => Ok(Box::new(
+ workflows::passive_churn_recovery_workflow::ExecutePcrWorkflow,
+ )),
}
};
@@ -360,18 +362,6 @@ impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner {
}
}
-#[cfg(feature = "v2")]
-#[async_trait::async_trait]
-impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner {
- async fn trigger_workflow<'a>(
- &'a self,
- _state: &'a routes::SessionState,
- _process: storage::ProcessTracker,
- ) -> CustomResult<(), ProcessTrackerError> {
- todo!()
- }
-}
-
async fn start_scheduler(
state: &routes::AppState,
scheduler_flow: scheduler::SchedulerFlow,
diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs
index 365cdaf3a12..fa243d0269a 100644
--- a/crates/router/src/core.rs
+++ b/crates/router/src/core.rs
@@ -57,4 +57,6 @@ pub mod webhooks;
pub mod unified_authentication_service;
+#[cfg(feature = "v2")]
+pub mod passive_churn_recovery;
pub mod relay;
diff --git a/crates/router/src/core/passive_churn_recovery.rs b/crates/router/src/core/passive_churn_recovery.rs
new file mode 100644
index 00000000000..3c77de98e7e
--- /dev/null
+++ b/crates/router/src/core/passive_churn_recovery.rs
@@ -0,0 +1,207 @@
+pub mod transformers;
+pub mod types;
+use api_models::payments::PaymentsRetrieveRequest;
+use common_utils::{self, id_type, types::keymanager::KeyManagerState};
+use diesel_models::process_tracker::business_status;
+use error_stack::{self, ResultExt};
+use hyperswitch_domain_models::{
+ errors::api_error_response,
+ payments::{PaymentIntent, PaymentStatusData},
+};
+use scheduler::errors;
+
+use crate::{
+ core::{
+ errors::RouterResult,
+ passive_churn_recovery::types as pcr_types,
+ payments::{self, operations::Operation},
+ },
+ db::StorageInterface,
+ logger,
+ routes::{metrics, SessionState},
+ types::{
+ api,
+ storage::{self, passive_churn_recovery as pcr},
+ transformers::ForeignInto,
+ },
+};
+
+pub async fn perform_execute_payment(
+ state: &SessionState,
+ execute_task_process: &storage::ProcessTracker,
+ tracking_data: &pcr::PcrWorkflowTrackingData,
+ pcr_data: &pcr::PcrPaymentData,
+ _key_manager_state: &KeyManagerState,
+ payment_intent: &PaymentIntent,
+) -> Result<(), errors::ProcessTrackerError> {
+ let db = &*state.store;
+ let decision = pcr_types::Decision::get_decision_based_on_params(
+ state,
+ payment_intent.status,
+ false,
+ payment_intent.active_attempt_id.clone(),
+ pcr_data,
+ &tracking_data.global_payment_id,
+ )
+ .await?;
+ // TODO decide if its a global failure or is it requeueable error
+ match decision {
+ pcr_types::Decision::Execute => {
+ let action = pcr_types::Action::execute_payment(
+ db,
+ pcr_data.merchant_account.get_id(),
+ payment_intent,
+ execute_task_process,
+ )
+ .await?;
+ action
+ .execute_payment_task_response_handler(
+ db,
+ &pcr_data.merchant_account,
+ payment_intent,
+ execute_task_process,
+ &pcr_data.profile,
+ )
+ .await?;
+ }
+
+ pcr_types::Decision::Psync(attempt_status, attempt_id) => {
+ // find if a psync task is already present
+ let task = "PSYNC_WORKFLOW";
+ let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;
+ let process_tracker_id = format!("{runner}_{task}_{}", attempt_id.get_string_repr());
+ let psync_process = db.find_process_by_id(&process_tracker_id).await?;
+
+ match psync_process {
+ Some(_) => {
+ let pcr_status: pcr_types::PcrAttemptStatus = attempt_status.foreign_into();
+
+ pcr_status
+ .update_pt_status_based_on_attempt_status_for_execute_payment(
+ db,
+ execute_task_process,
+ )
+ .await?;
+ }
+
+ None => {
+ // insert new psync task
+ insert_psync_pcr_task(
+ db,
+ pcr_data.merchant_account.get_id().clone(),
+ payment_intent.get_id().clone(),
+ pcr_data.profile.get_id().clone(),
+ attempt_id.clone(),
+ storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,
+ )
+ .await?;
+
+ // finish the current task
+ db.finish_process_with_business_status(
+ execute_task_process.clone(),
+ business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC,
+ )
+ .await?;
+ }
+ };
+ }
+ pcr_types::Decision::InvalidDecision => {
+ db.finish_process_with_business_status(
+ execute_task_process.clone(),
+ business_status::EXECUTE_WORKFLOW_COMPLETE,
+ )
+ .await?;
+ logger::warn!("Abnormal State Identified")
+ }
+ }
+
+ Ok(())
+}
+
+async fn insert_psync_pcr_task(
+ db: &dyn StorageInterface,
+ merchant_id: id_type::MerchantId,
+ payment_id: id_type::GlobalPaymentId,
+ profile_id: id_type::ProfileId,
+ payment_attempt_id: id_type::GlobalAttemptId,
+ runner: storage::ProcessTrackerRunner,
+) -> RouterResult<storage::ProcessTracker> {
+ let task = "PSYNC_WORKFLOW";
+ let process_tracker_id = format!("{runner}_{task}_{}", payment_attempt_id.get_string_repr());
+ let schedule_time = common_utils::date_time::now();
+ let psync_workflow_tracking_data = pcr::PcrWorkflowTrackingData {
+ global_payment_id: payment_id,
+ merchant_id,
+ profile_id,
+ payment_attempt_id,
+ };
+ let tag = ["PCR"];
+ let process_tracker_entry = storage::ProcessTrackerNew::new(
+ process_tracker_id,
+ task,
+ runner,
+ tag,
+ psync_workflow_tracking_data,
+ schedule_time,
+ )
+ .change_context(api_error_response::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to construct delete tokenized data process tracker task")?;
+
+ let response = db
+ .insert_process(process_tracker_entry)
+ .await
+ .change_context(api_error_response::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to construct delete tokenized data process tracker task")?;
+ metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "PsyncPcr")));
+
+ Ok(response)
+}
+
+pub async fn call_psync_api(
+ state: &SessionState,
+ global_payment_id: &id_type::GlobalPaymentId,
+ pcr_data: &pcr::PcrPaymentData,
+) -> RouterResult<PaymentStatusData<api::PSync>> {
+ let operation = payments::operations::PaymentGet;
+ let req = PaymentsRetrieveRequest {
+ force_sync: false,
+ param: None,
+ expand_attempts: true,
+ };
+ // TODO : Use api handler instead of calling get_tracker and payments_operation_core
+ // Get the tracker related information. This includes payment intent and payment attempt
+ let get_tracker_response = operation
+ .to_get_tracker()?
+ .get_trackers(
+ state,
+ global_payment_id,
+ &req,
+ &pcr_data.merchant_account,
+ &pcr_data.profile,
+ &pcr_data.key_store,
+ &hyperswitch_domain_models::payments::HeaderPayload::default(),
+ None,
+ )
+ .await?;
+
+ let (payment_data, _req, _, _, _) = Box::pin(payments::payments_operation_core::<
+ api::PSync,
+ _,
+ _,
+ _,
+ PaymentStatusData<api::PSync>,
+ >(
+ state,
+ state.get_req_state(),
+ pcr_data.merchant_account.clone(),
+ pcr_data.key_store.clone(),
+ &pcr_data.profile,
+ operation,
+ req,
+ get_tracker_response,
+ payments::CallConnectorAction::Trigger,
+ hyperswitch_domain_models::payments::HeaderPayload::default(),
+ ))
+ .await?;
+ Ok(payment_data)
+}
diff --git a/crates/router/src/core/passive_churn_recovery/transformers.rs b/crates/router/src/core/passive_churn_recovery/transformers.rs
new file mode 100644
index 00000000000..ce47714353a
--- /dev/null
+++ b/crates/router/src/core/passive_churn_recovery/transformers.rs
@@ -0,0 +1,39 @@
+use common_enums::AttemptStatus;
+
+use crate::{
+ core::passive_churn_recovery::types::PcrAttemptStatus, types::transformers::ForeignFrom,
+};
+
+impl ForeignFrom<AttemptStatus> for PcrAttemptStatus {
+ fn foreign_from(s: AttemptStatus) -> Self {
+ match s {
+ AttemptStatus::Authorized | AttemptStatus::Charged | AttemptStatus::AutoRefunded => {
+ Self::Succeeded
+ }
+
+ AttemptStatus::Started
+ | AttemptStatus::AuthenticationSuccessful
+ | AttemptStatus::Authorizing
+ | AttemptStatus::CodInitiated
+ | AttemptStatus::VoidInitiated
+ | AttemptStatus::CaptureInitiated
+ | AttemptStatus::Pending => Self::Processing,
+
+ AttemptStatus::AuthenticationFailed
+ | AttemptStatus::AuthorizationFailed
+ | AttemptStatus::VoidFailed
+ | AttemptStatus::RouterDeclined
+ | AttemptStatus::CaptureFailed
+ | AttemptStatus::Failure => Self::Failed,
+
+ AttemptStatus::Voided
+ | AttemptStatus::ConfirmationAwaited
+ | AttemptStatus::PartialCharged
+ | AttemptStatus::PartialChargedAndChargeable
+ | AttemptStatus::PaymentMethodAwaited
+ | AttemptStatus::AuthenticationPending
+ | AttemptStatus::DeviceDataCollectionPending
+ | AttemptStatus::Unresolved => Self::InvalidStatus(s.to_string()),
+ }
+ }
+}
diff --git a/crates/router/src/core/passive_churn_recovery/types.rs b/crates/router/src/core/passive_churn_recovery/types.rs
new file mode 100644
index 00000000000..c47248a882a
--- /dev/null
+++ b/crates/router/src/core/passive_churn_recovery/types.rs
@@ -0,0 +1,259 @@
+use common_enums::{self, AttemptStatus, IntentStatus};
+use common_utils::{self, ext_traits::OptionExt, id_type};
+use diesel_models::{enums, process_tracker::business_status};
+use error_stack::{self, ResultExt};
+use hyperswitch_domain_models::{
+ business_profile, merchant_account,
+ payments::{PaymentConfirmData, PaymentIntent},
+};
+use time::PrimitiveDateTime;
+
+use crate::{
+ core::{
+ errors::{self, RouterResult},
+ passive_churn_recovery::{self as core_pcr},
+ },
+ db::StorageInterface,
+ logger,
+ routes::SessionState,
+ types::{api::payments as api_types, storage, transformers::ForeignInto},
+ workflows::passive_churn_recovery_workflow::get_schedule_time_to_retry_mit_payments,
+};
+
+type RecoveryResult<T> = error_stack::Result<T, errors::RecoveryError>;
+
+/// The status of Passive Churn Payments
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub enum PcrAttemptStatus {
+ Succeeded,
+ Failed,
+ Processing,
+ InvalidStatus(String),
+ // Cancelled,
+}
+
+impl PcrAttemptStatus {
+ pub(crate) async fn update_pt_status_based_on_attempt_status_for_execute_payment(
+ &self,
+ db: &dyn StorageInterface,
+ execute_task_process: &storage::ProcessTracker,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ match &self {
+ Self::Succeeded | Self::Failed | Self::Processing => {
+ // finish the current execute task
+ db.finish_process_with_business_status(
+ execute_task_process.clone(),
+ business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC,
+ )
+ .await?;
+ }
+
+ Self::InvalidStatus(action) => {
+ logger::debug!(
+ "Invalid Attempt Status for the Recovery Payment : {}",
+ action
+ );
+ let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
+ status: enums::ProcessTrackerStatus::Review,
+ business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_COMPLETE)),
+ };
+ // update the process tracker status as Review
+ db.update_process(execute_task_process.clone(), pt_update)
+ .await?;
+ }
+ };
+ Ok(())
+ }
+}
+#[derive(Debug, Clone)]
+pub enum Decision {
+ Execute,
+ Psync(AttemptStatus, id_type::GlobalAttemptId),
+ InvalidDecision,
+}
+
+impl Decision {
+ pub async fn get_decision_based_on_params(
+ state: &SessionState,
+ intent_status: IntentStatus,
+ called_connector: bool,
+ active_attempt_id: Option<id_type::GlobalAttemptId>,
+ pcr_data: &storage::passive_churn_recovery::PcrPaymentData,
+ payment_id: &id_type::GlobalPaymentId,
+ ) -> RecoveryResult<Self> {
+ Ok(match (intent_status, called_connector, active_attempt_id) {
+ (IntentStatus::Failed, false, None) => Self::Execute,
+ (IntentStatus::Processing, true, Some(_)) => {
+ let psync_data = core_pcr::call_psync_api(state, payment_id, pcr_data)
+ .await
+ .change_context(errors::RecoveryError::PaymentCallFailed)
+ .attach_printable("Error while executing the Psync call")?;
+ let payment_attempt = psync_data
+ .payment_attempt
+ .get_required_value("Payment Attempt")
+ .change_context(errors::RecoveryError::ValueNotFound)
+ .attach_printable("Error while executing the Psync call")?;
+ Self::Psync(payment_attempt.status, payment_attempt.get_id().clone())
+ }
+ _ => Self::InvalidDecision,
+ })
+ }
+}
+
+#[derive(Debug, Clone)]
+pub enum Action {
+ SyncPayment(id_type::GlobalAttemptId),
+ RetryPayment(PrimitiveDateTime),
+ TerminalFailure,
+ SuccessfulPayment,
+ ReviewPayment,
+ ManualReviewAction,
+}
+impl Action {
+ pub async fn execute_payment(
+ db: &dyn StorageInterface,
+ merchant_id: &id_type::MerchantId,
+ payment_intent: &PaymentIntent,
+ process: &storage::ProcessTracker,
+ ) -> RecoveryResult<Self> {
+ // call the proxy api
+ let response = call_proxy_api::<api_types::Authorize>(payment_intent);
+ // handle proxy api's response
+ match response {
+ Ok(payment_data) => match payment_data.payment_attempt.status.foreign_into() {
+ PcrAttemptStatus::Succeeded => Ok(Self::SuccessfulPayment),
+ PcrAttemptStatus::Failed => {
+ Self::decide_retry_failure_action(db, merchant_id, process.clone()).await
+ }
+
+ PcrAttemptStatus::Processing => {
+ Ok(Self::SyncPayment(payment_data.payment_attempt.id))
+ }
+ PcrAttemptStatus::InvalidStatus(action) => {
+ logger::info!(?action, "Invalid Payment Status For PCR Payment");
+ Ok(Self::ManualReviewAction)
+ }
+ },
+ Err(err) =>
+ // check for an active attempt being constructed or not
+ {
+ logger::error!(execute_payment_res=?err);
+ match payment_intent.active_attempt_id.clone() {
+ Some(attempt_id) => Ok(Self::SyncPayment(attempt_id)),
+ None => Ok(Self::ReviewPayment),
+ }
+ }
+ }
+ }
+
+ pub async fn execute_payment_task_response_handler(
+ &self,
+ db: &dyn StorageInterface,
+ merchant_account: &merchant_account::MerchantAccount,
+ payment_intent: &PaymentIntent,
+ execute_task_process: &storage::ProcessTracker,
+ profile: &business_profile::Profile,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ match self {
+ Self::SyncPayment(attempt_id) => {
+ core_pcr::insert_psync_pcr_task(
+ db,
+ merchant_account.get_id().to_owned(),
+ payment_intent.id.clone(),
+ profile.get_id().to_owned(),
+ attempt_id.clone(),
+ storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,
+ )
+ .await
+ .change_context(errors::RecoveryError::ProcessTrackerFailure)
+ .attach_printable("Failed to create a psync workflow in the process tracker")?;
+
+ db.as_scheduler()
+ .finish_process_with_business_status(
+ execute_task_process.clone(),
+ business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC,
+ )
+ .await
+ .change_context(errors::RecoveryError::ProcessTrackerFailure)
+ .attach_printable("Failed to update the process tracker")?;
+ Ok(())
+ }
+
+ Self::RetryPayment(schedule_time) => {
+ let mut pt = execute_task_process.clone();
+ // update the schedule time
+ pt.schedule_time = Some(*schedule_time);
+
+ let pt_task_update = diesel_models::ProcessTrackerUpdate::StatusUpdate {
+ status: storage::enums::ProcessTrackerStatus::Pending,
+ business_status: Some(business_status::PENDING.to_owned()),
+ };
+ db.as_scheduler()
+ .update_process(pt.clone(), pt_task_update)
+ .await?;
+ // TODO: update the connector called field and make the active attempt None
+
+ Ok(())
+ }
+ Self::TerminalFailure => {
+ // TODO: Record a failure transaction back to Billing Connector
+ Ok(())
+ }
+ Self::SuccessfulPayment => Ok(()),
+ Self::ReviewPayment => Ok(()),
+ Self::ManualReviewAction => {
+ logger::debug!("Invalid Payment Status For PCR Payment");
+ let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
+ status: enums::ProcessTrackerStatus::Review,
+ business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_COMPLETE)),
+ };
+ // update the process tracker status as Review
+ db.as_scheduler()
+ .update_process(execute_task_process.clone(), pt_update)
+ .await?;
+ Ok(())
+ }
+ }
+ }
+
+ pub(crate) async fn decide_retry_failure_action(
+ db: &dyn StorageInterface,
+ merchant_id: &id_type::MerchantId,
+ pt: storage::ProcessTracker,
+ ) -> RecoveryResult<Self> {
+ let schedule_time =
+ get_schedule_time_to_retry_mit_payments(db, merchant_id, pt.retry_count + 1).await;
+ match schedule_time {
+ Some(schedule_time) => Ok(Self::RetryPayment(schedule_time)),
+
+ None => Ok(Self::TerminalFailure),
+ }
+ }
+}
+
+// This function would be converted to proxy_payments_core
+fn call_proxy_api<F>(payment_intent: &PaymentIntent) -> RouterResult<PaymentConfirmData<F>>
+where
+ F: Send + Clone + Sync,
+{
+ let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new(
+ payment_intent
+ .shipping_address
+ .clone()
+ .map(|address| address.into_inner()),
+ payment_intent
+ .billing_address
+ .clone()
+ .map(|address| address.into_inner()),
+ None,
+ Some(true),
+ );
+ let response = PaymentConfirmData {
+ flow: std::marker::PhantomData,
+ payment_intent: payment_intent.clone(),
+ payment_attempt: todo!(),
+ payment_method_data: None,
+ payment_address,
+ };
+ Ok(response)
+}
diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rs
index 0f42948e3f0..40b1918323c 100644
--- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs
@@ -210,8 +210,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, PaymentsConfir
)
.await?;
- let payment_attempt = db
- .insert_payment_attempt(
+ let payment_attempt: hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt =
+ db.insert_payment_attempt(
key_manager_state,
key_store,
payment_attempt_domain_model,
@@ -416,7 +416,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentConfirmData<F>, PaymentsConfirmInt
hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::ConfirmIntent {
status: intent_status,
updated_by: storage_scheme.to_string(),
- active_attempt_id: payment_data.payment_attempt.id.clone(),
+ active_attempt_id: Some(payment_data.payment_attempt.id.clone()),
};
let authentication_type = payment_data.payment_attempt.authentication_type;
diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs
index 96a0d580056..bd033ff4c2a 100644
--- a/crates/router/src/types/storage.rs
+++ b/crates/router/src/types/storage.rs
@@ -28,6 +28,8 @@ pub mod mandate;
pub mod merchant_account;
pub mod merchant_connector_account;
pub mod merchant_key_store;
+#[cfg(feature = "v2")]
+pub mod passive_churn_recovery;
pub mod payment_attempt;
pub mod payment_link;
pub mod payment_method;
diff --git a/crates/router/src/types/storage/passive_churn_recovery.rs b/crates/router/src/types/storage/passive_churn_recovery.rs
new file mode 100644
index 00000000000..3cf3316a398
--- /dev/null
+++ b/crates/router/src/types/storage/passive_churn_recovery.rs
@@ -0,0 +1,18 @@
+use std::fmt::Debug;
+
+use common_utils::id_type;
+use hyperswitch_domain_models::{business_profile, merchant_account, merchant_key_store};
+#[derive(serde::Serialize, serde::Deserialize, Debug)]
+pub struct PcrWorkflowTrackingData {
+ pub merchant_id: id_type::MerchantId,
+ pub profile_id: id_type::ProfileId,
+ pub global_payment_id: id_type::GlobalPaymentId,
+ pub payment_attempt_id: id_type::GlobalAttemptId,
+}
+
+#[derive(Debug, Clone)]
+pub struct PcrPaymentData {
+ pub merchant_account: merchant_account::MerchantAccount,
+ pub profile: business_profile::Profile,
+ pub key_store: merchant_key_store::MerchantKeyStore,
+}
diff --git a/crates/router/src/workflows.rs b/crates/router/src/workflows.rs
index e86d49faf6c..4961932e067 100644
--- a/crates/router/src/workflows.rs
+++ b/crates/router/src/workflows.rs
@@ -2,12 +2,12 @@
pub mod api_key_expiry;
#[cfg(feature = "payouts")]
pub mod attach_payout_account_workflow;
-#[cfg(feature = "v1")]
pub mod outgoing_webhook_retry;
-#[cfg(feature = "v1")]
pub mod payment_method_status_update;
pub mod payment_sync;
-#[cfg(feature = "v1")]
+
pub mod refund_router;
-#[cfg(feature = "v1")]
+
pub mod tokenized_data;
+
+pub mod passive_churn_recovery_workflow;
diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rs
index c7df4aeff0c..9be893c7ac8 100644
--- a/crates/router/src/workflows/outgoing_webhook_retry.rs
+++ b/crates/router/src/workflows/outgoing_webhook_retry.rs
@@ -36,6 +36,7 @@ pub struct OutgoingWebhookRetryWorkflow;
#[async_trait::async_trait]
impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {
+ #[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn execute_workflow<'a>(
&'a self,
@@ -226,6 +227,14 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {
Ok(())
}
+ #[cfg(feature = "v2")]
+ async fn execute_workflow<'a>(
+ &'a self,
+ _state: &'a SessionState,
+ _process: storage::ProcessTracker,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ todo!()
+ }
#[instrument(skip_all)]
async fn error_handler<'a>(
@@ -266,6 +275,7 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {
/// seconds between them by default.
/// - `custom_merchant_mapping.merchant_id1`: Merchant-specific retry configuration for merchant
/// with merchant ID `merchant_id1`.
+#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub(crate) async fn get_webhook_delivery_retry_schedule_time(
db: &dyn StorageInterface,
@@ -311,6 +321,7 @@ pub(crate) async fn get_webhook_delivery_retry_schedule_time(
}
/// Schedule the webhook delivery task for retry
+#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub(crate) async fn retry_webhook_delivery_task(
db: &dyn StorageInterface,
@@ -334,6 +345,7 @@ pub(crate) async fn retry_webhook_delivery_task(
}
}
+#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn get_outgoing_webhook_content_and_event_type(
state: SessionState,
diff --git a/crates/router/src/workflows/passive_churn_recovery_workflow.rs b/crates/router/src/workflows/passive_churn_recovery_workflow.rs
new file mode 100644
index 00000000000..d67f91f1169
--- /dev/null
+++ b/crates/router/src/workflows/passive_churn_recovery_workflow.rs
@@ -0,0 +1,175 @@
+#[cfg(feature = "v2")]
+use api_models::payments::PaymentsGetIntentRequest;
+#[cfg(feature = "v2")]
+use common_utils::ext_traits::{StringExt, ValueExt};
+#[cfg(feature = "v2")]
+use error_stack::ResultExt;
+#[cfg(feature = "v2")]
+use hyperswitch_domain_models::payments::PaymentIntentData;
+#[cfg(feature = "v2")]
+use router_env::logger;
+use scheduler::{consumer::workflows::ProcessTrackerWorkflow, errors};
+#[cfg(feature = "v2")]
+use scheduler::{types::process_data, utils as scheduler_utils};
+
+#[cfg(feature = "v2")]
+use crate::{
+ core::{
+ passive_churn_recovery::{self as pcr},
+ payments,
+ },
+ db::StorageInterface,
+ errors::StorageError,
+ types::{
+ api::{self as api_types},
+ storage::passive_churn_recovery as pcr_storage_types,
+ },
+};
+use crate::{routes::SessionState, types::storage};
+pub struct ExecutePcrWorkflow;
+
+#[async_trait::async_trait]
+impl ProcessTrackerWorkflow<SessionState> for ExecutePcrWorkflow {
+ #[cfg(feature = "v1")]
+ async fn execute_workflow<'a>(
+ &'a self,
+ _state: &'a SessionState,
+ _process: storage::ProcessTracker,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ Ok(())
+ }
+ #[cfg(feature = "v2")]
+ async fn execute_workflow<'a>(
+ &'a self,
+ state: &'a SessionState,
+ process: storage::ProcessTracker,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ let tracking_data = process
+ .tracking_data
+ .clone()
+ .parse_value::<pcr_storage_types::PcrWorkflowTrackingData>(
+ "PCRWorkflowTrackingData",
+ )?;
+ let request = PaymentsGetIntentRequest {
+ id: tracking_data.global_payment_id.clone(),
+ };
+ let key_manager_state = &state.into();
+ let pcr_data = extract_data_and_perform_action(state, &tracking_data).await?;
+ let (payment_data, _, _) = payments::payments_intent_operation_core::<
+ api_types::PaymentGetIntent,
+ _,
+ _,
+ PaymentIntentData<api_types::PaymentGetIntent>,
+ >(
+ state,
+ state.get_req_state(),
+ pcr_data.merchant_account.clone(),
+ pcr_data.profile.clone(),
+ pcr_data.key_store.clone(),
+ payments::operations::PaymentGetIntent,
+ request,
+ tracking_data.global_payment_id.clone(),
+ hyperswitch_domain_models::payments::HeaderPayload::default(),
+ None,
+ )
+ .await?;
+
+ match process.name.as_deref() {
+ Some("EXECUTE_WORKFLOW") => {
+ pcr::perform_execute_payment(
+ state,
+ &process,
+ &tracking_data,
+ &pcr_data,
+ key_manager_state,
+ &payment_data.payment_intent,
+ )
+ .await
+ }
+ Some("PSYNC_WORKFLOW") => todo!(),
+
+ Some("REVIEW_WORKFLOW") => todo!(),
+ _ => Err(errors::ProcessTrackerError::JobNotFound),
+ }
+ }
+}
+#[cfg(feature = "v2")]
+pub(crate) async fn extract_data_and_perform_action(
+ state: &SessionState,
+ tracking_data: &pcr_storage_types::PcrWorkflowTrackingData,
+) -> Result<pcr_storage_types::PcrPaymentData, errors::ProcessTrackerError> {
+ let db = &state.store;
+
+ let key_manager_state = &state.into();
+ let key_store = db
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
+ &tracking_data.merchant_id,
+ &db.get_master_key().to_vec().into(),
+ )
+ .await?;
+
+ let merchant_account = db
+ .find_merchant_account_by_merchant_id(
+ key_manager_state,
+ &tracking_data.merchant_id,
+ &key_store,
+ )
+ .await?;
+
+ let profile = db
+ .find_business_profile_by_profile_id(
+ key_manager_state,
+ &key_store,
+ &tracking_data.profile_id,
+ )
+ .await?;
+
+ let pcr_payment_data = pcr_storage_types::PcrPaymentData {
+ merchant_account,
+ profile,
+ key_store,
+ };
+ Ok(pcr_payment_data)
+}
+
+#[cfg(feature = "v2")]
+pub(crate) async fn get_schedule_time_to_retry_mit_payments(
+ db: &dyn StorageInterface,
+ merchant_id: &common_utils::id_type::MerchantId,
+ retry_count: i32,
+) -> Option<time::PrimitiveDateTime> {
+ let key = "pt_mapping_pcr_retries";
+ let result = db
+ .find_config_by_key(key)
+ .await
+ .map(|value| value.config)
+ .and_then(|config| {
+ config
+ .parse_struct("RevenueRecoveryPaymentProcessTrackerMapping")
+ .change_context(StorageError::DeserializationFailed)
+ });
+
+ let mapping = result.map_or_else(
+ |error| {
+ if error.current_context().is_db_not_found() {
+ logger::debug!("Revenue Recovery retry config `{key}` not found, ignoring");
+ } else {
+ logger::error!(
+ ?error,
+ "Failed to read Revenue Recovery retry config `{key}`"
+ );
+ }
+ process_data::RevenueRecoveryPaymentProcessTrackerMapping::default()
+ },
+ |mapping| {
+ logger::debug!(?mapping, "Using custom pcr payments retry config");
+ mapping
+ },
+ );
+
+ let time_delta =
+ scheduler_utils::get_pcr_payments_retry_schedule_time(mapping, merchant_id, retry_count);
+
+ scheduler_utils::get_time_from_delta(time_delta)
+}
diff --git a/crates/router/src/workflows/payment_method_status_update.rs b/crates/router/src/workflows/payment_method_status_update.rs
index 124417e3355..dba3bace252 100644
--- a/crates/router/src/workflows/payment_method_status_update.rs
+++ b/crates/router/src/workflows/payment_method_status_update.rs
@@ -111,6 +111,14 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodStatusUpdateWorkflow
Ok(())
}
+ #[cfg(feature = "v2")]
+ async fn execute_workflow<'a>(
+ &'a self,
+ _state: &'a SessionState,
+ _process: storage::ProcessTracker,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ todo!()
+ }
async fn error_handler<'a>(
&'a self,
_state: &'a SessionState,
diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs
index fb83922935e..64c4853d14b 100644
--- a/crates/router/src/workflows/payment_sync.rs
+++ b/crates/router/src/workflows/payment_sync.rs
@@ -31,8 +31,8 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow {
#[cfg(feature = "v2")]
async fn execute_workflow<'a>(
&'a self,
- state: &'a SessionState,
- process: storage::ProcessTracker,
+ _state: &'a SessionState,
+ _process: storage::ProcessTracker,
) -> Result<(), sch_errors::ProcessTrackerError> {
todo!()
}
diff --git a/crates/router/src/workflows/refund_router.rs b/crates/router/src/workflows/refund_router.rs
index 515e34c0689..82e7d8a45de 100644
--- a/crates/router/src/workflows/refund_router.rs
+++ b/crates/router/src/workflows/refund_router.rs
@@ -1,13 +1,14 @@
use scheduler::consumer::workflows::ProcessTrackerWorkflow;
-use crate::{
- core::refunds as refund_flow, errors, logger::error, routes::SessionState, types::storage,
-};
+#[cfg(feature = "v1")]
+use crate::core::refunds as refund_flow;
+use crate::{errors, logger::error, routes::SessionState, types::storage};
pub struct RefundWorkflowRouter;
#[async_trait::async_trait]
impl ProcessTrackerWorkflow<SessionState> for RefundWorkflowRouter {
+ #[cfg(feature = "v1")]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
@@ -15,6 +16,14 @@ impl ProcessTrackerWorkflow<SessionState> for RefundWorkflowRouter {
) -> Result<(), errors::ProcessTrackerError> {
Ok(Box::pin(refund_flow::start_refund_workflow(state, &process)).await?)
}
+ #[cfg(feature = "v2")]
+ async fn execute_workflow<'a>(
+ &'a self,
+ _state: &'a SessionState,
+ _process: storage::ProcessTracker,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ todo!()
+ }
async fn error_handler<'a>(
&'a self,
diff --git a/crates/router/src/workflows/tokenized_data.rs b/crates/router/src/workflows/tokenized_data.rs
index bc1842205ae..2f2474df66c 100644
--- a/crates/router/src/workflows/tokenized_data.rs
+++ b/crates/router/src/workflows/tokenized_data.rs
@@ -1,13 +1,14 @@
use scheduler::consumer::workflows::ProcessTrackerWorkflow;
-use crate::{
- core::payment_methods::vault, errors, logger::error, routes::SessionState, types::storage,
-};
+#[cfg(feature = "v1")]
+use crate::core::payment_methods::vault;
+use crate::{errors, logger::error, routes::SessionState, types::storage};
pub struct DeleteTokenizeDataWorkflow;
#[async_trait::async_trait]
impl ProcessTrackerWorkflow<SessionState> for DeleteTokenizeDataWorkflow {
+ #[cfg(feature = "v1")]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
@@ -16,6 +17,15 @@ impl ProcessTrackerWorkflow<SessionState> for DeleteTokenizeDataWorkflow {
Ok(vault::start_tokenize_data_workflow(state, &process).await?)
}
+ #[cfg(feature = "v2")]
+ async fn execute_workflow<'a>(
+ &'a self,
+ _state: &'a SessionState,
+ _process: storage::ProcessTracker,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ todo!()
+ }
+
async fn error_handler<'a>(
&'a self,
_state: &'a SessionState,
diff --git a/crates/scheduler/src/consumer/types/process_data.rs b/crates/scheduler/src/consumer/types/process_data.rs
index f68ad4795df..26d0fdf7022 100644
--- a/crates/scheduler/src/consumer/types/process_data.rs
+++ b/crates/scheduler/src/consumer/types/process_data.rs
@@ -82,3 +82,39 @@ impl Default for OutgoingWebhookRetryProcessTrackerMapping {
}
}
}
+
+/// Configuration for outgoing webhook retries.
+#[derive(Debug, Serialize, Deserialize)]
+pub struct RevenueRecoveryPaymentProcessTrackerMapping {
+ /// Default (fallback) retry configuration used when no merchant-specific retry configuration
+ /// exists.
+ pub default_mapping: RetryMapping,
+
+ /// Merchant-specific retry configuration.
+ pub custom_merchant_mapping: HashMap<common_utils::id_type::MerchantId, RetryMapping>,
+}
+
+impl Default for RevenueRecoveryPaymentProcessTrackerMapping {
+ fn default() -> Self {
+ Self {
+ default_mapping: RetryMapping {
+ // 1st attempt happens after 1 minute of it being
+ start_after: 60,
+
+ frequencies: vec![
+ // 2nd and 3rd attempts happen at intervals of 3 hours each
+ (60 * 60 * 3, 2),
+ // 4th, 5th, 6th attempts happen at intervals of 6 hours each
+ (60 * 60 * 6, 3),
+ // 7th, 8th, 9th attempts happen at intervals of 9 hour each
+ (60 * 60 * 9, 3),
+ // 10th, 11th and 12th attempts happen at intervals of 12 hours each
+ (60 * 60 * 12, 3),
+ // 13th, 14th and 15th attempts happen at intervals of 18 hours each
+ (60 * 60 * 18, 3),
+ ],
+ },
+ custom_merchant_mapping: HashMap::new(),
+ }
+ }
+}
diff --git a/crates/scheduler/src/errors.rs b/crates/scheduler/src/errors.rs
index 1fb7599aed0..254c4979524 100644
--- a/crates/scheduler/src/errors.rs
+++ b/crates/scheduler/src/errors.rs
@@ -4,7 +4,7 @@ use external_services::email::EmailError;
use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
pub use redis_interface::errors::RedisError;
pub use storage_impl::errors::ApplicationError;
-use storage_impl::errors::StorageError;
+use storage_impl::errors::{RecoveryError, StorageError};
use crate::env::logger::{self, error};
@@ -46,6 +46,8 @@ pub enum ProcessTrackerError {
EApiErrorResponse,
#[error("Received Error ClientError")]
EClientError,
+ #[error("Received RecoveryError: {0:?}")]
+ ERecoveryError(error_stack::Report<RecoveryError>),
#[error("Received Error StorageError: {0:?}")]
EStorageError(error_stack::Report<StorageError>),
#[error("Received Error RedisError: {0:?}")]
@@ -131,3 +133,8 @@ error_to_process_tracker_error!(
error_stack::Report<EmailError>,
ProcessTrackerError::EEmailError(error_stack::Report<EmailError>)
);
+
+error_to_process_tracker_error!(
+ error_stack::Report<RecoveryError>,
+ ProcessTrackerError::ERecoveryError(error_stack::Report<RecoveryError>)
+);
diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rs
index 0dbea173eae..3d7f637de90 100644
--- a/crates/scheduler/src/utils.rs
+++ b/crates/scheduler/src/utils.rs
@@ -350,6 +350,25 @@ pub fn get_outgoing_webhook_retry_schedule_time(
}
}
+pub fn get_pcr_payments_retry_schedule_time(
+ mapping: process_data::RevenueRecoveryPaymentProcessTrackerMapping,
+ merchant_id: &common_utils::id_type::MerchantId,
+ retry_count: i32,
+) -> Option<i32> {
+ let mapping = match mapping.custom_merchant_mapping.get(merchant_id) {
+ Some(map) => map.clone(),
+ None => mapping.default_mapping,
+ };
+ // TODO: check if the current scheduled time is not more than the configured timerange
+
+ // For first try, get the `start_after` time
+ if retry_count == 0 {
+ Some(mapping.start_after)
+ } else {
+ get_delay(retry_count, &mapping.frequencies)
+ }
+}
+
/// Get the delay based on the retry count
pub fn get_delay<'a>(
retry_count: i32,
diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs
index d75911d593c..657e9b000a5 100644
--- a/crates/storage_impl/src/errors.rs
+++ b/crates/storage_impl/src/errors.rs
@@ -299,3 +299,15 @@ pub enum HealthCheckGRPCServiceError {
#[error("Failed to establish connection with gRPC service")]
FailedToCallService,
}
+
+#[derive(thiserror::Error, Debug, Clone)]
+pub enum RecoveryError {
+ #[error("Failed to make a recovery payment")]
+ PaymentCallFailed,
+ #[error("Encountered a Process Tracker Task Failure")]
+ ProcessTrackerFailure,
+ #[error("The encountered task is invalid")]
+ InvalidTask,
+ #[error("The Intended data was not found")]
+ ValueNotFound,
+}
|
feat
|
create a process_tracker workflow for PCR (#7124)
|
4ae6af4632bbef5d21c3cb28538dcc4a94a10789
|
2023-12-15 17:07:55
|
DEEPANSHU BANSAL
|
feat(connector): [CYBERSOURCE] Implement Google Pay (#3139)
| false
|
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index 4abb878043f..80e98a68f5d 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -4809,6 +4809,93 @@ impl Default for super::settings::RequiredFields {
),
common: HashMap::new(),
}
+ ),
+ (
+ enums::Connector::Cybersource,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::from(
+ [
+ (
+ "email".to_string(),
+ RequiredFieldInfo {
+ required_field: "email".to_string(),
+ display_name: "email".to_string(),
+ field_type: enums::FieldType::UserEmailAddress,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.first_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.first_name".to_string(),
+ display_name: "billing_first_name".to_string(),
+ field_type: enums::FieldType::UserBillingName,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.last_name".to_string(),
+ display_name: "billing_last_name".to_string(),
+ field_type: enums::FieldType::UserBillingName,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.city".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.city".to_string(),
+ display_name: "city".to_string(),
+ field_type: enums::FieldType::UserAddressCity,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.state".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.state".to_string(),
+ display_name: "state".to_string(),
+ field_type: enums::FieldType::UserAddressState,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.zip".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.zip".to_string(),
+ display_name: "zip".to_string(),
+ field_type: enums::FieldType::UserAddressPincode,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.country".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.country".to_string(),
+ display_name: "country".to_string(),
+ field_type: enums::FieldType::UserAddressCountry{
+ options: vec![
+ "ALL".to_string(),
+ ]
+ },
+ value: None,
+ }
+ ),
+ (
+ "billing.address.line1".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.line1".to_string(),
+ display_name: "line1".to_string(),
+ field_type: enums::FieldType::UserAddressLine1,
+ value: None,
+ }
+ ),
+ ]
+ ),
+ common: HashMap::new(),
+ }
)
]),
},
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index a4cea13e218..a5b55f111b9 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -1,12 +1,13 @@
use api_models::payments;
+use base64::Engine;
use common_utils::pii;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
connector::utils::{
- self, AddressDetailsData, PaymentsAuthorizeRequestData, PaymentsSetupMandateRequestData,
- RouterData,
+ self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData,
+ PaymentsSetupMandateRequestData, RouterData,
},
consts,
core::errors,
@@ -66,7 +67,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest {
let order_information = OrderInformationWithBill {
amount_details: Amount {
total_amount: "0".to_string(),
- currency: item.request.currency.to_string(),
+ currency: item.request.currency,
},
bill_to: Some(bill_to),
};
@@ -90,6 +91,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest {
action_token_types,
authorization_options,
commerce_indicator: CybersourceCommerceIndicator::Internet,
+ payment_solution: None,
};
let client_reference_information = ClientReferenceInformation {
@@ -103,11 +105,12 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest {
expiration_month: ccard.card_exp_month,
expiration_year: ccard.card_exp_year,
security_code: ccard.card_cvc,
+ card_type: None,
});
- PaymentInformation {
+ PaymentInformation::Cards(CardPaymentInformation {
card,
instrument_identifier: None,
- }
+ })
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
@@ -140,6 +143,7 @@ pub struct ProcessingInformation {
commerce_indicator: CybersourceCommerceIndicator,
capture: Option<bool>,
capture_options: Option<CaptureOptions>,
+ payment_solution: Option<String>,
}
#[derive(Debug, Serialize)]
@@ -197,11 +201,30 @@ pub struct CaptureOptions {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct PaymentInformation {
+pub struct CardPaymentInformation {
card: CardDetails,
instrument_identifier: Option<CybersoucreInstrumentIdentifier>,
}
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FluidData {
+ value: Secret<String>,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GooglePayPaymentInformation {
+ fluid_data: FluidData,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(untagged)]
+pub enum PaymentInformation {
+ Cards(CardPaymentInformation),
+ GooglePay(GooglePayPaymentInformation),
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CybersoucreInstrumentIdentifier {
id: String,
@@ -221,6 +244,8 @@ pub struct Card {
expiration_month: Secret<String>,
expiration_year: Secret<String>,
security_code: Secret<String>,
+ #[serde(rename = "type")]
+ card_type: Option<String>,
}
#[derive(Debug, Serialize)]
@@ -253,7 +278,7 @@ pub struct OrderInformation {
#[serde(rename_all = "camelCase")]
pub struct Amount {
total_amount: String,
- currency: String,
+ currency: api_models::enums::Currency,
}
#[derive(Debug, Serialize)]
@@ -263,6 +288,22 @@ pub struct AdditionalAmount {
currency: String,
}
+#[derive(Debug, Serialize)]
+pub enum PaymentSolution {
+ ApplePay,
+ GooglePay,
+}
+
+impl From<PaymentSolution> for String {
+ fn from(solution: PaymentSolution) -> Self {
+ let payment_solution = match solution {
+ PaymentSolution::ApplePay => "001",
+ PaymentSolution::GooglePay => "012",
+ };
+ payment_solution.to_string()
+ }
+}
+
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BillTo {
@@ -276,6 +317,82 @@ pub struct BillTo {
email: pii::Email,
}
+impl From<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
+ for ClientReferenceInformation
+{
+ fn from(item: &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>) -> Self {
+ Self {
+ code: Some(item.router_data.connector_request_reference_id.clone()),
+ }
+ }
+}
+
+impl
+ From<(
+ &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ Option<PaymentSolution>,
+ )> for ProcessingInformation
+{
+ fn from(
+ (item, solution): (
+ &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ Option<PaymentSolution>,
+ ),
+ ) -> Self {
+ let (action_list, action_token_types, authorization_options) =
+ if item.router_data.request.setup_future_usage.is_some() {
+ (
+ Some(vec![CybersourceActionsList::TokenCreate]),
+ Some(vec![CybersourceActionsTokenType::InstrumentIdentifier]),
+ Some(CybersourceAuthorizationOptions {
+ initiator: CybersourcePaymentInitiator {
+ initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer),
+ credential_stored_on_file: Some(true),
+ stored_credential_used: None,
+ },
+ merchant_intitiated_transaction: None,
+ }),
+ )
+ } else {
+ (None, None, None)
+ };
+ Self {
+ capture: Some(matches!(
+ item.router_data.request.capture_method,
+ Some(enums::CaptureMethod::Automatic) | None
+ )),
+ payment_solution: solution.map(String::from),
+ action_list,
+ action_token_types,
+ authorization_options,
+ capture_options: None,
+ commerce_indicator: CybersourceCommerceIndicator::Internet,
+ }
+ }
+}
+
+impl
+ From<(
+ &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ BillTo,
+ )> for OrderInformationWithBill
+{
+ fn from(
+ (item, bill_to): (
+ &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ BillTo,
+ ),
+ ) -> Self {
+ Self {
+ amount_details: Amount {
+ total_amount: item.amount.to_owned(),
+ currency: item.router_data.request.currency,
+ },
+ bill_to: Some(bill_to),
+ }
+ }
+}
+
// for cybersource each item in Billing is mandatory
fn build_bill_to(
address_details: &payments::Address,
@@ -297,85 +414,150 @@ fn build_bill_to(
})
}
-impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
- for CybersourcePaymentsRequest
+impl
+ TryFrom<(
+ &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ payments::Card,
+ )> for CybersourcePaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ (item, ccard): (
+ &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ payments::Card,
+ ),
) -> Result<Self, Self::Error> {
let email = item.router_data.request.get_email()?;
let bill_to = build_bill_to(item.router_data.get_billing()?, email)?;
+ let order_information = OrderInformationWithBill::from((item, bill_to));
- let order_information = OrderInformationWithBill {
- amount_details: Amount {
- total_amount: item.amount.to_owned(),
- currency: item.router_data.request.currency.to_string(),
- },
- bill_to: Some(bill_to),
+ let card_issuer = ccard.get_card_issuer();
+ let card_type = match card_issuer {
+ Ok(issuer) => Some(String::from(issuer)),
+ Err(_) => None,
};
- let (action_list, action_token_types, authorization_options) =
- if item.router_data.request.setup_future_usage.is_some() {
- (
- Some(vec![CybersourceActionsList::TokenCreate]),
- Some(vec![CybersourceActionsTokenType::InstrumentIdentifier]),
- Some(CybersourceAuthorizationOptions {
- initiator: CybersourcePaymentInitiator {
- initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer),
- credential_stored_on_file: Some(true),
- stored_credential_used: None,
- },
- merchant_intitiated_transaction: None,
- }),
- )
- } else {
- (None, None, None)
- };
- let processing_information = ProcessingInformation {
- capture: Some(matches!(
- item.router_data.request.capture_method,
- Some(enums::CaptureMethod::Automatic) | None
- )),
- capture_options: None,
- action_list,
- action_token_types,
- authorization_options,
- commerce_indicator: CybersourceCommerceIndicator::Internet,
- };
+ let instrument_identifier =
+ item.router_data
+ .request
+ .connector_mandate_id()
+ .map(|mandate_token_id| CybersoucreInstrumentIdentifier {
+ id: mandate_token_id,
+ });
- let client_reference_information = ClientReferenceInformation {
- code: Some(item.router_data.connector_request_reference_id.clone()),
+ let card = if instrument_identifier.is_some() {
+ CardDetails::MandateCard(MandateCardDetails {
+ expiration_month: ccard.card_exp_month,
+ expiration_year: ccard.card_exp_year,
+ })
+ } else {
+ CardDetails::PaymentCard(Card {
+ number: ccard.card_number,
+ expiration_month: ccard.card_exp_month,
+ expiration_year: ccard.card_exp_year,
+ security_code: ccard.card_cvc,
+ card_type,
+ })
};
- let payment_information = match item.router_data.request.payment_method_data.clone() {
- api::PaymentMethodData::Card(ccard) => {
- let instrument_identifier =
- item.router_data
- .request
- .connector_mandate_id()
- .map(|mandate_token_id| CybersoucreInstrumentIdentifier {
- id: mandate_token_id,
- });
- let card = if instrument_identifier.is_some() {
- CardDetails::MandateCard(MandateCardDetails {
- expiration_month: ccard.card_exp_month,
- expiration_year: ccard.card_exp_year,
- })
- } else {
- CardDetails::PaymentCard(Card {
- number: ccard.card_number,
- expiration_month: ccard.card_exp_month,
- expiration_year: ccard.card_exp_year,
- security_code: ccard.card_cvc,
- })
- };
- PaymentInformation {
- card,
- instrument_identifier,
+
+ let payment_information = PaymentInformation::Cards(CardPaymentInformation {
+ card,
+ instrument_identifier,
+ });
+
+ let processing_information = ProcessingInformation::from((item, None));
+ let client_reference_information = ClientReferenceInformation::from(item);
+
+ Ok(Self {
+ processing_information,
+ payment_information,
+ order_information,
+ client_reference_information,
+ })
+ }
+}
+
+impl
+ TryFrom<(
+ &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ payments::GooglePayWalletData,
+ )> for CybersourcePaymentsRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ (item, google_pay_data): (
+ &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ payments::GooglePayWalletData,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let email = item.router_data.request.get_email()?;
+ let bill_to = build_bill_to(item.router_data.get_billing()?, email)?;
+ let order_information = OrderInformationWithBill::from((item, bill_to));
+
+ let payment_information = PaymentInformation::GooglePay(GooglePayPaymentInformation {
+ fluid_data: FluidData {
+ value: Secret::from(
+ consts::BASE64_ENGINE.encode(google_pay_data.tokenization_data.token),
+ ),
+ },
+ });
+
+ let processing_information =
+ ProcessingInformation::from((item, Some(PaymentSolution::GooglePay)));
+ let client_reference_information = ClientReferenceInformation::from(item);
+
+ Ok(Self {
+ processing_information,
+ payment_information,
+ order_information,
+ client_reference_information,
+ })
+ }
+}
+
+impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
+ for CybersourcePaymentsRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ match item.router_data.request.payment_method_data.clone() {
+ payments::PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)),
+ payments::PaymentMethodData::Wallet(wallet_data) => match wallet_data {
+ payments::WalletData::GooglePay(google_pay_data) => {
+ Self::try_from((item, google_pay_data))
}
- }
+ payments::WalletData::ApplePay(_)
+ | payments::WalletData::AliPayQr(_)
+ | payments::WalletData::AliPayRedirect(_)
+ | payments::WalletData::AliPayHkRedirect(_)
+ | payments::WalletData::MomoRedirect(_)
+ | payments::WalletData::KakaoPayRedirect(_)
+ | payments::WalletData::GoPayRedirect(_)
+ | payments::WalletData::GcashRedirect(_)
+ | payments::WalletData::ApplePayRedirect(_)
+ | payments::WalletData::ApplePayThirdPartySdk(_)
+ | payments::WalletData::DanaRedirect {}
+ | payments::WalletData::GooglePayRedirect(_)
+ | payments::WalletData::GooglePayThirdPartySdk(_)
+ | payments::WalletData::MbWayRedirect(_)
+ | payments::WalletData::MobilePayRedirect(_)
+ | payments::WalletData::PaypalRedirect(_)
+ | payments::WalletData::PaypalSdk(_)
+ | payments::WalletData::SamsungPay(_)
+ | payments::WalletData::TwintRedirect {}
+ | payments::WalletData::VippsRedirect {}
+ | payments::WalletData::TouchNGoRedirect(_)
+ | payments::WalletData::WeChatPayRedirect(_)
+ | payments::WalletData::WeChatPayQr(_)
+ | payments::WalletData::CashappQr(_)
+ | payments::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Cybersource"),
+ )
+ .into()),
+ },
payments::PaymentMethodData::CardRedirect(_)
- | payments::PaymentMethodData::Wallet(_)
| payments::PaymentMethodData::PayLater(_)
| payments::PaymentMethodData::BankRedirect(_)
| payments::PaymentMethodData::BankDebit(_)
@@ -389,15 +571,10 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
| payments::PaymentMethodData::CardToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
- ))?
+ )
+ .into())
}
- };
- Ok(Self {
- processing_information,
- payment_information,
- order_information,
- client_reference_information,
- })
+ }
}
}
@@ -433,11 +610,12 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsCaptureRouterData>>
authorization_options: None,
capture: None,
commerce_indicator: CybersourceCommerceIndicator::Internet,
+ payment_solution: None,
},
order_information: OrderInformationWithBill {
amount_details: Amount {
total_amount: item.amount.clone(),
- currency: item.router_data.request.currency.to_string(),
+ currency: item.router_data.request.currency,
},
bill_to: None,
},
@@ -469,6 +647,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsIncrementalAuthorizationRout
commerce_indicator: CybersourceCommerceIndicator::Internet,
capture: None,
capture_options: None,
+ payment_solution: None,
},
order_information: OrderInformationIncrementalAuthorization {
amount_details: AdditionalAmount {
@@ -917,7 +1096,7 @@ impl<F> TryFrom<&CybersourceRouterData<&types::RefundsRouterData<F>>> for Cybers
order_information: OrderInformation {
amount_details: Amount {
total_amount: item.amount.clone(),
- currency: item.router_data.request.currency.to_string(),
+ currency: item.router_data.request.currency,
},
},
})
|
feat
|
[CYBERSOURCE] Implement Google Pay (#3139)
|
21352cf875e360c808562a15fcbb8d8c6a27ae50
|
2024-09-09 13:23:47
|
Hrithikesh
|
feat: enable payment and refund filter at DB query level (#5827)
| false
|
diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs
index d8a9d5f40f4..a9d44bca88f 100644
--- a/crates/diesel_models/src/query/payment_attempt.rs
+++ b/crates/diesel_models/src/query/payment_attempt.rs
@@ -322,6 +322,7 @@ impl PaymentAttempt {
payment_method: Option<Vec<enums::PaymentMethod>>,
payment_method_type: Option<Vec<enums::PaymentMethodType>>,
authentication_type: Option<Vec<enums::AuthenticationType>>,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
) -> StorageResult<i64> {
let mut filter = <Self as HasTable>::table()
@@ -346,6 +347,9 @@ impl PaymentAttempt {
if let Some(merchant_connector_id) = merchant_connector_id {
filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id))
}
+ if let Some(profile_id_list) = profile_id_list {
+ filter = filter.filter(dsl::profile_id.eq_any(profile_id_list))
+ }
router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index 54920dee6ba..b0a660ad5d3 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -14,6 +14,7 @@ pub mod payment_methods;
pub mod payments;
#[cfg(feature = "payouts")]
pub mod payouts;
+pub mod refunds;
pub mod router_data;
pub mod router_data_v2;
pub mod router_flow_types;
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 4c2a67ff126..c39e5b8c092 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -112,6 +112,7 @@ pub trait PaymentAttemptInterface {
payment_method_type: Option<Vec<storage_enums::PaymentMethodType>>,
authentication_type: Option<Vec<storage_enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
+ profile_id_list: Option<Vec<id_type::ProfileId>>,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<i64, errors::StorageError>;
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index 64403cf3b9c..3f62b16c420 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -771,6 +771,16 @@ pub enum PaymentIntentFetchConstraints {
List(Box<PaymentIntentListParams>),
}
+impl PaymentIntentFetchConstraints {
+ pub fn get_profile_id_list(&self) -> Option<Vec<id_type::ProfileId>> {
+ if let Self::List(pi_list_params) = self {
+ pi_list_params.profile_id.clone()
+ } else {
+ None
+ }
+ }
+}
+
pub struct PaymentIntentListParams {
pub offset: u32,
pub starting_at: Option<PrimitiveDateTime>,
@@ -783,7 +793,7 @@ pub struct PaymentIntentListParams {
pub payment_method_type: Option<Vec<storage_enums::PaymentMethodType>>,
pub authentication_type: Option<Vec<storage_enums::AuthenticationType>>,
pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
- pub profile_id: Option<id_type::ProfileId>,
+ pub profile_id: Option<Vec<id_type::ProfileId>>,
pub customer_id: Option<id_type::CustomerId>,
pub starting_after_id: Option<id_type::PaymentId>,
pub ending_before_id: Option<id_type::PaymentId>,
@@ -793,10 +803,21 @@ pub struct PaymentIntentListParams {
impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchConstraints {
fn from(value: api_models::payments::PaymentListConstraints) -> Self {
+ let api_models::payments::PaymentListConstraints {
+ customer_id,
+ starting_after,
+ ending_before,
+ limit,
+ created,
+ created_lt,
+ created_gt,
+ created_lte,
+ created_gte,
+ } = value;
Self::List(Box::new(PaymentIntentListParams {
offset: 0,
- starting_at: value.created_gte.or(value.created_gt).or(value.created),
- ending_at: value.created_lte.or(value.created_lt).or(value.created),
+ starting_at: created_gte.or(created_gt).or(created),
+ ending_at: created_lte.or(created_lt).or(created),
amount_filter: None,
connector: None,
currency: None,
@@ -806,10 +827,10 @@ impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchCo
authentication_type: None,
merchant_connector_id: None,
profile_id: None,
- customer_id: value.customer_id,
- starting_after_id: value.starting_after,
- ending_before_id: value.ending_before,
- limit: Some(std::cmp::min(value.limit, PAYMENTS_LIST_MAX_LIMIT_V1)),
+ customer_id,
+ starting_after_id: starting_after,
+ ending_before_id: ending_before,
+ limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V1)),
order: Default::default(),
}))
}
@@ -841,28 +862,96 @@ impl From<api_models::payments::TimeRange> for PaymentIntentFetchConstraints {
impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentFetchConstraints {
fn from(value: api_models::payments::PaymentListFilterConstraints) -> Self {
- if let Some(payment_intent_id) = value.payment_id {
+ let api_models::payments::PaymentListFilterConstraints {
+ payment_id,
+ profile_id,
+ customer_id,
+ limit,
+ offset,
+ amount_filter,
+ time_range,
+ connector,
+ currency,
+ status,
+ payment_method,
+ payment_method_type,
+ authentication_type,
+ merchant_connector_id,
+ order,
+ } = value;
+ if let Some(payment_intent_id) = payment_id {
Self::Single { payment_intent_id }
} else {
Self::List(Box::new(PaymentIntentListParams {
- offset: value.offset.unwrap_or_default(),
- starting_at: value.time_range.map(|t| t.start_time),
- ending_at: value.time_range.and_then(|t| t.end_time),
- amount_filter: value.amount_filter,
- connector: value.connector,
- currency: value.currency,
- status: value.status,
- payment_method: value.payment_method,
- payment_method_type: value.payment_method_type,
- authentication_type: value.authentication_type,
- merchant_connector_id: value.merchant_connector_id,
- profile_id: value.profile_id,
- customer_id: value.customer_id,
+ offset: offset.unwrap_or_default(),
+ starting_at: time_range.map(|t| t.start_time),
+ ending_at: time_range.and_then(|t| t.end_time),
+ amount_filter,
+ connector,
+ currency,
+ status,
+ payment_method,
+ payment_method_type,
+ authentication_type,
+ merchant_connector_id,
+ profile_id: profile_id.map(|profile_id| vec![profile_id]),
+ customer_id,
starting_after_id: None,
ending_before_id: None,
- limit: Some(std::cmp::min(value.limit, PAYMENTS_LIST_MAX_LIMIT_V2)),
- order: value.order,
+ limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V2)),
+ order,
}))
}
}
}
+
+impl<T> TryFrom<(T, Option<Vec<id_type::ProfileId>>)> for PaymentIntentFetchConstraints
+where
+ Self: From<T>,
+{
+ type Error = error_stack::Report<errors::api_error_response::ApiErrorResponse>;
+ fn try_from(
+ (constraints, auth_profile_id_list): (T, Option<Vec<id_type::ProfileId>>),
+ ) -> Result<Self, Self::Error> {
+ let payment_intent_constraints = Self::from(constraints);
+ if let Self::List(mut pi_list_params) = payment_intent_constraints {
+ let profile_id_from_request_body = pi_list_params.profile_id;
+ match (profile_id_from_request_body, auth_profile_id_list) {
+ (None, None) => pi_list_params.profile_id = None,
+ (None, Some(auth_profile_id_list)) => {
+ pi_list_params.profile_id = Some(auth_profile_id_list)
+ }
+ (Some(profile_id_from_request_body), None) => {
+ pi_list_params.profile_id = Some(profile_id_from_request_body)
+ }
+ (Some(profile_id_from_request_body), Some(auth_profile_id_list)) => {
+ let profile_id_from_request_body_is_available_in_auth_profile_id_list =
+ profile_id_from_request_body
+ .iter()
+ .all(|profile_id| auth_profile_id_list.contains(profile_id));
+
+ if profile_id_from_request_body_is_available_in_auth_profile_id_list {
+ pi_list_params.profile_id = Some(profile_id_from_request_body)
+ } else {
+ // This scenario is very unlikely to happen
+ let inaccessible_profile_ids: Vec<_> = profile_id_from_request_body
+ .iter()
+ .filter(|profile_id| !auth_profile_id_list.contains(profile_id))
+ .collect();
+ return Err(error_stack::Report::new(
+ errors::api_error_response::ApiErrorResponse::PreconditionFailed {
+ message: format!(
+ "Access not available for the given profile_id {:?}",
+ inaccessible_profile_ids
+ ),
+ },
+ ));
+ }
+ }
+ }
+ Ok(Self::List(pi_list_params))
+ } else {
+ Ok(payment_intent_constraints)
+ }
+ }
+}
diff --git a/crates/hyperswitch_domain_models/src/refunds.rs b/crates/hyperswitch_domain_models/src/refunds.rs
new file mode 100644
index 00000000000..3b3a79407d0
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/refunds.rs
@@ -0,0 +1,82 @@
+use crate::errors;
+
+pub struct RefundListConstraints {
+ pub payment_id: Option<common_utils::id_type::PaymentId>,
+ pub refund_id: Option<String>,
+ pub profile_id: Option<Vec<common_utils::id_type::ProfileId>>,
+ pub limit: Option<i64>,
+ pub offset: Option<i64>,
+ pub time_range: Option<api_models::payments::TimeRange>,
+ pub amount_filter: Option<api_models::payments::AmountFilter>,
+ pub connector: Option<Vec<String>>,
+ pub merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
+ pub currency: Option<Vec<common_enums::Currency>>,
+ pub refund_status: Option<Vec<common_enums::RefundStatus>>,
+}
+
+impl
+ TryFrom<(
+ api_models::refunds::RefundListRequest,
+ Option<Vec<common_utils::id_type::ProfileId>>,
+ )> for RefundListConstraints
+{
+ type Error = error_stack::Report<errors::api_error_response::ApiErrorResponse>;
+
+ fn try_from(
+ (value, auth_profile_id_list): (
+ api_models::refunds::RefundListRequest,
+ Option<Vec<common_utils::id_type::ProfileId>>,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let api_models::refunds::RefundListRequest {
+ connector,
+ currency,
+ refund_status,
+ payment_id,
+ refund_id,
+ profile_id,
+ limit,
+ offset,
+ time_range,
+ amount_filter,
+ merchant_connector_id,
+ } = value;
+ let profile_id_from_request_body = profile_id;
+ let profile_id_list = match (profile_id_from_request_body, auth_profile_id_list) {
+ (None, None) => None,
+ (None, Some(auth_profile_id_list)) => Some(auth_profile_id_list),
+ (Some(profile_id_from_request_body), None) => Some(vec![profile_id_from_request_body]),
+ (Some(profile_id_from_request_body), Some(auth_profile_id_list)) => {
+ let profile_id_from_request_body_is_available_in_auth_profile_id_list =
+ auth_profile_id_list.contains(&profile_id_from_request_body);
+
+ if profile_id_from_request_body_is_available_in_auth_profile_id_list {
+ Some(vec![profile_id_from_request_body])
+ } else {
+ // This scenario is very unlikely to happen
+ return Err(error_stack::Report::new(
+ errors::api_error_response::ApiErrorResponse::PreconditionFailed {
+ message: format!(
+ "Access not available for the given profile_id {:?}",
+ profile_id_from_request_body
+ ),
+ },
+ ));
+ }
+ }
+ };
+ Ok(Self {
+ payment_id,
+ refund_id,
+ profile_id: profile_id_list,
+ limit,
+ offset,
+ time_range,
+ amount_filter,
+ connector,
+ merchant_connector_id,
+ currency,
+ refund_status,
+ })
+ }
+}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index f71bf9b94ab..29566b6b9a0 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -2940,15 +2940,13 @@ pub async fn list_payments(
let db = state.store.as_ref();
let payment_intents = helpers::filter_by_constraints(
&state,
- &constraints,
+ &(constraints, profile_id_list).try_into()?,
merchant_id,
&key_store,
merchant.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
- let payment_intents =
- utils::filter_objects_based_on_profile_id_list(profile_id_list, payment_intents);
let collected_futures = payment_intents.into_iter().map(|pi| {
async {
@@ -3011,25 +3009,25 @@ pub async fn apply_filters_on_payments(
) -> RouterResponse<api::PaymentListResponseV2> {
let limit = &constraints.limit;
helpers::validate_payment_list_request_for_joins(*limit)?;
- let db = state.store.as_ref();
+ let db: &dyn StorageInterface = state.store.as_ref();
+ let pi_fetch_constraints = (constraints.clone(), profile_id_list.clone()).try_into()?;
let list: Vec<(storage::PaymentIntent, storage::PaymentAttempt)> = db
.get_filtered_payment_intents_attempt(
&(&state).into(),
merchant.get_id(),
- &constraints.clone().into(),
+ &pi_fetch_constraints,
&merchant_key_store,
merchant.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
- let list = utils::filter_objects_based_on_profile_id_list(profile_id_list, list);
let data: Vec<api::PaymentsResponse> =
list.into_iter().map(ForeignFrom::foreign_from).collect();
let active_attempt_ids = db
.get_filtered_active_attempt_ids_for_total_count(
merchant.get_id(),
- &constraints.clone().into(),
+ &pi_fetch_constraints,
merchant.storage_scheme,
)
.await
@@ -3044,6 +3042,7 @@ pub async fn apply_filters_on_payments(
constraints.payment_method_type,
constraints.authentication_type,
constraints.merchant_connector_id,
+ pi_fetch_constraints.get_profile_id_list(),
merchant.storage_scheme,
)
.await
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index fdec36d3b76..d97e609aee4 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -26,7 +26,10 @@ use hyperswitch_domain_models::payments::payment_intent::CustomerData;
use hyperswitch_domain_models::{
mandates::MandateData,
payment_method_data::GetPaymentMethodType,
- payments::{payment_attempt::PaymentAttempt, PaymentIntent},
+ payments::{
+ payment_attempt::PaymentAttempt, payment_intent::PaymentIntentFetchConstraints,
+ PaymentIntent,
+ },
router_data::KlarnaSdkResponse,
};
use hyperswitch_interfaces::integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject};
@@ -2538,7 +2541,7 @@ where
#[cfg(feature = "olap")]
pub(super) async fn filter_by_constraints(
state: &SessionState,
- constraints: &api::PaymentListConstraints,
+ constraints: &PaymentIntentFetchConstraints,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: storage_enums::MerchantStorageScheme,
@@ -2548,7 +2551,7 @@ pub(super) async fn filter_by_constraints(
.filter_payment_intent_by_constraints(
&(state).into(),
merchant_id,
- &constraints.clone().into(),
+ constraints,
key_store,
storage_scheme,
)
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 1761c0bad03..b702b32a733 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -869,7 +869,7 @@ pub async fn validate_and_create_refund(
pub async fn refund_list(
state: SessionState,
merchant_account: domain::MerchantAccount,
- _profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
req: api_models::refunds::RefundListRequest,
) -> RouterResponse<api_models::refunds::RefundListResponse> {
let db = state.store;
@@ -879,7 +879,7 @@ pub async fn refund_list(
let refund_list = db
.filter_refund_by_constraints(
merchant_account.get_id(),
- &req,
+ &(req.clone(), profile_id_list.clone()).try_into()?,
merchant_account.storage_scheme,
limit,
offset,
@@ -895,7 +895,7 @@ pub async fn refund_list(
let total_count = db
.get_total_count_of_refunds(
merchant_account.get_id(),
- &req,
+ &(req, profile_id_list).try_into()?,
merchant_account.storage_scheme,
)
.await
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 31ed4ad93e2..9c625f1f2b5 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -9,13 +9,14 @@ use diesel_models::{
reverse_lookup::{ReverseLookup, ReverseLookupNew},
user_role as user_storage,
};
-use hyperswitch_domain_models::payments::{
- payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface,
-};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::payouts::{
payout_attempt::PayoutAttemptInterface, payouts::PayoutsInterface,
};
+use hyperswitch_domain_models::{
+ payments::{payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface},
+ refunds,
+};
#[cfg(not(feature = "payouts"))]
use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};
use masking::Secret;
@@ -1490,6 +1491,7 @@ impl PaymentAttemptInterface for KafkaStore {
payment_method_type: Option<Vec<common_enums::PaymentMethodType>>,
authentication_type: Option<Vec<common_enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
+ profile_id_list: Option<Vec<id_type::ProfileId>>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::DataStorageError> {
self.diesel_store
@@ -1501,6 +1503,7 @@ impl PaymentAttemptInterface for KafkaStore {
payment_method_type,
authentication_type,
merchant_connector_id,
+ profile_id_list,
storage_scheme,
)
.await
@@ -2361,7 +2364,7 @@ impl RefundInterface for KafkaStore {
async fn filter_refund_by_constraints(
&self,
merchant_id: &id_type::MerchantId,
- refund_details: &api_models::refunds::RefundListRequest,
+ refund_details: &refunds::RefundListConstraints,
storage_scheme: MerchantStorageScheme,
limit: i64,
offset: i64,
@@ -2393,7 +2396,7 @@ impl RefundInterface for KafkaStore {
async fn get_total_count_of_refunds(
&self,
merchant_id: &id_type::MerchantId,
- refund_details: &api_models::refunds::RefundListRequest,
+ refund_details: &refunds::RefundListConstraints,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
self.diesel_store
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index e6b46c5af5c..6208a06d141 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -4,6 +4,7 @@ use std::collections::HashSet;
#[cfg(feature = "olap")]
use common_utils::types::MinorUnit;
use diesel_models::{errors::DatabaseError, refund::RefundUpdateInternal};
+use hyperswitch_domain_models::refunds;
use super::MockDb;
use crate::{
@@ -69,7 +70,7 @@ pub trait RefundInterface {
async fn filter_refund_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- refund_details: &api_models::refunds::RefundListRequest,
+ refund_details: &refunds::RefundListConstraints,
storage_scheme: enums::MerchantStorageScheme,
limit: i64,
offset: i64,
@@ -87,7 +88,7 @@ pub trait RefundInterface {
async fn get_total_count_of_refunds(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- refund_details: &api_models::refunds::RefundListRequest,
+ refund_details: &refunds::RefundListConstraints,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError>;
}
@@ -216,7 +217,7 @@ mod storage {
async fn filter_refund_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- refund_details: &api_models::refunds::RefundListRequest,
+ refund_details: &refunds::RefundListConstraints,
_storage_scheme: enums::MerchantStorageScheme,
limit: i64,
offset: i64,
@@ -255,7 +256,7 @@ mod storage {
async fn get_total_count_of_refunds(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- refund_details: &api_models::refunds::RefundListRequest,
+ refund_details: &refunds::RefundListConstraints,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -274,6 +275,7 @@ mod storage {
mod storage {
use common_utils::{ext_traits::Encode, fallback_reverse_lookup_not_found};
use error_stack::{report, ResultExt};
+ use hyperswitch_domain_models::refunds;
use redis_interface::HsetnxReply;
use router_env::{instrument, tracing};
use storage_impl::redis::kv_store::{
@@ -752,7 +754,7 @@ mod storage {
async fn filter_refund_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- refund_details: &api_models::refunds::RefundListRequest,
+ refund_details: &refunds::RefundListConstraints,
_storage_scheme: enums::MerchantStorageScheme,
limit: i64,
offset: i64,
@@ -788,7 +790,7 @@ mod storage {
async fn get_total_count_of_refunds(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- refund_details: &api_models::refunds::RefundListRequest,
+ refund_details: &refunds::RefundListConstraints,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -963,7 +965,7 @@ impl RefundInterface for MockDb {
async fn filter_refund_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- refund_details: &api_models::refunds::RefundListRequest,
+ refund_details: &refunds::RefundListConstraints,
_storage_scheme: enums::MerchantStorageScheme,
limit: i64,
offset: i64,
@@ -972,6 +974,7 @@ impl RefundInterface for MockDb {
let mut unique_merchant_connector_ids = HashSet::new();
let mut unique_currencies = HashSet::new();
let mut unique_statuses = HashSet::new();
+ let mut unique_profile_ids = HashSet::new();
// Fill the hash sets with data from refund_details
if let Some(connectors) = &refund_details.connector {
@@ -1000,6 +1003,10 @@ impl RefundInterface for MockDb {
});
}
+ if let Some(profile_id_list) = &refund_details.profile_id {
+ unique_profile_ids = profile_id_list.iter().collect();
+ }
+
let refunds = self.refunds.lock().await;
let filtered_refunds = refunds
.iter()
@@ -1016,7 +1023,11 @@ impl RefundInterface for MockDb {
.clone()
.map_or(true, |id| id == refund.refund_id)
})
- .filter(|refund| refund_details.profile_id == refund.profile_id)
+ .filter(|refund| {
+ refund.profile_id.as_ref().is_some_and(|profile_id| {
+ unique_profile_ids.is_empty() || unique_profile_ids.contains(profile_id)
+ })
+ })
.filter(|refund| {
refund.created_at
>= refund_details.time_range.map_or(
@@ -1116,13 +1127,14 @@ impl RefundInterface for MockDb {
async fn get_total_count_of_refunds(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- refund_details: &api_models::refunds::RefundListRequest,
+ refund_details: &refunds::RefundListConstraints,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
let mut unique_connectors = HashSet::new();
let mut unique_merchant_connector_ids = HashSet::new();
let mut unique_currencies = HashSet::new();
let mut unique_statuses = HashSet::new();
+ let mut unique_profile_ids = HashSet::new();
// Fill the hash sets with data from refund_details
if let Some(connectors) = &refund_details.connector {
@@ -1151,6 +1163,10 @@ impl RefundInterface for MockDb {
});
}
+ if let Some(profile_id_list) = &refund_details.profile_id {
+ unique_profile_ids = profile_id_list.iter().collect();
+ }
+
let refunds = self.refunds.lock().await;
let filtered_refunds = refunds
.iter()
@@ -1167,7 +1183,11 @@ impl RefundInterface for MockDb {
.clone()
.map_or(true, |id| id == refund.refund_id)
})
- .filter(|refund| refund_details.profile_id == refund.profile_id)
+ .filter(|refund| {
+ refund.profile_id.as_ref().is_some_and(|profile_id| {
+ unique_profile_ids.is_empty() || unique_profile_ids.contains(profile_id)
+ })
+ })
.filter(|refund| {
refund.created_at
>= refund_details.time_range.map_or(
diff --git a/crates/router/src/types/storage/refund.rs b/crates/router/src/types/storage/refund.rs
index 1860771d026..257982a0fba 100644
--- a/crates/router/src/types/storage/refund.rs
+++ b/crates/router/src/types/storage/refund.rs
@@ -12,6 +12,7 @@ use diesel_models::{
schema::refund::dsl,
};
use error_stack::ResultExt;
+use hyperswitch_domain_models::refunds;
use crate::{connection::PgPooledConn, logger};
@@ -20,7 +21,7 @@ pub trait RefundDbExt: Sized {
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
- refund_list_details: &api_models::refunds::RefundListRequest,
+ refund_list_details: &refunds::RefundListConstraints,
limit: i64,
offset: i64,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
@@ -34,7 +35,7 @@ pub trait RefundDbExt: Sized {
async fn get_refunds_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
- refund_list_details: &api_models::refunds::RefundListRequest,
+ refund_list_details: &refunds::RefundListConstraints,
) -> CustomResult<i64, errors::DatabaseError>;
}
@@ -43,7 +44,7 @@ impl RefundDbExt for Refund {
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
- refund_list_details: &api_models::refunds::RefundListRequest,
+ refund_list_details: &refunds::RefundListConstraints,
limit: i64,
offset: i64,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
@@ -88,7 +89,7 @@ impl RefundDbExt for Refund {
match &refund_list_details.profile_id {
Some(profile_id) => {
filter = filter
- .filter(dsl::profile_id.eq(profile_id.to_owned()))
+ .filter(dsl::profile_id.eq_any(profile_id.to_owned()))
.limit(limit)
.offset(offset);
}
@@ -206,7 +207,7 @@ impl RefundDbExt for Refund {
async fn get_refunds_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
- refund_list_details: &api_models::refunds::RefundListRequest,
+ refund_list_details: &refunds::RefundListConstraints,
) -> CustomResult<i64, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
.count()
@@ -237,7 +238,7 @@ impl RefundDbExt for Refund {
}
}
if let Some(profile_id) = &refund_list_details.profile_id {
- filter = filter.filter(dsl::profile_id.eq(profile_id.to_owned()));
+ filter = filter.filter(dsl::profile_id.eq_any(profile_id.to_owned()));
}
if let Some(time_range) = refund_list_details.time_range {
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index 9cdc1e87ce8..11205b94db5 100644
--- a/crates/storage_impl/src/mock_db/payment_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs
@@ -45,6 +45,7 @@ impl PaymentAttemptInterface for MockDb {
_payment_method_type: Option<Vec<PaymentMethodType>>,
_authentication_type: Option<Vec<AuthenticationType>>,
_merchanat_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
+ _profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<i64, StorageError> {
Err(StorageError::MockDbError)?
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index 7edf5fd5a77..3cc04e8af5d 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -296,6 +296,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
payment_method_type: Option<Vec<PaymentMethodType>>,
authentication_type: Option<Vec<AuthenticationType>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
let conn = self
@@ -318,6 +319,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
payment_method,
payment_method_type,
authentication_type,
+ profile_id_list,
merchant_connector_id,
)
.await
@@ -1067,6 +1069,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_method_type: Option<Vec<PaymentMethodType>>,
authentication_type: Option<Vec<AuthenticationType>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
self.router_store
@@ -1078,6 +1081,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_method_type,
authentication_type,
merchant_connector_id,
+ profile_id_list,
storage_scheme,
)
.await
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index 4624f33eec3..f69c26e6409 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -553,7 +553,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
query = query.filter(pi_dsl::customer_id.eq(customer_id.clone()));
}
if let Some(profile_id) = ¶ms.profile_id {
- query = query.filter(pi_dsl::profile_id.eq(profile_id.clone()));
+ query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone()));
}
query = match (params.starting_at, ¶ms.starting_after_id) {
@@ -758,7 +758,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
}
if let Some(profile_id) = ¶ms.profile_id {
- query = query.filter(pi_dsl::profile_id.eq(profile_id.clone()));
+ query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone()));
}
query = match (params.starting_at, ¶ms.starting_after_id) {
@@ -922,7 +922,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
query = query.filter(pi_dsl::customer_id.eq(customer_id.clone()));
}
if let Some(profile_id) = ¶ms.profile_id {
- query = query.filter(pi_dsl::profile_id.eq(profile_id.clone()));
+ query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone()));
}
query = match params.starting_at {
|
feat
|
enable payment and refund filter at DB query level (#5827)
|
8a019f08acf74e04c3ae9c8790dd481301bdcfee
|
2024-01-24 15:46:29
|
AkshayaFoiger
|
refactor(compatibility): revert add multiuse mandates support in stripe compatibility (#3436)
| false
|
diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs
index 51f938d445c..38007a3110d 100644
--- a/crates/router/src/compatibility/stripe/payment_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs
@@ -738,25 +738,9 @@ impl ForeignTryFrom<(Option<MandateData>, Option<String>)> for Option<payments::
metadata: None,
},
)),
- StripeMandateType::MultiUse => Some(payments::MandateType::MultiUse(Some(
- payments::MandateAmountData {
- amount: mandate.amount.unwrap_or_default(),
- currency,
- start_date: mandate.start_date,
- end_date: mandate.end_date,
- metadata: None,
- },
- ))),
+ StripeMandateType::MultiUse => Some(payments::MandateType::MultiUse(None)),
},
- None => Some(api_models::payments::MandateType::MultiUse(Some(
- payments::MandateAmountData {
- amount: mandate.amount.unwrap_or_default(),
- currency,
- start_date: mandate.start_date,
- end_date: mandate.end_date,
- metadata: None,
- },
- ))),
+ None => Some(api_models::payments::MandateType::MultiUse(None)),
},
customer_acceptance: Some(payments::CustomerAcceptance {
acceptance_type: payments::AcceptanceType::Online,
|
refactor
|
revert add multiuse mandates support in stripe compatibility (#3436)
|
1cdc1367a777d98e5d5e40adbf5dcbc5d926e974
|
2022-12-19 15:41:26
|
Nishant Joshi
|
fix(router_env): resolve/remove `FIXME`'s and redundent files (#168)
| false
|
diff --git a/Cargo.lock b/Cargo.lock
index db913f6c007..5a17c96e964 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2799,6 +2799,7 @@ dependencies = [
"rustc-hash",
"serde",
"serde_json",
+ "serde_path_to_error",
"strum",
"time",
"tokio",
diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.toml
index d9fb1518a09..82615bc2e6b 100644
--- a/crates/router_env/Cargo.toml
+++ b/crates/router_env/Cargo.toml
@@ -17,6 +17,7 @@ opentelemetry-otlp = { git = "https://github.com/open-telemetry/opentelemetry-ru
rustc-hash = "1.1"
serde = { version = "1.0.149", features = ["derive"] }
serde_json = "1.0.89"
+serde_path_to_error = "0.1.8"
strum = { version = "0.24.1", features = ["derive"] }
time = { version = "0.3.17", default-features = false, features = ["formatting"] }
tokio = { version = "1.23.0" }
diff --git a/crates/router_env/README.md b/crates/router_env/README.md
index 1812281241d..6108585645b 100644
--- a/crates/router_env/README.md
+++ b/crates/router_env/README.md
@@ -22,8 +22,6 @@ pub fn sample() -> () {
## Files Tree Layout
-<!-- FIXME: fill missing -->
-
```text
├── src : source code
│ └── logger : logger
diff --git a/crates/router_env/src/logger/config.rs b/crates/router_env/src/logger/config.rs
index 114fad09335..a823aef47b5 100644
--- a/crates/router_env/src/logger/config.rs
+++ b/crates/router_env/src/logger/config.rs
@@ -115,22 +115,15 @@ impl Config {
let environment = crate::env::which();
let config_path = Self::config_path(&environment.to_string(), explicit_config_path);
- // println!(
- // "config_path : {:?} {:?}",
- // config_path,
- // std::path::Path::new(&config_path).exists()
- // );
-
let config = Self::builder(&environment.to_string())?
.add_source(config::File::from(config_path).required(true))
.add_source(config::Environment::with_prefix("ROUTER").separator("__"))
.build()?;
- // FIXME: in case config is missing information about error is not readable
- config.try_deserialize().map_err(|e| {
- crate::error!("Unable to source config file");
- eprintln!("Unable to source config file");
- e
+ serde_path_to_error::deserialize(config).map_err(|error| {
+ crate::error!(%error, "Unable to deserialize configuration");
+ eprintln!("Unable to deserialize application configuration: {error}");
+ error.into_inner()
})
}
@@ -144,6 +137,7 @@ impl Config {
// Should be single source of truth.
.set_override("env", environment)?
.add_source(config::File::from_str(
+ // Plan on handling with the changes in crates/router
// FIXME: embedding of textual file into bin files has several disadvantages
// 1. larger bin file
// 2. slower initialization of program
diff --git a/crates/router_env/src/logger/formatter.rs b/crates/router_env/src/logger/formatter.rs
index 11d9abc66bc..cc66fccfe4a 100644
--- a/crates/router_env/src/logger/formatter.rs
+++ b/crates/router_env/src/logger/formatter.rs
@@ -22,8 +22,7 @@ use tracing_subscriber::{
};
use crate::Storage;
-
-// FIXME: xxx: Describe each implicit field with examples.
+// TODO: Documentation coverage for this crate
// Implicit keys
@@ -52,14 +51,6 @@ const REQUEST_METHOD: &str = "request_method";
const REQUEST_URL_PATH: &str = "request_url_path";
const REQUEST_ID: &str = "request_id";
-//const TAG: &str = "tag";
-//const CATEGORY: &str = "category";
-//const SESSION_ID: &str = "session_id";
-//const PAYMENT_ID: &str = "payment_id";
-//const PAYMENT_ATTEMPT_ID: &str = "payment_attempt_id";
-//const MERCHANT_ID: &str = "merchant_id";
-//const FLOW: &str = "flow";
-
/// Set of predefined implicit keys.
pub static IMPLICIT_KEYS: Lazy<rustc_hash::FxHashSet<&str>> = Lazy::new(|| {
let mut set = rustc_hash::FxHashSet::default();
diff --git a/crates/router_env/src/logger/macros.rs b/crates/router_env/src/logger/macros.rs
deleted file mode 100644
index c3398e98c64..00000000000
--- a/crates/router_env/src/logger/macros.rs
+++ /dev/null
@@ -1,104 +0,0 @@
-//!
-//! Macros.
-//!
-
-pub use crate::log;
-
-///
-/// Make a new log Event.
-///
-/// The event macro is invoked with a Level and up to 32 key-value fields.
-/// Optionally, a format string and arguments may follow the fields; this will be used to construct an implicit field named “message”.
-/// See the top-level [documentation of tracing](https://docs.rs/tracing/latest/tracing/index.html#using-the-macros) for details on the syntax accepted by this macro.
-///
-/// # Example
-/// ```rust
-/// // FIXME: write
-/// ```
-///
-
-#[macro_export]
-macro_rules! log {
-
- // done
-
- (
- @MUNCH
- {
- level : { $level:ident },
- tag : { $tag:ident },
- category : { $category:ident },
- flow : { $flow:expr },
- // $( session_id : { $session_id:expr }, )?
- // $( payment_id : { $payment_id:expr }, )?
- // $( payment_attempt_id : { $payment_attempt_id:expr }, )?
- // $( merchant_id : { $merchant_id:expr }, )?
- },
- $( $tail:tt )*
- )
- =>
- (
- ::tracing::event!
- (
- ::router_env::Level::$level,
- level = ?::router_env::Level::$level,
- tag = ?::router_env::Tag::$tag,
- category = ?::router_env::Category::$category,
- flow = ?$flow,
- // $( session_id = $session_id, )?
- // $( payment_id = $payment_id, )?
- // $( payment_attempt_id = $payment_attempt_id, )?
- // $( merchant_id = $merchant_id, )?
- $( $tail )*
- );
- );
-
- // entry with colon
-
- (
- level : $level:ident,
- tag : $tag:ident,
- category : $category:ident,
- flow : $(?)?$flow:expr,
- $( $tail:tt )*
- )
- =>
- (
- $crate::log!
- {
- @MUNCH
- {
- level : { $level },
- tag : { $tag },
- category : { $category },
- flow : { $flow },
- },
- $( $tail )*
- }
- );
-
- // entry without colon
-
- (
- $level:ident,
- $tag:ident,
- $category:ident,
- $flow:expr,
- $( $tail:tt )*
- )
- =>
- (
- $crate::log!
- {
- @MUNCH
- {
- level : { $level },
- tag : { $tag },
- category : { $category },
- flow : { $flow },
- },
- $( $tail )*
- }
- );
-
-}
diff --git a/crates/router_env/src/logger/setup.rs b/crates/router_env/src/logger/setup.rs
index 4ba3bbc3429..e2970b3be1a 100644
--- a/crates/router_env/src/logger/setup.rs
+++ b/crates/router_env/src/logger/setup.rs
@@ -22,30 +22,6 @@ use tracing_subscriber::{
use crate::{config, FormattingLayer, Level, StorageSubscription};
-// FIXME: xxx: clean
-pub struct DebugLayer;
-impl<S> Layer<S> for DebugLayer
-where
- S: tracing::Subscriber,
-{
- fn on_event(
- &self,
- event: &tracing::Event<'_>,
- _ctx: tracing_subscriber::layer::Context<'_, S>,
- ) {
- if event.metadata().level() == &Level::TRACE {
- return;
- }
- println!("Got event!");
- println!(" level={:?}", event.metadata().level());
- println!(" target={:?}", event.metadata().target());
- println!(" name={:?}", event.metadata().name());
- for field in event.fields() {
- println!(" field={}", field.name());
- }
- }
-}
-
/// TelemetryGuard which helps with
#[derive(Debug)]
pub struct TelemetryGuard {
|
fix
|
resolve/remove `FIXME`'s and redundent files (#168)
|
23762a479f1082a6659c8af83c70c23b0ec08aec
|
2022-11-23 19:08:12
|
Sampras Lopes
|
ci(release): fix the docker router release image build step (#11)
| false
|
diff --git a/.github/workflows/auto-release-tag.yml b/.github/workflows/auto-release-tag.yml
index c0b89d62991..37c9feed756 100644
--- a/.github/workflows/auto-release-tag.yml
+++ b/.github/workflows/auto-release-tag.yml
@@ -13,7 +13,7 @@ jobs:
- uses: actions/checkout@v3
- name: Build router Docker image
- run: docker build . --file Dockerfile --tag juspaydotin/orca:${{ github.ref_name }} --build-arg APP_MODE=router --build-arg BINARY=bach
+ run: docker build . --file Dockerfile --tag juspaydotin/orca:${{ github.ref_name }} --build-arg APP_MODE=router
- name: Build consumer Docker image
run: docker build . --file Dockerfile --tag juspaydotin/orca-consumer:${{ github.ref_name }} --build-arg APP_MODE=consumer --build-arg BINARY=scheduler --build-arg SCHEDULER_FLOW=Consumer
diff --git a/.github/workflows/manual-release.yml b/.github/workflows/manual-release.yml
index 3fbb18e26c9..29a0499c4ff 100644
--- a/.github/workflows/manual-release.yml
+++ b/.github/workflows/manual-release.yml
@@ -11,7 +11,7 @@ jobs:
- uses: actions/checkout@v3
- name: Build router Docker image
- run: docker build . --file Dockerfile --tag juspaydotin/orca:${{ github.sha }} --build-arg APP_MODE=router --build-arg BINARY=bach
+ run: docker build . --file Dockerfile --tag juspaydotin/orca:${{ github.sha }} --build-arg APP_MODE=router
- name: Build consumer Docker image
run: docker build . --file Dockerfile --tag juspaydotin/orca-consumer:${{ github.sha }} --build-arg APP_MODE=consumer --build-arg BINARY=scheduler --build-arg SCHEDULER_FLOW=Consumer
|
ci
|
fix the docker router release image build step (#11)
|
57366f3304121b9f7dd8b4afa1ae002822c292e5
|
2022-12-21 17:10:00
|
Nishant Joshi
|
fix: send Connector as reference for base_url (#200)
| false
|
diff --git a/crates/router/src/connector/aci.rs b/crates/router/src/connector/aci.rs
index e3f55c2b55d..e4cbec17f35 100644
--- a/crates/router/src/connector/aci.rs
+++ b/crates/router/src/connector/aci.rs
@@ -30,8 +30,8 @@ impl api::ConnectorCommon for Aci {
"application/x-www-form-urlencoded"
}
- fn base_url(&self, connectors: settings::Connectors) -> String {
- connectors.aci.base_url
+ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ connectors.aci.base_url.as_ref()
}
fn get_auth_header(
@@ -112,7 +112,7 @@ impl
fn get_url(
&self,
req: &types::PaymentsSyncRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth = aci::AciAuthType::try_from(&req.connector_auth_type)?;
Ok(format!(
@@ -131,7 +131,7 @@ impl
fn build_request(
&self,
req: &types::PaymentsSyncRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
@@ -216,7 +216,7 @@ impl
fn get_url(
&self,
_req: &types::PaymentsAuthorizeRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "v1/payments"))
}
@@ -239,7 +239,7 @@ impl
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
@@ -323,7 +323,7 @@ impl
fn get_url(
&self,
req: &types::PaymentsCancelRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = &req.request.connector_transaction_id;
Ok(format!("{}v1/payments/{}", self.base_url(connectors), id))
@@ -340,7 +340,7 @@ impl
fn build_request(
&self,
req: &types::PaymentsCancelRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
@@ -421,7 +421,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
fn get_url(
&self,
req: &types::RefundsRouterData<api::Execute>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
@@ -443,7 +443,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
fn build_request(
&self,
req: &types::RefundsRouterData<api::Execute>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs
index 9aea53aed02..312231a29db 100644
--- a/crates/router/src/connector/adyen.rs
+++ b/crates/router/src/connector/adyen.rs
@@ -40,8 +40,8 @@ impl api::ConnectorCommon for Adyen {
Ok(vec![(headers::X_API_KEY.to_string(), auth.api_key)])
}
- fn base_url(&self, connectors: settings::Connectors) -> String {
- connectors.adyen.base_url
+ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ connectors.adyen.base_url.as_ref()
}
}
@@ -153,7 +153,7 @@ impl
fn get_url(
&self,
_req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
@@ -165,7 +165,7 @@ impl
fn build_request(
&self,
req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
@@ -245,7 +245,7 @@ impl
fn get_url(
&self,
_req: &types::PaymentsAuthorizeRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "v68/payments"))
}
@@ -266,7 +266,7 @@ impl
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
@@ -340,7 +340,7 @@ impl
fn get_url(
&self,
_req: &types::PaymentsCancelRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "v68/cancel"))
}
@@ -356,7 +356,7 @@ impl
fn build_request(
&self,
req: &types::PaymentsCancelRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
@@ -428,7 +428,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
fn get_url(
&self,
req: &types::RefundsRouterData<api::Execute>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
@@ -450,7 +450,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
fn build_request(
&self,
req: &types::RefundsRouterData<api::Execute>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
diff --git a/crates/router/src/connector/applepay.rs b/crates/router/src/connector/applepay.rs
index 1cff6f3054f..3f6bfb04ad8 100644
--- a/crates/router/src/connector/applepay.rs
+++ b/crates/router/src/connector/applepay.rs
@@ -26,8 +26,8 @@ impl api::ConnectorCommon for Applepay {
"applepay"
}
- fn base_url(&self, connectors: settings::Connectors) -> String {
- connectors.applepay.base_url
+ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ connectors.applepay.base_url.as_ref()
}
}
@@ -103,7 +103,7 @@ impl
fn get_url(
&self,
_req: &types::PaymentsSessionRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
@@ -124,7 +124,7 @@ impl
fn build_request(
&self,
req: &types::PaymentsSessionRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs
index d382f761557..8be464900e3 100644
--- a/crates/router/src/connector/authorizedotnet.rs
+++ b/crates/router/src/connector/authorizedotnet.rs
@@ -32,8 +32,8 @@ impl api::ConnectorCommon for Authorizedotnet {
"application/json"
}
- fn base_url(&self, connectors: settings::Connectors) -> String {
- connectors.authorizedotnet.base_url
+ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ connectors.authorizedotnet.base_url.as_ref()
}
}
@@ -101,9 +101,9 @@ impl
fn get_url(
&self,
_req: &types::PaymentsSyncRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Ok(self.base_url(connectors))
+ Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
@@ -121,7 +121,7 @@ impl
fn build_request(
&self,
req: &types::PaymentsSyncRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::Method::Post)
@@ -193,9 +193,9 @@ impl
fn get_url(
&self,
_req: &types::PaymentsAuthorizeRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Ok(self.base_url(connectors))
+ Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
@@ -216,7 +216,7 @@ impl
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
@@ -292,9 +292,9 @@ impl
fn get_url(
&self,
_req: &types::PaymentsCancelRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Ok(self.base_url(connectors))
+ Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
@@ -309,7 +309,7 @@ impl
fn build_request(
&self,
req: &types::PaymentsCancelRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
@@ -384,9 +384,9 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
fn get_url(
&self,
_req: &types::RefundsRouterData<api::Execute>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Ok(self.base_url(connectors))
+ Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
@@ -403,7 +403,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
fn build_request(
&self,
req: &types::RefundsRouterData<api::Execute>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::Method::Post)
@@ -473,9 +473,9 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun
fn get_url(
&self,
_req: &types::RefundsRouterData<api::RSync>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Ok(self.base_url(connectors))
+ Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
@@ -493,7 +493,7 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun
fn build_request(
&self,
req: &types::RefundsRouterData<api::RSync>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs
index 56d11ced206..28e32c6c86f 100644
--- a/crates/router/src/connector/braintree.rs
+++ b/crates/router/src/connector/braintree.rs
@@ -29,8 +29,8 @@ impl api::ConnectorCommon for Braintree {
"braintree"
}
- fn base_url(&self, connectors: settings::Connectors) -> String {
- connectors.braintree.base_url
+ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ connectors.braintree.base_url.as_ref()
}
fn get_auth_header(
@@ -85,7 +85,7 @@ impl
fn get_url(
&self,
req: &types::PaymentsSessionRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth_type = braintree::BraintreeAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
@@ -99,7 +99,7 @@ impl
fn build_request(
&self,
req: &types::PaymentsSessionRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = Some(
services::RequestBuilder::new()
@@ -213,7 +213,7 @@ impl
fn get_url(
&self,
req: &types::PaymentsSyncRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth_type = braintree::BraintreeAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
@@ -233,7 +233,7 @@ impl
fn build_request(
&self,
req: &types::PaymentsSyncRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
@@ -314,7 +314,7 @@ impl
fn get_url(
&self,
req: &types::PaymentsAuthorizeRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth_type = braintree::BraintreeAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
@@ -329,7 +329,7 @@ impl
fn build_request(
&self,
req: &types::PaymentsAuthorizeRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
@@ -421,7 +421,7 @@ impl
fn get_url(
&self,
req: &types::PaymentsCancelRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth_type = braintree::BraintreeAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
@@ -436,7 +436,7 @@ impl
fn build_request(
&self,
req: &types::PaymentsCancelRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
@@ -521,7 +521,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
fn get_url(
&self,
req: &types::RefundsRouterData<api::Execute>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth_type = braintree::BraintreeAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
@@ -547,7 +547,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
fn build_request(
&self,
req: &types::RefundsRouterData<api::Execute>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::Method::Post)
@@ -603,7 +603,7 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun
fn get_url(
&self,
_req: &types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>,
- _connectors: settings::Connectors,
+ _connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("braintree".to_string()).into())
}
@@ -625,7 +625,7 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun
fn build_request(
&self,
_req: &types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>,
- _connectors: settings::Connectors,
+ _connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(None)
}
diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs
index 6d9bc34471e..726a6c59c88 100644
--- a/crates/router/src/connector/checkout.rs
+++ b/crates/router/src/connector/checkout.rs
@@ -45,8 +45,8 @@ impl api::ConnectorCommon for Checkout {
Ok(vec![(headers::AUTHORIZATION.to_string(), auth.api_key)])
}
- fn base_url(&self, connectors: settings::Connectors) -> String {
- connectors.checkout.base_url
+ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ connectors.checkout.base_url.as_ref()
}
}
@@ -112,7 +112,7 @@ impl
fn get_url(
&self,
req: &types::PaymentsSyncRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}{}",
@@ -128,7 +128,7 @@ impl
fn build_request(
&self,
req: &types::PaymentsSyncRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
@@ -211,7 +211,7 @@ impl
fn get_url(
&self,
_req: &types::PaymentsAuthorizeRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "payments"))
}
@@ -231,7 +231,7 @@ impl
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
@@ -310,7 +310,7 @@ impl
fn get_url(
&self,
req: &types::PaymentsCancelRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}payments/{}/voids",
@@ -330,7 +330,7 @@ impl
fn build_request(
&self,
req: &types::PaymentsCancelRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
@@ -411,7 +411,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
fn get_url(
&self,
req: &types::RefundsRouterData<api::Execute>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = req.request.connector_transaction_id.clone();
Ok(format!(
@@ -433,7 +433,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
fn build_request(
&self,
req: &types::RefundsRouterData<api::Execute>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::Method::Post)
@@ -509,7 +509,7 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun
fn get_url(
&self,
req: &types::RefundsRouterData<api::RSync>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = req.request.connector_transaction_id.clone();
Ok(format!(
@@ -522,7 +522,7 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun
fn build_request(
&self,
req: &types::RefundsRouterData<api::RSync>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs
index 427cd63b5f8..a842835793e 100644
--- a/crates/router/src/connector/klarna.rs
+++ b/crates/router/src/connector/klarna.rs
@@ -30,8 +30,8 @@ impl api::ConnectorCommon for Klarna {
"application/x-www-form-urlencoded"
}
- fn base_url(&self, connectors: settings::Connectors) -> String {
- connectors.klarna.base_url
+ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ connectors.klarna.base_url.as_ref()
}
fn get_auth_header(
@@ -83,7 +83,7 @@ impl
fn get_url(
&self,
_req: &types::PaymentsSessionRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
@@ -106,7 +106,7 @@ impl
fn build_request(
&self,
req: &types::PaymentsSessionRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs
index 9ce3ca85d07..2d202bab108 100644
--- a/crates/router/src/connector/stripe.rs
+++ b/crates/router/src/connector/stripe.rs
@@ -35,9 +35,9 @@ impl api::ConnectorCommon for Stripe {
"application/x-www-form-urlencoded"
}
- fn base_url(&self, connectors: settings::Connectors) -> String {
+ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
// &self.base_url
- connectors.stripe.base_url
+ connectors.stripe.base_url.as_ref()
}
fn get_auth_header(
@@ -102,7 +102,7 @@ impl
&self,
req: &types::PaymentsCaptureRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = req.request.connector_transaction_id.as_str();
@@ -127,7 +127,7 @@ impl
&self,
req: &types::PaymentsCaptureRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
@@ -209,7 +209,7 @@ impl
fn get_url(
&self,
req: &types::PaymentsSyncRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = req.request.connector_transaction_id.clone();
Ok(format!(
@@ -224,7 +224,7 @@ impl
fn build_request(
&self,
req: &types::PaymentsSyncRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
@@ -310,7 +310,7 @@ impl
fn get_url(
&self,
_req: &types::PaymentsAuthorizeRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
@@ -331,7 +331,7 @@ impl
fn build_request(
&self,
req: &types::PaymentsAuthorizeRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
@@ -416,7 +416,7 @@ impl
fn get_url(
&self,
req: &types::PaymentsCancelRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let payment_id = &req.request.connector_transaction_id;
Ok(format!(
@@ -440,7 +440,7 @@ impl
fn build_request(
&self,
req: &types::PaymentsCancelRouterData,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::Method::Post)
@@ -529,7 +529,7 @@ impl
types::VerifyRequestData,
types::PaymentsResponseData,
>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
@@ -550,7 +550,7 @@ impl
fn build_request(
&self,
req: &types::RouterData<api::Verify, types::VerifyRequestData, types::PaymentsResponseData>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
@@ -644,7 +644,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
fn get_url(
&self,
_req: &types::RefundsRouterData<api::Execute>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "v1/refunds"))
}
@@ -661,7 +661,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
fn build_request(
&self,
req: &types::RefundsRouterData<api::Execute>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::Method::Post)
@@ -739,7 +739,7 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun
fn get_url(
&self,
req: &types::RefundsRouterData<api::RSync>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = req
.response
@@ -755,7 +755,7 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun
fn build_request(
&self,
req: &types::RefundsRouterData<api::RSync>,
- connectors: settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index d0f439069a8..c5bc263ef7b 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -65,7 +65,7 @@ pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationExt<T, Req, Re
fn get_url(
&self,
_req: &types::RouterData<T, Req, Resp>,
- _connectors: Connectors,
+ _connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(String::new())
}
@@ -80,7 +80,7 @@ pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationExt<T, Req, Re
fn build_request(
&self,
_req: &types::RouterData<T, Req, Resp>,
- _connectors: Connectors,
+ _connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(None)
}
@@ -155,7 +155,7 @@ where
Ok(router_data)
}
payments::CallConnectorAction::Trigger => {
- match connector_integration.build_request(req, state.conf.connectors.clone())? {
+ match connector_integration.build_request(req, &state.conf.connectors)? {
Some(request) => {
let response = call_connector_api(state, request).await;
match response {
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 5aeddbac5a8..e256cfe5411 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -41,9 +41,8 @@ pub trait ConnectorCommon {
// FIXME write doc - think about this
// fn headers(&self) -> Vec<(&str, &str)>;
- // TODO: Pass the connectors as borrow
/// The base URL for interacting with the connector's API.
- fn base_url(&self, connectors: Connectors) -> String;
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str;
}
pub trait Router {}
|
fix
|
send Connector as reference for base_url (#200)
|
d58f706dc3fdd5ea277eeef6de9c224fe6097b46
|
2024-10-25 18:29:25
|
Sandeep Kumar
|
fix(analytics): fix refund status filter on dashboard (#6431)
| false
|
diff --git a/crates/api_models/src/analytics/refunds.rs b/crates/api_models/src/analytics/refunds.rs
index 8acb51e764c..ef17387d1ea 100644
--- a/crates/api_models/src/analytics/refunds.rs
+++ b/crates/api_models/src/analytics/refunds.rs
@@ -5,7 +5,7 @@ use std::{
use common_utils::id_type;
-use crate::{enums::Currency, refunds::RefundStatus};
+use crate::enums::{Currency, RefundStatus};
#[derive(
Clone,
|
fix
|
fix refund status filter on dashboard (#6431)
|
ba013026a78dc525f259b11cc1263554ead87eb3
|
2023-04-17 23:59:54
|
SamraatBansal
|
fix: Update events table after notifying merchant (#871)
| false
|
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index c735856f46e..48397952d87 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -430,6 +430,8 @@ pub enum WebhooksFlowError {
DisputeCoreFailed,
#[error("Webhook event creation failed")]
WebhookEventCreationFailed,
+ #[error("Webhook event updation failed")]
+ WebhookEventUpdationFailed,
#[error("Unable to fork webhooks flow for outgoing webhooks")]
ForkFlowFailed,
#[error("Webhook api call to merchant failed")]
diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs
index 34c2a77704f..cd593dd30c1 100644
--- a/crates/router/src/core/webhooks.rs
+++ b/crates/router/src/core/webhooks.rs
@@ -416,7 +416,7 @@ async fn create_event_and_trigger_outgoing_webhook<W: api::OutgoingWebhookType>(
async fn trigger_webhook_to_merchant<W: api::OutgoingWebhookType>(
merchant_account: storage::MerchantAccount,
webhook: api::OutgoingWebhook,
- _db: Box<dyn StorageInterface>,
+ db: Box<dyn StorageInterface>,
) -> CustomResult<(), errors::WebhooksFlowError> {
let webhook_details_json = merchant_account
.webhook_details
@@ -434,6 +434,8 @@ async fn trigger_webhook_to_merchant<W: api::OutgoingWebhookType>(
.change_context(errors::WebhooksFlowError::MerchantWebhookURLNotConfigured)
.map(ExposeInterface::expose)?;
+ let outgoing_webhook_event_id = webhook.event_id.clone();
+
let transformed_outgoing_webhook = W::from(webhook);
let response = reqwest::Client::new()
@@ -454,7 +456,14 @@ async fn trigger_webhook_to_merchant<W: api::OutgoingWebhookType>(
.change_context(errors::WebhooksFlowError::CallToMerchantFailed)?;
}
Ok(res) => {
- if !res.status().is_success() {
+ if res.status().is_success() {
+ let update_event = storage::EventUpdate::UpdateWebhookNotified {
+ is_webhook_notified: Some(true),
+ };
+ db.update_event(outgoing_webhook_event_id, update_event)
+ .await
+ .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)?;
+ } else {
// [#217]: Schedule webhook for retry.
Err(errors::WebhooksFlowError::NotReceivedByMerchant).into_report()?;
}
diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs
index 6b512eb07e2..aed2f285bfb 100644
--- a/crates/router/src/db/events.rs
+++ b/crates/router/src/db/events.rs
@@ -13,6 +13,11 @@ pub trait EventInterface {
&self,
event: storage::EventNew,
) -> CustomResult<storage::Event, errors::StorageError>;
+ async fn update_event(
+ &self,
+ event_id: String,
+ event: storage::EventUpdate,
+ ) -> CustomResult<storage::Event, errors::StorageError>;
}
#[async_trait::async_trait]
@@ -24,6 +29,17 @@ impl EventInterface for Store {
let conn = connection::pg_connection_write(self).await?;
event.insert(&conn).await.map_err(Into::into).into_report()
}
+ async fn update_event(
+ &self,
+ event_id: String,
+ event: storage::EventUpdate,
+ ) -> CustomResult<storage::Event, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::Event::update(&conn, &event_id, event)
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
}
#[async_trait::async_trait]
@@ -35,4 +51,11 @@ impl EventInterface for MockDb {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
+ async fn update_event(
+ &self,
+ _event_id: String,
+ _event: storage::EventUpdate,
+ ) -> CustomResult<storage::Event, errors::StorageError> {
+ Err(errors::StorageError::MockDbError)?
+ }
}
diff --git a/crates/router/src/types/storage/events.rs b/crates/router/src/types/storage/events.rs
index c56791a8de6..b7469e5e786 100644
--- a/crates/router/src/types/storage/events.rs
+++ b/crates/router/src/types/storage/events.rs
@@ -1 +1 @@
-pub use storage_models::events::{Event, EventNew};
+pub use storage_models::events::{Event, EventNew, EventUpdate};
diff --git a/crates/storage_models/src/events.rs b/crates/storage_models/src/events.rs
index 6b1306bfa23..2f040fc00cc 100644
--- a/crates/storage_models/src/events.rs
+++ b/crates/storage_models/src/events.rs
@@ -1,5 +1,5 @@
use common_utils::custom_serde;
-use diesel::{Identifiable, Insertable, Queryable};
+use diesel::{AsChangeset, Identifiable, Insertable, Queryable};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -18,6 +18,17 @@ pub struct EventNew {
pub primary_object_type: storage_enums::EventObjectType,
}
+#[derive(Debug)]
+pub enum EventUpdate {
+ UpdateWebhookNotified { is_webhook_notified: Option<bool> },
+}
+
+#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
+#[diesel(table_name = events)]
+pub struct EventUpdateInternal {
+ pub is_webhook_notified: Option<bool>,
+}
+
#[derive(Clone, Debug, Deserialize, Serialize, Identifiable, Queryable)]
#[diesel(table_name = events)]
pub struct Event {
@@ -33,3 +44,15 @@ pub struct Event {
#[serde(with = "custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
}
+
+impl From<EventUpdate> for EventUpdateInternal {
+ fn from(event_update: EventUpdate) -> Self {
+ match event_update {
+ EventUpdate::UpdateWebhookNotified {
+ is_webhook_notified,
+ } => Self {
+ is_webhook_notified,
+ },
+ }
+ }
+}
diff --git a/crates/storage_models/src/query/events.rs b/crates/storage_models/src/query/events.rs
index 7606f65fb10..c8711abf9e4 100644
--- a/crates/storage_models/src/query/events.rs
+++ b/crates/storage_models/src/query/events.rs
@@ -1,8 +1,10 @@
+use diesel::{associations::HasTable, ExpressionMethods};
use router_env::{instrument, tracing};
use super::generics;
use crate::{
- events::{Event, EventNew},
+ events::{Event, EventNew, EventUpdate, EventUpdateInternal},
+ schema::events::dsl,
PgPooledConn, StorageResult,
};
@@ -12,3 +14,24 @@ impl EventNew {
generics::generic_insert(conn, self).await
}
}
+
+impl Event {
+ #[instrument(skip(conn))]
+ pub async fn update(
+ conn: &PgPooledConn,
+ event_id: &str,
+ event: EventUpdate,
+ ) -> StorageResult<Self> {
+ generics::generic_update_with_unique_predicate_get_result::<
+ <Self as HasTable>::Table,
+ _,
+ _,
+ _,
+ >(
+ conn,
+ dsl::event_id.eq(event_id.to_owned()),
+ EventUpdateInternal::from(event),
+ )
+ .await
+ }
+}
|
fix
|
Update events table after notifying merchant (#871)
|
d11d87408d0c4195bbe2c4c51df50f24c1d332c6
|
2024-12-12 20:50:33
|
Kashif
|
feat(core): payment links - add support for custom background image and layout in details section (#6725)
| false
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 6c3e9f5072a..0f62f111277 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -5537,6 +5537,11 @@
"description": "A list of allowed domains (glob patterns) where this link can be embedded / opened from",
"uniqueItems": true,
"nullable": true
+ },
+ "branding_visibility": {
+ "type": "boolean",
+ "description": "Toggle for HyperSwitch branding visibility",
+ "nullable": true
}
}
}
@@ -7882,6 +7887,61 @@
}
}
},
+ "ElementPosition": {
+ "type": "string",
+ "enum": [
+ "left",
+ "top left",
+ "top",
+ "top right",
+ "right",
+ "bottom right",
+ "bottom",
+ "bottom left",
+ "center"
+ ]
+ },
+ "ElementSize": {
+ "oneOf": [
+ {
+ "type": "object",
+ "required": [
+ "Variants"
+ ],
+ "properties": {
+ "Variants": {
+ "$ref": "#/components/schemas/SizeVariants"
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": [
+ "Percentage"
+ ],
+ "properties": {
+ "Percentage": {
+ "type": "integer",
+ "format": "int32",
+ "minimum": 0
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": [
+ "Pixels"
+ ],
+ "properties": {
+ "Pixels": {
+ "type": "integer",
+ "format": "int32",
+ "minimum": 0
+ }
+ }
+ }
+ ]
+ },
"EnablePaymentLinkRequest": {
"type": "string",
"description": "Whether payment link is requested to be enabled or not for this transaction",
@@ -12540,6 +12600,35 @@
}
}
},
+ "PaymentLinkBackgroundImageConfig": {
+ "type": "object",
+ "required": [
+ "url"
+ ],
+ "properties": {
+ "url": {
+ "type": "string",
+ "description": "URL of the image",
+ "example": "https://hyperswitch.io/favicon.ico"
+ },
+ "position": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ElementPosition"
+ }
+ ],
+ "nullable": true
+ },
+ "size": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ElementSize"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
"PaymentLinkConfig": {
"type": "object",
"required": [
@@ -12601,6 +12690,27 @@
},
"description": "Dynamic details related to merchant to be rendered in payment link",
"nullable": true
+ },
+ "background_image": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentLinkBackgroundImageConfig"
+ }
+ ],
+ "nullable": true
+ },
+ "details_layout": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentLinkDetailsLayout"
+ }
+ ],
+ "nullable": true
+ },
+ "branding_visibility": {
+ "type": "boolean",
+ "description": "Toggle for HyperSwitch branding visibility",
+ "nullable": true
}
}
},
@@ -12670,9 +12780,32 @@
},
"description": "Dynamic details related to merchant to be rendered in payment link",
"nullable": true
+ },
+ "background_image": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentLinkBackgroundImageConfig"
+ }
+ ],
+ "nullable": true
+ },
+ "details_layout": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentLinkDetailsLayout"
+ }
+ ],
+ "nullable": true
}
}
},
+ "PaymentLinkDetailsLayout": {
+ "type": "string",
+ "enum": [
+ "layout1",
+ "layout2"
+ ]
+ },
"PaymentLinkInitiateRequest": {
"type": "object",
"required": [
@@ -20016,6 +20149,13 @@
}
]
},
+ "SizeVariants": {
+ "type": "string",
+ "enum": [
+ "cover",
+ "contain"
+ ]
+ },
"StraightThroughAlgorithm": {
"oneOf": [
{
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json
index ce383f24064..8b06e167e21 100644
--- a/api-reference/openapi_spec.json
+++ b/api-reference/openapi_spec.json
@@ -7974,6 +7974,11 @@
"description": "A list of allowed domains (glob patterns) where this link can be embedded / opened from",
"uniqueItems": true,
"nullable": true
+ },
+ "branding_visibility": {
+ "type": "boolean",
+ "description": "Toggle for HyperSwitch branding visibility",
+ "nullable": true
}
}
}
@@ -10268,6 +10273,61 @@
"none"
]
},
+ "ElementPosition": {
+ "type": "string",
+ "enum": [
+ "left",
+ "top left",
+ "top",
+ "top right",
+ "right",
+ "bottom right",
+ "bottom",
+ "bottom left",
+ "center"
+ ]
+ },
+ "ElementSize": {
+ "oneOf": [
+ {
+ "type": "object",
+ "required": [
+ "Variants"
+ ],
+ "properties": {
+ "Variants": {
+ "$ref": "#/components/schemas/SizeVariants"
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": [
+ "Percentage"
+ ],
+ "properties": {
+ "Percentage": {
+ "type": "integer",
+ "format": "int32",
+ "minimum": 0
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": [
+ "Pixels"
+ ],
+ "properties": {
+ "Pixels": {
+ "type": "integer",
+ "format": "int32",
+ "minimum": 0
+ }
+ }
+ }
+ ]
+ },
"EnabledPaymentMethod": {
"type": "object",
"description": "Object for EnabledPaymentMethod",
@@ -15255,6 +15315,35 @@
}
}
},
+ "PaymentLinkBackgroundImageConfig": {
+ "type": "object",
+ "required": [
+ "url"
+ ],
+ "properties": {
+ "url": {
+ "type": "string",
+ "description": "URL of the image",
+ "example": "https://hyperswitch.io/favicon.ico"
+ },
+ "position": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ElementPosition"
+ }
+ ],
+ "nullable": true
+ },
+ "size": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ElementSize"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
"PaymentLinkConfig": {
"type": "object",
"required": [
@@ -15316,6 +15405,27 @@
},
"description": "Dynamic details related to merchant to be rendered in payment link",
"nullable": true
+ },
+ "background_image": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentLinkBackgroundImageConfig"
+ }
+ ],
+ "nullable": true
+ },
+ "details_layout": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentLinkDetailsLayout"
+ }
+ ],
+ "nullable": true
+ },
+ "branding_visibility": {
+ "type": "boolean",
+ "description": "Toggle for HyperSwitch branding visibility",
+ "nullable": true
}
}
},
@@ -15385,9 +15495,32 @@
},
"description": "Dynamic details related to merchant to be rendered in payment link",
"nullable": true
+ },
+ "background_image": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentLinkBackgroundImageConfig"
+ }
+ ],
+ "nullable": true
+ },
+ "details_layout": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentLinkDetailsLayout"
+ }
+ ],
+ "nullable": true
}
}
},
+ "PaymentLinkDetailsLayout": {
+ "type": "string",
+ "enum": [
+ "layout1",
+ "layout2"
+ ]
+ },
"PaymentLinkInitiateRequest": {
"type": "object",
"required": [
@@ -23934,6 +24067,13 @@
}
]
},
+ "SizeVariants": {
+ "type": "string",
+ "enum": [
+ "cover",
+ "contain"
+ ]
+ },
"StraightThroughAlgorithm": {
"oneOf": [
{
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 82f9b65b27a..d4432b7021b 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -179,7 +179,7 @@ card.credit = { connector_list = "cybersource" } # Update Mandate sup
card.debit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card
[network_transaction_id_supported_connectors]
-connector_list = "stripe,adyen,cybersource"
+connector_list = "adyen"
[payouts]
payout_eligibility = true # Defaults the eligibility of a payout method to true in case connector does not provide checks for payout eligibility
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 769ef592803..226d3974053 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -2667,6 +2667,8 @@ pub struct BusinessPaymentLinkConfig {
/// A list of allowed domains (glob patterns) where this link can be embedded / opened from
#[schema(value_type = Option<HashSet<String>>)]
pub allowed_domains: Option<HashSet<String>>,
+ /// Toggle for HyperSwitch branding visibility
+ pub branding_visibility: Option<bool>,
}
impl BusinessPaymentLinkConfig {
@@ -2725,6 +2727,11 @@ pub struct PaymentLinkConfigRequest {
pub show_card_form_by_default: Option<bool>,
/// Dynamic details related to merchant to be rendered in payment link
pub transaction_details: Option<Vec<PaymentLinkTransactionDetails>>,
+ /// Configurations for the background image for details section
+ pub background_image: Option<PaymentLinkBackgroundImageConfig>,
+ /// Custom layout for details section
+ #[schema(value_type = Option<PaymentLinkDetailsLayout>, example = "layout1")]
+ pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)]
@@ -2752,6 +2759,19 @@ pub struct TransactionDetailsUiConfiguration {
pub is_value_bold: Option<bool>,
}
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)]
+pub struct PaymentLinkBackgroundImageConfig {
+ /// URL of the image
+ #[schema(value_type = String, example = "https://hyperswitch.io/favicon.ico")]
+ pub url: common_utils::types::Url,
+ /// Position of the image in the UI
+ #[schema(value_type = Option<ElementPosition>, example = "top-left")]
+ pub position: Option<api_enums::ElementPosition>,
+ /// Size of the image in the UI
+ #[schema(value_type = Option<ElementSize>, example = "contain")]
+ pub size: Option<api_enums::ElementSize>,
+}
+
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, ToSchema)]
pub struct PaymentLinkConfig {
/// custom theme for the payment link
@@ -2774,6 +2794,13 @@ pub struct PaymentLinkConfig {
pub allowed_domains: Option<HashSet<String>>,
/// Dynamic details related to merchant to be rendered in payment link
pub transaction_details: Option<Vec<PaymentLinkTransactionDetails>>,
+ /// Configurations for the background image for details section
+ pub background_image: Option<PaymentLinkBackgroundImageConfig>,
+ /// Custom layout for details section
+ #[schema(value_type = Option<PaymentLinkDetailsLayout>, example = "layout1")]
+ pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>,
+ /// Toggle for HyperSwitch branding visibility
+ pub branding_visibility: Option<bool>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 2114bc9f6ca..83246d944a3 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -6856,6 +6856,9 @@ pub struct PaymentLinkDetails {
pub show_card_form_by_default: bool,
pub locale: Option<String>,
pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>,
+ pub background_image: Option<admin::PaymentLinkBackgroundImageConfig>,
+ pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>,
+ pub branding_visibility: Option<bool>,
}
#[derive(Debug, serde::Serialize, Clone)]
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 88c3b684678..2a74983f251 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -1,8 +1,10 @@
mod payments;
+mod ui;
use std::num::{ParseFloatError, TryFromIntError};
pub use payments::ProductType;
use serde::{Deserialize, Serialize};
+pub use ui::*;
use utoipa::ToSchema;
pub use super::connector_enums::RoutableConnectors;
diff --git a/crates/common_enums/src/enums/ui.rs b/crates/common_enums/src/enums/ui.rs
new file mode 100644
index 00000000000..aec6c7ed64a
--- /dev/null
+++ b/crates/common_enums/src/enums/ui.rs
@@ -0,0 +1,149 @@
+use std::fmt;
+
+use serde::{de::Visitor, Deserialize, Deserializer, Serialize};
+use utoipa::ToSchema;
+
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Default,
+ Eq,
+ Hash,
+ PartialEq,
+ Serialize,
+ Deserialize,
+ strum::Display,
+ strum::EnumString,
+ ToSchema,
+)]
+#[router_derive::diesel_enum(storage_type = "db_enum")]
+#[serde(rename_all = "lowercase")]
+pub enum ElementPosition {
+ Left,
+ #[default]
+ #[serde(rename = "top left")]
+ TopLeft,
+ Top,
+ #[serde(rename = "top right")]
+ TopRight,
+ Right,
+ #[serde(rename = "bottom right")]
+ BottomRight,
+ Bottom,
+ #[serde(rename = "bottom left")]
+ BottomLeft,
+ Center,
+}
+
+#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, strum::Display, strum::EnumString, ToSchema)]
+#[router_derive::diesel_enum(storage_type = "db_enum")]
+pub enum ElementSize {
+ Variants(SizeVariants),
+ Percentage(u32),
+ Pixels(u32),
+}
+
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Default,
+ Eq,
+ Hash,
+ PartialEq,
+ Serialize,
+ Deserialize,
+ strum::Display,
+ strum::EnumString,
+ ToSchema,
+)]
+#[router_derive::diesel_enum(storage_type = "db_enum")]
+#[serde(rename_all = "lowercase")]
+#[strum(serialize_all = "lowercase")]
+pub enum SizeVariants {
+ #[default]
+ Cover,
+ Contain,
+}
+
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Default,
+ Eq,
+ Hash,
+ PartialEq,
+ Serialize,
+ Deserialize,
+ strum::Display,
+ strum::EnumString,
+ ToSchema,
+)]
+#[router_derive::diesel_enum(storage_type = "db_enum")]
+#[serde(rename_all = "lowercase")]
+#[strum(serialize_all = "lowercase")]
+pub enum PaymentLinkDetailsLayout {
+ #[default]
+ Layout1,
+ Layout2,
+}
+
+impl<'de> Deserialize<'de> for ElementSize {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ struct ElementSizeVisitor;
+
+ impl Visitor<'_> for ElementSizeVisitor {
+ type Value = ElementSize;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter.write_str("a string with possible values - contain, cover or values in percentage or pixels. For eg: 48px or 50%")
+ }
+
+ fn visit_str<E>(self, value: &str) -> Result<ElementSize, E>
+ where
+ E: serde::de::Error,
+ {
+ if let Some(percent) = value.strip_suffix('%') {
+ percent
+ .parse::<u32>()
+ .map(ElementSize::Percentage)
+ .map_err(E::custom)
+ } else if let Some(px) = value.strip_suffix("px") {
+ px.parse::<u32>()
+ .map(ElementSize::Pixels)
+ .map_err(E::custom)
+ } else {
+ match value {
+ "cover" => Ok(ElementSize::Variants(SizeVariants::Cover)),
+ "contain" => Ok(ElementSize::Variants(SizeVariants::Contain)),
+ _ => Err(E::custom("invalid size variant")),
+ }
+ }
+ }
+ }
+
+ deserializer.deserialize_str(ElementSizeVisitor)
+ }
+}
+
+impl Serialize for ElementSize {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: serde::ser::Serializer,
+ {
+ match self {
+ Self::Variants(variant) => serializer.serialize_str(variant.to_string().as_str()),
+ Self::Pixels(pixel_count) => {
+ serializer.serialize_str(format!("{}px", pixel_count).as_str())
+ }
+ Self::Percentage(pixel_count) => {
+ serializer.serialize_str(format!("{}%", pixel_count).as_str())
+ }
+ }
+ }
+}
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index 0cae67873d6..bafd1897200 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -556,6 +556,7 @@ pub struct BusinessPaymentLinkConfig {
pub default_config: Option<PaymentLinkConfigRequest>,
pub business_specific_configs: Option<HashMap<String, PaymentLinkConfigRequest>>,
pub allowed_domains: Option<HashSet<String>>,
+ pub branding_visibility: Option<bool>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
@@ -568,6 +569,15 @@ pub struct PaymentLinkConfigRequest {
pub enabled_saved_payment_method: Option<bool>,
pub hide_card_nickname_field: Option<bool>,
pub show_card_form_by_default: Option<bool>,
+ pub background_image: Option<PaymentLinkBackgroundImageConfig>,
+ pub details_layout: Option<common_enums::PaymentLinkDetailsLayout>,
+}
+
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)]
+pub struct PaymentLinkBackgroundImageConfig {
+ pub url: common_utils::types::Url,
+ pub position: Option<common_enums::ElementPosition>,
+ pub size: Option<common_enums::ElementSize>,
}
common_utils::impl_to_sql_from_sql_json!(BusinessPaymentLinkConfig);
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index b29da50d0a7..8d037c5356f 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -4,13 +4,13 @@ use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
-use crate::enums as storage_enums;
#[cfg(feature = "v1")]
use crate::schema::payment_intent;
#[cfg(feature = "v2")]
use crate::schema_v2::payment_intent;
#[cfg(feature = "v2")]
use crate::types::{FeatureMetadata, OrderDetailsWithAmount};
+use crate::{business_profile::PaymentLinkBackgroundImageConfig, enums as storage_enums};
#[cfg(feature = "v2")]
#[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable)]
@@ -161,6 +161,10 @@ pub struct PaymentLinkConfigRequestForPayments {
pub show_card_form_by_default: Option<bool>,
/// Dynamic details related to merchant to be rendered in payment link
pub transaction_details: Option<Vec<PaymentLinkTransactionDetails>>,
+ /// Configurations for the background image for details section
+ pub background_image: Option<PaymentLinkBackgroundImageConfig>,
+ /// Custom layout for details section
+ pub details_layout: Option<common_enums::PaymentLinkDetailsLayout>,
}
common_utils::impl_to_sql_from_sql_json!(PaymentLinkConfigRequestForPayments);
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index 31732e13286..0e8722644bd 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -193,6 +193,7 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest>
enabled_saved_payment_method: item.enabled_saved_payment_method,
hide_card_nickname_field: item.hide_card_nickname_field,
show_card_form_by_default: item.show_card_form_by_default,
+ details_layout: item.details_layout,
transaction_details: item.transaction_details.map(|transaction_details| {
transaction_details
.into_iter()
@@ -203,6 +204,11 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest>
})
.collect()
}),
+ background_image: item.background_image.map(|background_image| {
+ diesel_models::business_profile::PaymentLinkBackgroundImageConfig::convert_from(
+ background_image,
+ )
+ }),
}
}
fn convert_back(self) -> api_models::admin::PaymentLinkConfigRequest {
@@ -216,6 +222,8 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest>
hide_card_nickname_field,
show_card_form_by_default,
transaction_details,
+ background_image,
+ details_layout,
} = self;
api_models::admin::PaymentLinkConfigRequest {
theme,
@@ -226,12 +234,15 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest>
enabled_saved_payment_method,
hide_card_nickname_field,
show_card_form_by_default,
+ details_layout,
transaction_details: transaction_details.map(|transaction_details| {
transaction_details
.into_iter()
.map(|transaction_detail| transaction_detail.convert_back())
.collect()
}),
+ background_image: background_image
+ .map(|background_image| background_image.convert_back()),
}
}
}
@@ -264,6 +275,31 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkTransactionDet
}
}
+#[cfg(feature = "v2")]
+impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkBackgroundImageConfig>
+ for diesel_models::business_profile::PaymentLinkBackgroundImageConfig
+{
+ fn convert_from(from: api_models::admin::PaymentLinkBackgroundImageConfig) -> Self {
+ Self {
+ url: from.url,
+ position: from.position,
+ size: from.size,
+ }
+ }
+ fn convert_back(self) -> api_models::admin::PaymentLinkBackgroundImageConfig {
+ let Self {
+ url,
+ position,
+ size,
+ } = self;
+ api_models::admin::PaymentLinkBackgroundImageConfig {
+ url,
+ position,
+ size,
+ }
+ }
+}
+
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<api_models::admin::TransactionDetailsUiConfiguration>
for diesel_models::TransactionDetailsUiConfiguration
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index d50bf863b5b..68b0893bcc0 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -286,6 +286,10 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::enums::ReconStatus,
api_models::enums::ConnectorStatus,
api_models::enums::AuthorizationStatus,
+ api_models::enums::ElementPosition,
+ api_models::enums::ElementSize,
+ api_models::enums::SizeVariants,
+ api_models::enums::PaymentLinkDetailsLayout,
api_models::enums::PaymentMethodStatus,
api_models::enums::UIWidgetFormLayout,
api_models::admin::MerchantConnectorCreate,
@@ -305,6 +309,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::admin::ProfileCreate,
api_models::admin::ProfileResponse,
api_models::admin::BusinessPaymentLinkConfig,
+ api_models::admin::PaymentLinkBackgroundImageConfig,
api_models::admin::PaymentLinkConfigRequest,
api_models::admin::PaymentLinkConfig,
api_models::admin::PaymentLinkTransactionDetails,
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 688d749d5d9..e3c9ef0b015 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -247,6 +247,10 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::enums::ReconStatus,
api_models::enums::ConnectorStatus,
api_models::enums::AuthorizationStatus,
+ api_models::enums::ElementPosition,
+ api_models::enums::ElementSize,
+ api_models::enums::SizeVariants,
+ api_models::enums::PaymentLinkDetailsLayout,
api_models::enums::PaymentMethodStatus,
api_models::enums::OrderFulfillmentTimeOrigin,
api_models::enums::UIWidgetFormLayout,
@@ -267,6 +271,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::admin::ProfileCreate,
api_models::admin::ProfileResponse,
api_models::admin::BusinessPaymentLinkConfig,
+ api_models::admin::PaymentLinkBackgroundImageConfig,
api_models::admin::PaymentLinkConfigRequest,
api_models::admin::PaymentLinkConfig,
api_models::admin::PaymentLinkTransactionDetails,
diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs
index bc66461e819..f9522b04d95 100644
--- a/crates/router/src/core/payment_link.rs
+++ b/crates/router/src/core/payment_link.rs
@@ -35,7 +35,7 @@ use crate::{
api::payment_link::PaymentLinkResponseExt,
domain,
storage::{enums as storage_enums, payment_link::PaymentLink},
- transformers::ForeignFrom,
+ transformers::{ForeignFrom, ForeignInto},
},
};
@@ -129,6 +129,9 @@ pub async fn form_payment_link_data(
show_card_form_by_default: DEFAULT_SHOW_CARD_FORM,
allowed_domains: DEFAULT_ALLOWED_DOMAINS,
transaction_details: None,
+ background_image: None,
+ details_layout: None,
+ branding_visibility: None,
}
};
@@ -271,6 +274,9 @@ pub async fn form_payment_link_data(
show_card_form_by_default: payment_link_config.show_card_form_by_default,
locale,
transaction_details: payment_link_config.transaction_details.clone(),
+ background_image: payment_link_config.background_image.clone(),
+ details_layout: payment_link_config.details_layout,
+ branding_visibility: payment_link_config.branding_visibility,
};
Ok((
@@ -586,18 +592,16 @@ pub fn get_payment_link_config_based_on_priority(
default_domain_name: String,
payment_link_config_id: Option<String>,
) -> Result<(PaymentLinkConfig, String), error_stack::Report<errors::ApiErrorResponse>> {
- let (domain_name, business_theme_configs, allowed_domains) =
+ let (domain_name, business_theme_configs, allowed_domains, branding_visibility) =
if let Some(business_config) = business_link_config {
- logger::info!(
- "domain name set to custom domain https://{:?}",
- business_config.domain_name
- );
-
(
business_config
.domain_name
.clone()
- .map(|d_name| format!("https://{}", d_name))
+ .map(|d_name| {
+ logger::info!("domain name set to custom domain https://{:?}", d_name);
+ format!("https://{}", d_name)
+ })
.unwrap_or_else(|| default_domain_name.clone()),
payment_link_config_id
.and_then(|id| {
@@ -608,9 +612,10 @@ pub fn get_payment_link_config_based_on_priority(
})
.or(business_config.default_config),
business_config.allowed_domains,
+ business_config.branding_visibility,
)
} else {
- (default_domain_name, None, None)
+ (default_domain_name, None, None, None)
};
let (
@@ -637,19 +642,45 @@ pub fn get_payment_link_config_based_on_priority(
(hide_card_nickname_field, DEFAULT_HIDE_CARD_NICKNAME_FIELD),
(show_card_form_by_default, DEFAULT_SHOW_CARD_FORM)
);
- let payment_link_config = PaymentLinkConfig {
- theme,
- logo,
- seller_name,
- sdk_layout,
- display_sdk_only,
- enabled_saved_payment_method,
- hide_card_nickname_field,
- show_card_form_by_default,
- allowed_domains,
- transaction_details: payment_create_link_config
- .and_then(|payment_link_config| payment_link_config.theme_config.transaction_details),
- };
+ let payment_link_config =
+ PaymentLinkConfig {
+ theme,
+ logo,
+ seller_name,
+ sdk_layout,
+ display_sdk_only,
+ enabled_saved_payment_method,
+ hide_card_nickname_field,
+ show_card_form_by_default,
+ allowed_domains,
+ branding_visibility,
+ transaction_details: payment_create_link_config.as_ref().and_then(
+ |payment_link_config| payment_link_config.theme_config.transaction_details.clone(),
+ ),
+ details_layout: payment_create_link_config
+ .as_ref()
+ .and_then(|payment_link_config| payment_link_config.theme_config.details_layout)
+ .or_else(|| {
+ business_theme_configs
+ .as_ref()
+ .and_then(|business_theme_config| business_theme_config.details_layout)
+ }),
+ background_image: payment_create_link_config
+ .as_ref()
+ .and_then(|payment_link_config| {
+ payment_link_config.theme_config.background_image.clone()
+ })
+ .or_else(|| {
+ business_theme_configs
+ .as_ref()
+ .and_then(|business_theme_config| {
+ business_theme_config
+ .background_image
+ .as_ref()
+ .map(|background_image| background_image.clone().foreign_into())
+ })
+ }),
+ };
Ok((payment_link_config, domain_name))
}
@@ -752,6 +783,9 @@ pub async fn get_payment_link_status(
show_card_form_by_default: DEFAULT_SHOW_CARD_FORM,
allowed_domains: DEFAULT_ALLOWED_DOMAINS,
transaction_details: None,
+ background_image: None,
+ details_layout: None,
+ branding_visibility: None,
}
};
diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.css b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.css
index 65a50e967f3..b8ccdeba33a 100644
--- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.css
+++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.css
@@ -71,6 +71,7 @@ body {
#hyper-checkout-details {
font-family: "Montserrat";
+ background-repeat: no-repeat;
}
.hyper-checkout-payment {
@@ -144,7 +145,7 @@ body {
#hyper-checkout-merchant-image,
#hyper-checkout-cart-image {
height: 64px;
- width: 64px;
+ padding: 0 10px;
border-radius: 4px;
display: flex;
align-self: flex-start;
@@ -153,8 +154,7 @@ body {
}
#hyper-checkout-merchant-image > img {
- height: 48px;
- width: 48px;
+ height: 40px;
}
#hyper-checkout-cart-image {
@@ -279,7 +279,7 @@ body {
#hyper-checkout-merchant-description {
font-size: 13px;
- color: #808080;
+ margin: 10px 0 20px 0;
}
.powered-by-hyper {
@@ -292,7 +292,6 @@ body {
min-width: 584px;
z-index: 2;
background-color: var(--primary-color);
- box-shadow: 0px 1px 10px #f2f2f2;
display: flex;
flex-flow: column;
align-items: center;
@@ -665,6 +664,12 @@ body {
animation: loading 1s linear infinite;
}
+@media only screen and (min-width: 1199px) {
+ #hyper-checkout-merchant-description {
+ color: #808080;
+ }
+}
+
@media only screen and (max-width: 1199px) {
body {
overflow-y: scroll;
diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html
index 963b4d6083a..9abcc440068 100644
--- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html
+++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html
@@ -185,7 +185,7 @@
<div></div>
</div>
</div>
- <div class="hyper-checkout hide-scrollbar">
+ <div id="hyper-checkout" class="hyper-checkout hide-scrollbar">
<div class="main hidden" id="hyper-checkout-status-canvas">
<div class="hyper-checkout-status-wrap">
<div id="hyper-checkout-status-header"></div>
@@ -270,18 +270,6 @@
</svg>
</div>
<div id="hyper-checkout-cart-items" class="hide-scrollbar"></div>
- <div id="hyper-checkout-merchant-description"></div>
- <div class="powered-by-hyper">
- <svg class="fill-current" height="18" width="130">
- <use
- xlink:href="#hyperswitch-brand"
- x="0"
- y="0"
- height="18"
- width="130"
- ></use>
- </svg>
- </div>
</div>
</div>
<div class="hyper-checkout-sdk" id="hyper-checkout-sdk">
@@ -313,17 +301,6 @@
</div>
</div>
</div>
- <div id="hyper-footer" class="hidden">
- <svg class="fill-current" height="18" width="130">
- <use
- xlink:href="#hyperswitch-brand"
- x="0"
- y="0"
- height="18"
- width="130"
- ></use>
- </svg>
- </div>
<script>
{{logging_template}}
{{locale_template}}
diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js
index 60cfad22eed..4bcdeed434f 100644
--- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js
+++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js
@@ -139,8 +139,8 @@ function invertToBW(color, bw, asArr) {
? hexToRgbArray(options.black)
: options.black
: asArr
- ? hexToRgbArray(options.white)
- : options.white;
+ ? hexToRgbArray(options.white)
+ : options.white;
}
function invert(color, bw) {
if (bw === void 0) {
@@ -204,7 +204,7 @@ function boot() {
}
else {
var orderDetails = paymentDetails.order_details;
- if (orderDetails!==null) {
+ if (orderDetails !== null) {
var charges = 0;
for (var i = 0; i < orderDetails.length; i++) {
@@ -213,8 +213,8 @@ function boot() {
orderDetails.push({
"amount": (paymentDetails.amount - charges).toFixed(2),
"product_img_link": "https://live.hyperswitch.io/payment-link-assets/cart_placeholder.png",
- "product_name": translations.miscellaneousCharges+"\n" +
- translations.miscellaneousChargesDetail,
+ "product_name": translations.miscellaneousCharges + "\n" +
+ translations.miscellaneousChargesDetail,
"quantity": null
});
}
@@ -233,13 +233,17 @@ function boot() {
}
// Render UI
- if (paymentDetails.display_sdk_only){
+ if (paymentDetails.display_sdk_only) {
renderSDKHeader(paymentDetails);
+ renderBranding(paymentDetails);
}
- else{
+ else {
+ renderBackgroundImage(paymentDetails);
renderPaymentDetails(paymentDetails);
renderDynamicMerchantDetails(paymentDetails);
renderCart(paymentDetails);
+ renderDescription(paymentDetails);
+ renderBranding(paymentDetails);
renderSDKHeader(paymentDetails);
}
@@ -295,12 +299,12 @@ function initializeEventListeners(paymentDetails) {
submitButtonLoaderNode.style.borderBottomColor = contrastingTone;
}
- // Get locale for pay now
- var payNowButtonText = document.createElement("div");
- var payNowButtonText = document.getElementById('submit-button-text');
- if (payNowButtonText) {
- payNowButtonText.textContent = translations.payNow;
- }
+ // Get locale for pay now
+ var payNowButtonText = document.createElement("div");
+ var payNowButtonText = document.getElementById('submit-button-text');
+ if (payNowButtonText) {
+ payNowButtonText.textContent = translations.payNow;
+ }
if (submitButtonNode instanceof HTMLButtonElement) {
submitButtonNode.style.color = contrastBWColor;
@@ -473,12 +477,16 @@ function addText(id, msg) {
function addClass(id, className) {
var element = document.querySelector(id);
- element.classList.add(className);
+ if (element instanceof HTMLElement) {
+ element.classList.add(className);
+ }
}
function removeClass(id, className) {
var element = document.querySelector(id);
- element.classList.remove(className);
+ if (element instanceof HTMLElement) {
+ element.classList.remove(className);
+ }
}
/**
@@ -570,7 +578,6 @@ function renderPaymentDetails(paymentDetails) {
// Create merchant logo's node
var merchantLogoNode = document.createElement("img");
merchantLogoNode.src = paymentDetails.merchant_logo;
- merchantLogoNode.setAttribute("width", "48"); // Set width to 100 pixels
merchantLogoNode.setAttribute("height", "48");
// Create expiry node
@@ -685,6 +692,113 @@ function appendMerchantDetails(paymentDetails, merchantDynamicDetails) {
}
}
+/**
+ * Uses
+ * - Creates and appends description below the cart section (LAYOUT 1 / DEFAULT LAYOUT specification)
+ * @param {String} merchantDescription
+ */
+function renderDefaultLayout(merchantDescription) {
+ var cartItemNode = document.getElementById("hyper-checkout-cart");
+ if (cartItemNode instanceof HTMLDivElement) {
+ var merchantDescriptionNode = document.createElement("div");
+ merchantDescriptionNode.id = "hyper-checkout-merchant-description";
+ merchantDescriptionNode.innerText = merchantDescription;
+ cartItemNode.appendChild(merchantDescriptionNode);
+ show("#hyper-checkout-merchant-description");
+ }
+}
+
+/**
+ * Uses
+ * - Renders description in the appropriate section based on the specified layout
+ * @param {PaymentDetails} paymentDetails
+ */
+function renderDescription(paymentDetails) {
+ var detailsLayout = paymentDetails.details_layout;
+ if (typeof paymentDetails.merchant_description === "string" && paymentDetails.merchant_description.length > 0) {
+ switch (detailsLayout) {
+ case "layout1": {
+ renderDefaultLayout(paymentDetails.merchant_description);
+ break;
+ }
+ case "layout2": {
+ var paymentContextNode = document.getElementById("hyper-checkout-payment-context");
+ if (paymentContextNode instanceof HTMLDivElement) {
+ var merchantDescriptionNode = document.createElement("div");
+ merchantDescriptionNode.id = "hyper-checkout-merchant-description";
+ merchantDescriptionNode.innerText = paymentDetails.merchant_description;
+ var merchantDetailsNode = document.getElementById("hyper-checkout-payment-merchant-details");
+ if (merchantDetailsNode instanceof HTMLDivElement) {
+ paymentContextNode.insertBefore(merchantDescriptionNode, merchantDetailsNode);
+ show("#hyper-checkout-merchant-description");
+ }
+ }
+ break;
+ }
+ default: {
+ renderDefaultLayout(paymentDetails.merchant_description);
+ }
+ }
+ }
+}
+
+/**
+ * Uses
+ * - Creates and returns a div element with the HyperSwitch branding SVG
+ * @param {String} wrapperId
+ * @returns {HTMLDivElement} brandingWrapperNode
+ */
+function createHyperSwitchBrandingSVGElement(wrapperId) {
+ var brandingWrapperNode = document.createElement("div");
+ brandingWrapperNode.id = wrapperId;
+ brandingWrapperNode.innerHTML = '<svg class="fill-current" height="18" width="130"><use xlink:href="#hyperswitch-brand" x="0" y="0" height="18" width="130"></use></svg>';
+ return brandingWrapperNode;
+}
+
+/**
+ * Uses
+ * - Creates and appends HyperSwitch branding in appropriate sections based on the viewport dimensions (web vs mobile views)
+ * @param {PaymentDetails} paymentDetails
+ */
+function renderBranding(paymentDetails) {
+ if (paymentDetails.branding_visibility !== false) {
+ // Append below cart section for web views
+ var cartItemNode = document.getElementById("hyper-checkout-cart");
+ if (cartItemNode instanceof HTMLDivElement) {
+ var brandingWrapper = createHyperSwitchBrandingSVGElement("powered-by-hyper");
+ cartItemNode.appendChild(brandingWrapper);
+ }
+
+ // Append in document's body for mobile views
+ var mobileBrandingWrapper = createHyperSwitchBrandingSVGElement("hyper-footer");
+ document.body.appendChild(mobileBrandingWrapper);
+ if (!window.state.isMobileView) {
+ hide("#hyper-footer");
+ }
+ }
+}
+
+/**
+ * Uses
+ * - Renders background image in the payment details section
+ * @param {PaymentDetails} paymentDetails
+ */
+function renderBackgroundImage(paymentDetails) {
+ var backgroundImage = paymentDetails.background_image;
+ if (typeof backgroundImage === "object" && backgroundImage !== null) {
+ var paymentDetailsNode = document.getElementById("hyper-checkout-details");
+ if (paymentDetailsNode instanceof HTMLDivElement) {
+ paymentDetailsNode.style.backgroundImage = "url(" + backgroundImage.url + ")";
+ if (typeof backgroundImage.size === "string") {
+ paymentDetailsNode.style.backgroundSize = backgroundImage.size;
+ }
+ if (typeof backgroundImage.position === "string") {
+ paymentDetailsNode.style.backgroundPosition = backgroundImage.position;
+ }
+ }
+ }
+}
+
/**
* Trigger - on boot
* Uses
@@ -737,7 +851,7 @@ function renderCart(paymentDetails) {
buttonTextNode.id = "hyper-checkout-cart-button-text";
var hiddenItemsCount =
orderDetails.length - MAX_ITEMS_VISIBLE_AFTER_COLLAPSE;
- buttonTextNode.innerText = translations.showMore+" (" + hiddenItemsCount + ")";
+ buttonTextNode.innerText = translations.showMore + " (" + hiddenItemsCount + ")";
expandButtonNode.append(buttonTextNode, buttonImageNode);
if (cartNode instanceof HTMLDivElement) {
cartNode.insertBefore(expandButtonNode, cartNode.lastElementChild);
@@ -747,18 +861,6 @@ function renderCart(paymentDetails) {
hide("#hyper-checkout-cart-header");
hide("#hyper-checkout-cart-items");
hide("#hyper-checkout-cart-image");
- if (
- typeof paymentDetails.merchant_description === "string" &&
- paymentDetails.merchant_description.length > 0
- ) {
- var merchantDescriptionNode = document.getElementById(
- "hyper-checkout-merchant-description"
- );
- if (merchantDescriptionNode instanceof HTMLDivElement) {
- merchantDescriptionNode.innerText = paymentDetails.merchant_description;
- }
- show("#hyper-checkout-merchant-description");
- }
}
}
@@ -801,8 +903,8 @@ function renderCartItem(
if (item.quantity !== null) {
var quantityNode = document.createElement("div");
quantityNode.className = "hyper-checkout-card-item-quantity";
- quantityNode.innerText = translations.quantity+": " + item.quantity;
- }
+ quantityNode.innerText = translations.quantity + ": " + item.quantity;
+ }
// Product price
var priceNode = document.createElement("div");
priceNode.className = "hyper-checkout-card-item-price";
@@ -869,9 +971,9 @@ function handleCartView(paymentDetails) {
);
});
}
- if (cartItemsNode instanceof HTMLDivElement){
+ if (cartItemsNode instanceof HTMLDivElement) {
cartItemsNode.style.maxHeight = cartItemsNode.scrollHeight + "px";
-
+
cartItemsNode.style.height = cartItemsNode.scrollHeight + "px";
}
@@ -914,7 +1016,7 @@ function handleCartView(paymentDetails) {
var hiddenItemsCount =
orderDetails.length - MAX_ITEMS_VISIBLE_AFTER_COLLAPSE;
if (cartButtonTextNode instanceof HTMLSpanElement) {
- cartButtonTextNode.innerText = translations.showMore+" (" + hiddenItemsCount + ")";
+ cartButtonTextNode.innerText = translations.showMore + " (" + hiddenItemsCount + ")";
}
var arrowDownImage = document.getElementById("arrow-down");
if (
diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js
index ab46223df17..d45a72b5e55 100644
--- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js
+++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js
@@ -27,6 +27,7 @@ function initializeSDK() {
// @ts-ignore
hyper = window.Hyper(pub_key, {
isPreloadEnabled: false,
+ shouldUseTopRedirection: true,
});
// @ts-ignore
widgets = hyper.widgets({
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 1a635b097ef..668de683181 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -3647,6 +3647,7 @@ impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest>
enabled_saved_payment_method: config.enabled_saved_payment_method,
hide_card_nickname_field: config.hide_card_nickname_field,
show_card_form_by_default: config.show_card_form_by_default,
+ details_layout: config.details_layout,
transaction_details: config.transaction_details.map(|transaction_details| {
transaction_details
.iter()
@@ -3655,6 +3656,11 @@ impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest>
})
.collect()
}),
+ background_image: config.background_image.map(|background_image| {
+ diesel_models::business_profile::PaymentLinkBackgroundImageConfig::foreign_from(
+ background_image.clone(),
+ )
+ }),
}
}
}
@@ -3701,6 +3707,7 @@ impl ForeignFrom<diesel_models::PaymentLinkConfigRequestForPayments>
enabled_saved_payment_method: config.enabled_saved_payment_method,
hide_card_nickname_field: config.hide_card_nickname_field,
show_card_form_by_default: config.show_card_form_by_default,
+ details_layout: config.details_layout,
transaction_details: config.transaction_details.map(|transaction_details| {
transaction_details
.iter()
@@ -3711,6 +3718,11 @@ impl ForeignFrom<diesel_models::PaymentLinkConfigRequestForPayments>
})
.collect()
}),
+ background_image: config.background_image.map(|background_image| {
+ api_models::admin::PaymentLinkBackgroundImageConfig::foreign_from(
+ background_image.clone(),
+ )
+ }),
}
}
}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index a3c3da0462a..269eb831fc6 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -1921,6 +1921,7 @@ impl ForeignFrom<api_models::admin::BusinessPaymentLinkConfig>
.collect()
}),
allowed_domains: item.allowed_domains,
+ branding_visibility: item.branding_visibility,
}
}
}
@@ -1938,6 +1939,7 @@ impl ForeignFrom<diesel_models::business_profile::BusinessPaymentLinkConfig>
.collect()
}),
allowed_domains: item.allowed_domains,
+ branding_visibility: item.branding_visibility,
}
}
}
@@ -1955,6 +1957,10 @@ impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest>
enabled_saved_payment_method: item.enabled_saved_payment_method,
hide_card_nickname_field: item.hide_card_nickname_field,
show_card_form_by_default: item.show_card_form_by_default,
+ details_layout: item.details_layout,
+ background_image: item
+ .background_image
+ .map(|background_image| background_image.foreign_into()),
}
}
}
@@ -1973,6 +1979,36 @@ impl ForeignFrom<diesel_models::business_profile::PaymentLinkConfigRequest>
hide_card_nickname_field: item.hide_card_nickname_field,
show_card_form_by_default: item.show_card_form_by_default,
transaction_details: None,
+ details_layout: item.details_layout,
+ background_image: item
+ .background_image
+ .map(|background_image| background_image.foreign_into()),
+ }
+ }
+}
+
+impl ForeignFrom<diesel_models::business_profile::PaymentLinkBackgroundImageConfig>
+ for api_models::admin::PaymentLinkBackgroundImageConfig
+{
+ fn foreign_from(
+ item: diesel_models::business_profile::PaymentLinkBackgroundImageConfig,
+ ) -> Self {
+ Self {
+ url: item.url,
+ position: item.position,
+ size: item.size,
+ }
+ }
+}
+
+impl ForeignFrom<api_models::admin::PaymentLinkBackgroundImageConfig>
+ for diesel_models::business_profile::PaymentLinkBackgroundImageConfig
+{
+ fn foreign_from(item: api_models::admin::PaymentLinkBackgroundImageConfig) -> Self {
+ Self {
+ url: item.url,
+ position: item.position,
+ size: item.size,
}
}
}
|
feat
|
payment links - add support for custom background image and layout in details section (#6725)
|
736ca446cd436d8482694f0efc4dbd8e6c36856e
|
2025-02-25 23:47:38
|
Sai Harsha Vardhan
|
feat(core): add support to external 3ds authentication for co-badged cards (#7274)
| false
|
diff --git a/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs b/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs
index 067c6042ec2..06d73644e30 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs
@@ -1,10 +1,11 @@
-use cards::CardNumber;
use common_utils::{ext_traits::OptionExt, pii::Email};
use error_stack::{Report, ResultExt};
use serde::{Deserialize, Serialize};
use crate::{
- address, errors::api_error_response::ApiErrorResponse, payment_method_data::PaymentMethodData,
+ address,
+ errors::api_error_response::ApiErrorResponse,
+ payment_method_data::{Card, PaymentMethodData},
router_request_types::BrowserInformation,
};
@@ -70,8 +71,8 @@ impl AuthNFlowType {
#[derive(Clone, Default, Debug)]
pub struct PreAuthNRequestData {
- // card number
- pub card_holder_account_number: CardNumber,
+ // card data
+ pub card: Card,
}
#[derive(Clone, Debug)]
diff --git a/crates/router/src/connector/gpayments/transformers.rs b/crates/router/src/connector/gpayments/transformers.rs
index 572b6dfa0e7..9acb374c8a8 100644
--- a/crates/router/src/connector/gpayments/transformers.rs
+++ b/crates/router/src/connector/gpayments/transformers.rs
@@ -69,7 +69,7 @@ impl TryFrom<&GpaymentsRouterData<&types::authentication::PreAuthNVersionCallRou
let router_data = value.router_data;
let metadata = GpaymentsMetaData::try_from(&router_data.connector_meta_data)?;
Ok(Self {
- acct_number: router_data.request.card_holder_account_number.clone(),
+ acct_number: router_data.request.card.card_number.clone(),
merchant_id: metadata.merchant_id,
})
}
@@ -141,7 +141,7 @@ impl TryFrom<&GpaymentsRouterData<&types::authentication::PreAuthNRouterData>>
let router_data = value.router_data;
let metadata = GpaymentsMetaData::try_from(&router_data.connector_meta_data)?;
Ok(Self {
- acct_number: router_data.request.card_holder_account_number.clone(),
+ acct_number: router_data.request.card.card_number.clone(),
card_scheme: None,
challenge_window_size: Some(gpayments_types::ChallengeWindowSize::FullScreen),
event_callback_url: "https://webhook.site/55e3db24-7c4e-4432-9941-d806f68d210b"
diff --git a/crates/router/src/connector/netcetera/transformers.rs b/crates/router/src/connector/netcetera/transformers.rs
index ab6002ba312..213433972c6 100644
--- a/crates/router/src/connector/netcetera/transformers.rs
+++ b/crates/router/src/connector/netcetera/transformers.rs
@@ -369,13 +369,52 @@ impl TryFrom<&NetceteraRouterData<&types::authentication::PreAuthNRouterData>>
value: &NetceteraRouterData<&types::authentication::PreAuthNRouterData>,
) -> Result<Self, Self::Error> {
let router_data = value.router_data;
+ let is_cobadged_card = || {
+ router_data
+ .request
+ .card
+ .card_number
+ .is_cobadged_card()
+ .change_context(errors::ConnectorError::RequestEncodingFailed)
+ .attach_printable("error while checking is_cobadged_card")
+ };
Ok(Self {
- cardholder_account_number: router_data.request.card_holder_account_number.clone(),
- scheme_id: None,
+ cardholder_account_number: router_data.request.card.card_number.clone(),
+ scheme_id: router_data
+ .request
+ .card
+ .card_network
+ .clone()
+ .map(|card_network| {
+ is_cobadged_card().map(|is_cobadged_card| {
+ is_cobadged_card.then_some(SchemeId::try_from(card_network))
+ })
+ })
+ .transpose()?
+ .flatten()
+ .transpose()?,
})
}
}
+impl TryFrom<common_enums::CardNetwork> for SchemeId {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(network: common_enums::CardNetwork) -> Result<Self, Self::Error> {
+ match network {
+ common_enums::CardNetwork::Visa => Ok(Self::Visa),
+ common_enums::CardNetwork::Mastercard => Ok(Self::Mastercard),
+ common_enums::CardNetwork::JCB => Ok(Self::Jcb),
+ common_enums::CardNetwork::AmericanExpress => Ok(Self::AmericanExpress),
+ common_enums::CardNetwork::DinersClub => Ok(Self::Diners),
+ common_enums::CardNetwork::CartesBancaires => Ok(Self::CartesBancaires),
+ common_enums::CardNetwork::UnionPay => Ok(Self::UnionPay),
+ _ => Err(errors::ConnectorError::RequestEncodingFailedWithReason(
+ "Invalid card network".to_string(),
+ ))?,
+ }
+ }
+}
+
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
#[serde_with::skip_serializing_none]
diff --git a/crates/router/src/connector/threedsecureio/transformers.rs b/crates/router/src/connector/threedsecureio/transformers.rs
index c66a0aa0b67..dc1a90f36e7 100644
--- a/crates/router/src/connector/threedsecureio/transformers.rs
+++ b/crates/router/src/connector/threedsecureio/transformers.rs
@@ -694,7 +694,7 @@ impl TryFrom<&ThreedsecureioRouterData<&types::authentication::PreAuthNRouterDat
) -> Result<Self, Self::Error> {
let router_data = value.router_data;
Ok(Self {
- acct_number: router_data.request.card_holder_account_number.clone(),
+ acct_number: router_data.request.card.card_number.clone(),
ds: None,
})
}
diff --git a/crates/router/src/core/authentication.rs b/crates/router/src/core/authentication.rs
index e6c27748170..ae8dc6e08c1 100644
--- a/crates/router/src/core/authentication.rs
+++ b/crates/router/src/core/authentication.rs
@@ -128,7 +128,7 @@ pub async fn perform_post_authentication(
pub async fn perform_pre_authentication(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
- card_number: cards::CardNumber,
+ card: hyperswitch_domain_models::payment_method_data::Card,
token: String,
business_profile: &domain::Profile,
acquirer_details: Option<types::AcquirerDetails>,
@@ -158,7 +158,7 @@ pub async fn perform_pre_authentication(
transformers::construct_pre_authentication_router_data(
state,
authentication_connector_name.clone(),
- card_number.clone(),
+ card.clone(),
&three_ds_connector_account,
business_profile.merchant_id.clone(),
)?;
@@ -186,7 +186,7 @@ pub async fn perform_pre_authentication(
transformers::construct_pre_authentication_router_data(
state,
authentication_connector_name.clone(),
- card_number,
+ card,
&three_ds_connector_account,
business_profile.merchant_id.clone(),
)?;
diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rs
index 4e7e005c946..c9d2711840e 100644
--- a/crates/router/src/core/authentication/transformers.rs
+++ b/crates/router/src/core/authentication/transformers.rs
@@ -108,7 +108,7 @@ pub fn construct_post_authentication_router_data(
pub fn construct_pre_authentication_router_data<F: Clone>(
state: &SessionState,
authentication_connector: String,
- card_holder_account_number: cards::CardNumber,
+ card: hyperswitch_domain_models::payment_method_data::Card,
merchant_connector_account: &payments_helpers::MerchantConnectorAccountType,
merchant_id: common_utils::id_type::MerchantId,
) -> RouterResult<
@@ -118,9 +118,7 @@ pub fn construct_pre_authentication_router_data<F: Clone>(
types::authentication::AuthenticationResponseData,
>,
> {
- let router_request = types::authentication::PreAuthNRequestData {
- card_holder_account_number,
- };
+ let router_request = types::authentication::PreAuthNRequestData { card };
construct_router_data(
state,
authentication_connector,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index ba509221956..21d84d3cba1 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -6621,7 +6621,7 @@ pub enum UnifiedAuthenticationServiceFlow {
ClickToPayInitiate,
ExternalAuthenticationInitiate {
acquirer_details: Option<authentication::types::AcquirerDetails>,
- card_number: ::cards::CardNumber,
+ card: Box<hyperswitch_domain_models::payment_method_data::Card>,
token: String,
},
ExternalAuthenticationPostAuthenticate {
@@ -6652,12 +6652,12 @@ pub async fn decide_action_for_unified_authentication_service<F: Clone>(
Ok(match external_authentication_flow {
Some(PaymentExternalAuthenticationFlow::PreAuthenticationFlow {
acquirer_details,
- card_number,
+ card,
token,
}) => Some(
UnifiedAuthenticationServiceFlow::ExternalAuthenticationInitiate {
acquirer_details,
- card_number,
+ card,
token,
},
),
@@ -6695,7 +6695,7 @@ pub async fn decide_action_for_unified_authentication_service<F: Clone>(
pub enum PaymentExternalAuthenticationFlow {
PreAuthenticationFlow {
acquirer_details: Option<authentication::types::AcquirerDetails>,
- card_number: ::cards::CardNumber,
+ card: Box<hyperswitch_domain_models::payment_method_data::Card>,
token: String,
},
PostAuthenticationFlow {
@@ -6734,9 +6734,9 @@ pub async fn get_payment_external_authentication_flow_during_confirm<F: Clone>(
"payment connector supports external authentication: {:?}",
connector_supports_separate_authn.is_some()
);
- let card_number = payment_data.payment_method_data.as_ref().and_then(|pmd| {
+ let card = payment_data.payment_method_data.as_ref().and_then(|pmd| {
if let domain::PaymentMethodData::Card(card) = pmd {
- Some(card.card_number.clone())
+ Some(card.clone())
} else {
None
}
@@ -6750,9 +6750,7 @@ pub async fn get_payment_external_authentication_flow_during_confirm<F: Clone>(
&& mandate_type
!= Some(api_models::payments::MandateTransactionType::RecurringMandateTransaction)
{
- if let Some((connector_data, card_number)) =
- connector_supports_separate_authn.zip(card_number)
- {
+ if let Some((connector_data, card)) = connector_supports_separate_authn.zip(card) {
let token = payment_data
.token
.clone()
@@ -6793,7 +6791,7 @@ pub async fn get_payment_external_authentication_flow_during_confirm<F: Clone>(
.ok()
});
Some(PaymentExternalAuthenticationFlow::PreAuthenticationFlow {
- card_number,
+ card: Box::new(card),
token,
acquirer_details,
})
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 62f60d938a2..852e51f4a8e 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -1009,19 +1009,19 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
payment_data.authentication = match external_authentication_flow {
Some(helpers::PaymentExternalAuthenticationFlow::PreAuthenticationFlow {
acquirer_details,
- card_number,
+ card,
token,
}) => {
- let authentication = authentication::perform_pre_authentication(
+ let authentication = Box::pin(authentication::perform_pre_authentication(
state,
key_store,
- card_number,
+ *card,
token,
business_profile,
acquirer_details,
Some(payment_data.payment_attempt.payment_id.clone()),
payment_data.payment_attempt.organization_id.clone(),
- )
+ ))
.await?;
if authentication.is_separate_authn_required()
|| authentication.authentication_status.is_failed()
|
feat
|
add support to external 3ds authentication for co-badged cards (#7274)
|
05ee47a6e90bd68a0faa6dcc381c48a1f0f274d8
|
2023-10-04 21:24:54
|
Hrithikesh
|
fix(connector): use enum to deserialize latest_charge in stripe psync response (#2444)
| false
|
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 488a7a295bd..57a7935f030 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -2125,7 +2125,14 @@ pub struct PaymentIntentSyncResponse {
#[serde(flatten)]
payment_intent_fields: PaymentIntentResponse,
pub last_payment_error: Option<LastPaymentError>,
- pub latest_charge: Option<StripeCharge>,
+ pub latest_charge: Option<StripeChargeEnum>,
+}
+
+#[derive(Deserialize, Debug, Clone)]
+#[serde(untagged)]
+pub enum StripeChargeEnum {
+ ChargeId(String),
+ ChargeObject(StripeCharge),
}
#[derive(Deserialize, Clone, Debug)]
@@ -2414,19 +2421,38 @@ impl<F, T>
types::MandateReference::foreign_from((
item.response.payment_method_options.clone(),
match item.response.latest_charge.clone() {
- Some(charge) => match charge.payment_method_details {
- Some(StripePaymentMethodDetailsResponse::Bancontact { bancontact }) => {
- bancontact.attached_payment_method.unwrap_or(pm)
- }
- Some(StripePaymentMethodDetailsResponse::Ideal { ideal }) => {
- ideal.attached_payment_method.unwrap_or(pm)
+ Some(StripeChargeEnum::ChargeObject(charge)) => {
+ match charge.payment_method_details {
+ Some(StripePaymentMethodDetailsResponse::Bancontact { bancontact }) => {
+ bancontact.attached_payment_method.unwrap_or(pm)
+ }
+ Some(StripePaymentMethodDetailsResponse::Ideal { ideal }) => {
+ ideal.attached_payment_method.unwrap_or(pm)
+ }
+ Some(StripePaymentMethodDetailsResponse::Sofort { sofort }) => {
+ sofort.attached_payment_method.unwrap_or(pm)
+ }
+ Some(StripePaymentMethodDetailsResponse::Blik)
+ | Some(StripePaymentMethodDetailsResponse::Eps)
+ | Some(StripePaymentMethodDetailsResponse::Fpx)
+ | Some(StripePaymentMethodDetailsResponse::Giropay)
+ | Some(StripePaymentMethodDetailsResponse::Przelewy24)
+ | Some(StripePaymentMethodDetailsResponse::Card)
+ | Some(StripePaymentMethodDetailsResponse::Klarna)
+ | Some(StripePaymentMethodDetailsResponse::Affirm)
+ | Some(StripePaymentMethodDetailsResponse::AfterpayClearpay)
+ | Some(StripePaymentMethodDetailsResponse::ApplePay)
+ | Some(StripePaymentMethodDetailsResponse::Ach)
+ | Some(StripePaymentMethodDetailsResponse::Sepa)
+ | Some(StripePaymentMethodDetailsResponse::Becs)
+ | Some(StripePaymentMethodDetailsResponse::Bacs)
+ | Some(StripePaymentMethodDetailsResponse::Wechatpay)
+ | Some(StripePaymentMethodDetailsResponse::Alipay)
+ | Some(StripePaymentMethodDetailsResponse::CustomerBalance)
+ | None => pm,
}
- Some(StripePaymentMethodDetailsResponse::Sofort { sofort }) => {
- sofort.attached_payment_method.unwrap_or(pm)
- }
- _ => pm,
- },
- None => pm,
+ }
+ Some(StripeChargeEnum::ChargeId(_)) | None => pm,
},
))
});
|
fix
|
use enum to deserialize latest_charge in stripe psync response (#2444)
|
326b6b52324ae60128a1b1fbcff85ab3b99a500a
|
2024-06-05 13:12:02
|
Jeeva Ramachandran
|
chore(eulid_wasm): allow merchant to select different paypal paymentmenthod type (#4882)
| false
|
diff --git a/crates/connector_configs/src/common_config.rs b/crates/connector_configs/src/common_config.rs
index fb4bf93c6ff..950af06752c 100644
--- a/crates/connector_configs/src/common_config.rs
+++ b/crates/connector_configs/src/common_config.rs
@@ -150,6 +150,7 @@ pub struct Provider {
}
), value_type = Option<AcceptedCountries>)]
pub accepted_countries: Option<api_models::admin::AcceptedCountries>,
+ pub payment_experience: Option<api_models::enums::PaymentExperience>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
diff --git a/crates/connector_configs/src/response_modifier.rs b/crates/connector_configs/src/response_modifier.rs
index bdd366ce1c1..16a50c3dcd9 100644
--- a/crates/connector_configs/src/response_modifier.rs
+++ b/crates/connector_configs/src/response_modifier.rs
@@ -71,6 +71,7 @@ impl ConnectorApiIntegrationPayload {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
+ payment_experience: method_type.payment_experience,
})
}
}
@@ -82,6 +83,7 @@ impl ConnectorApiIntegrationPayload {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
+ payment_experience: method_type.payment_experience,
})
}
}
@@ -93,6 +95,7 @@ impl ConnectorApiIntegrationPayload {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
+ payment_experience: method_type.payment_experience,
})
}
}
@@ -104,6 +107,7 @@ impl ConnectorApiIntegrationPayload {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
+ payment_experience: method_type.payment_experience,
})
}
}
@@ -115,6 +119,7 @@ impl ConnectorApiIntegrationPayload {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
+ payment_experience: method_type.payment_experience,
})
}
}
@@ -126,6 +131,7 @@ impl ConnectorApiIntegrationPayload {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
+ payment_experience: method_type.payment_experience,
})
}
}
@@ -137,6 +143,7 @@ impl ConnectorApiIntegrationPayload {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
+ payment_experience: method_type.payment_experience,
})
}
}
@@ -148,6 +155,7 @@ impl ConnectorApiIntegrationPayload {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
+ payment_experience: method_type.payment_experience,
})
}
}
@@ -159,6 +167,7 @@ impl ConnectorApiIntegrationPayload {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
+ payment_experience: method_type.payment_experience,
})
}
}
@@ -170,6 +179,7 @@ impl ConnectorApiIntegrationPayload {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
+ payment_experience: method_type.payment_experience,
})
}
}
@@ -181,6 +191,7 @@ impl ConnectorApiIntegrationPayload {
payment_method_type: method_type.payment_method_type,
accepted_currencies: method_type.accepted_currencies.clone(),
accepted_countries: method_type.accepted_countries.clone(),
+ payment_experience: method_type.payment_experience,
})
}
}
diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs
index 976068c98b6..be7f31416fe 100644
--- a/crates/connector_configs/src/transformer.rs
+++ b/crates/connector_configs/src/transformer.rs
@@ -35,6 +35,7 @@ impl DashboardRequestPayload {
connector: Connector,
payment_method_type: PaymentMethodType,
payment_method: PaymentMethod,
+ payment_experience: Option<api_models::enums::PaymentExperience>,
) -> Option<api_models::enums::PaymentExperience> {
match payment_method {
PaymentMethod::BankRedirect => None,
@@ -43,12 +44,11 @@ impl DashboardRequestPayload {
(Connector::DummyConnector4, _) | (Connector::DummyConnector7, _) => {
Some(api_models::enums::PaymentExperience::RedirectToUrl)
}
+ (Connector::Paypal, Paypal) => payment_experience,
(Connector::Zen, GooglePay) | (Connector::Zen, ApplePay) => {
Some(api_models::enums::PaymentExperience::RedirectToUrl)
}
- (Connector::Paypal, Paypal)
- | (Connector::Braintree, Paypal)
- | (Connector::Klarna, Klarna) => {
+ (Connector::Braintree, Paypal) | (Connector::Klarna, Klarna) => {
Some(api_models::enums::PaymentExperience::InvokeSdkClient)
}
(Connector::Globepay, AliPay)
@@ -64,38 +64,6 @@ impl DashboardRequestPayload {
}
}
- pub fn transform_paypal_payment_method(
- providers: Vec<Provider>,
- ) -> Vec<payment_methods::RequestPaymentMethodTypes> {
- let payment_experiences = [
- api_models::enums::PaymentExperience::RedirectToUrl,
- api_models::enums::PaymentExperience::InvokeSdkClient,
- ];
- let default_provider = Provider {
- payment_method_type: Paypal,
- accepted_currencies: None,
- accepted_countries: None,
- };
- let provider = providers.first().unwrap_or(&default_provider);
- let mut payment_method_types = Vec::new();
-
- for experience in payment_experiences {
- let data = payment_methods::RequestPaymentMethodTypes {
- payment_method_type: provider.payment_method_type,
- card_networks: None,
- minimum_amount: Some(0),
- maximum_amount: Some(68607706),
- recurring_enabled: true,
- installment_payment_enabled: false,
- accepted_currencies: provider.accepted_currencies.clone(),
- accepted_countries: provider.accepted_countries.clone(),
- payment_experience: Some(experience),
- };
- payment_method_types.push(data);
- }
-
- payment_method_types
- }
pub fn transform_payment_method(
connector: Connector,
provider: Vec<Provider>,
@@ -116,6 +84,7 @@ impl DashboardRequestPayload {
connector,
method_type.payment_method_type,
payment_method,
+ method_type.payment_experience,
),
};
payment_method_types.push(data)
@@ -158,37 +127,8 @@ impl DashboardRequestPayload {
}
}
- PaymentMethod::Wallet => match request.connector {
- Connector::Paypal => {
- if let Some(provider) = payload.provider {
- let val = Self::transform_paypal_payment_method(provider);
- if !val.is_empty() {
- let methods = PaymentMethodsEnabled {
- payment_method: payload.payment_method,
- payment_method_types: Some(val),
- };
- payment_method_enabled.push(methods);
- }
- }
- }
- _ => {
- if let Some(provider) = payload.provider {
- let val = Self::transform_payment_method(
- request.connector,
- provider,
- payload.payment_method,
- );
- if !val.is_empty() {
- let methods = PaymentMethodsEnabled {
- payment_method: payload.payment_method,
- payment_method_types: Some(val),
- };
- payment_method_enabled.push(methods);
- }
- }
- }
- },
PaymentMethod::BankRedirect
+ | PaymentMethod::Wallet
| PaymentMethod::PayLater
| PaymentMethod::BankTransfer
| PaymentMethod::Crypto
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index 0d40e81c4ad..e614ce45dcd 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -1630,6 +1630,10 @@ additional_secret="Payme Client Key"
payment_method_type = "UnionPay"
[[paypal.wallet]]
payment_method_type = "paypal"
+ payment_experience = "invoke_sdk_client"
+[[paypal.wallet]]
+ payment_method_type = "paypal"
+ payment_experience = "redirect_to_url"
[[paypal.bank_redirect]]
payment_method_type = "ideal"
[[paypal.bank_redirect]]
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index 32fa87d970d..d0bc19ec325 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -1260,6 +1260,10 @@ merchant_secret="Source verification key"
payment_method_type = "UnionPay"
[[paypal.wallet]]
payment_method_type = "paypal"
+ payment_experience = "invoke_sdk_client"
+[[paypal.wallet]]
+ payment_method_type = "paypal"
+ payment_experience = "redirect_to_url"
is_verifiable = true
[paypal.connector_auth.BodyKey]
api_key="Client Secret"
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index a71933870a5..e337dba4e71 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -1630,6 +1630,10 @@ additional_secret="Payme Client Key"
payment_method_type = "UnionPay"
[[paypal.wallet]]
payment_method_type = "paypal"
+ payment_experience = "invoke_sdk_client"
+[[paypal.wallet]]
+ payment_method_type = "paypal"
+ payment_experience = "redirect_to_url"
[[paypal.bank_redirect]]
payment_method_type = "ideal"
[[paypal.bank_redirect]]
|
chore
|
allow merchant to select different paypal paymentmenthod type (#4882)
|
53b4816d27fe7794cb482887ed17ddb4386bd2f7
|
2023-10-06 16:13:02
|
Narayan Bhat
|
refactor(merchant_account): make `organization_id` as mandatory (#2458)
| false
|
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index a1b13c5ff31..6162ceffcb3 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -265,7 +265,7 @@ pub struct MerchantAccountResponse {
pub intent_fulfillment_time: Option<i64>,
/// The organization id merchant is associated with
- pub organization_id: Option<String>,
+ pub organization_id: String,
/// A boolean value to indicate if the merchant has recon service is enabled or not, by default value is false
pub is_recon_enabled: bool,
diff --git a/crates/diesel_models/src/merchant_account.rs b/crates/diesel_models/src/merchant_account.rs
index 2b63d4bf9b2..dd68f3755f1 100644
--- a/crates/diesel_models/src/merchant_account.rs
+++ b/crates/diesel_models/src/merchant_account.rs
@@ -36,7 +36,7 @@ pub struct MerchantAccount {
pub modified_at: time::PrimitiveDateTime,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
- pub organization_id: Option<String>,
+ pub organization_id: String,
pub is_recon_enabled: bool,
pub default_profile: Option<String>,
pub recon_status: storage_enums::ReconStatus,
@@ -65,7 +65,7 @@ pub struct MerchantAccountNew {
pub modified_at: time::PrimitiveDateTime,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
- pub organization_id: Option<String>,
+ pub organization_id: String,
pub is_recon_enabled: bool,
pub default_profile: Option<String>,
pub recon_status: storage_enums::ReconStatus,
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index d8a888046b9..0da819f2a70 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -437,7 +437,7 @@ diesel::table! {
frm_routing_algorithm -> Nullable<Jsonb>,
payout_routing_algorithm -> Nullable<Jsonb>,
#[max_length = 32]
- organization_id -> Nullable<Varchar>,
+ organization_id -> Varchar,
is_recon_enabled -> Bool,
#[max_length = 64]
default_profile -> Nullable<Varchar>,
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index c7009bf4cc9..ec229bd8a56 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -31,6 +31,8 @@ use crate::{
utils::{self, OptionExt},
};
+const DEFAULT_ORG_ID: &str = "org_abcdefghijklmn";
+
#[inline]
pub fn create_merchant_publishable_key() -> String {
format!(
@@ -164,7 +166,7 @@ pub async fn create_merchant_account(
intent_fulfillment_time: req.intent_fulfillment_time.map(i64::from),
payout_routing_algorithm: req.payout_routing_algorithm,
id: None,
- organization_id: req.organization_id,
+ organization_id: req.organization_id.unwrap_or(DEFAULT_ORG_ID.to_string()),
is_recon_enabled: false,
default_profile: None,
recon_status: diesel_models::enums::ReconStatus::NotRequested,
diff --git a/crates/router/src/types/domain/merchant_account.rs b/crates/router/src/types/domain/merchant_account.rs
index 30950f8c9c9..c32942a847d 100644
--- a/crates/router/src/types/domain/merchant_account.rs
+++ b/crates/router/src/types/domain/merchant_account.rs
@@ -40,7 +40,7 @@ pub struct MerchantAccount {
pub modified_at: time::PrimitiveDateTime,
pub intent_fulfillment_time: Option<i64>,
pub payout_routing_algorithm: Option<serde_json::Value>,
- pub organization_id: Option<String>,
+ pub organization_id: String,
pub is_recon_enabled: bool,
pub default_profile: Option<String>,
pub recon_status: diesel_models::enums::ReconStatus,
diff --git a/migrations/2023-10-05-085859_make_org_id_mandatory_in_ma/down.sql b/migrations/2023-10-05-085859_make_org_id_mandatory_in_ma/down.sql
new file mode 100644
index 00000000000..eb6a02e3dac
--- /dev/null
+++ b/migrations/2023-10-05-085859_make_org_id_mandatory_in_ma/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE merchant_account
+ALTER COLUMN organization_id DROP NOT NULL;
diff --git a/migrations/2023-10-05-085859_make_org_id_mandatory_in_ma/up.sql b/migrations/2023-10-05-085859_make_org_id_mandatory_in_ma/up.sql
new file mode 100644
index 00000000000..eb6b24e16ae
--- /dev/null
+++ b/migrations/2023-10-05-085859_make_org_id_mandatory_in_ma/up.sql
@@ -0,0 +1,8 @@
+-- Your SQL goes here
+UPDATE merchant_account
+SET organization_id = 'org_abcdefghijklmn'
+WHERE organization_id IS NULL;
+
+ALTER TABLE merchant_account
+ALTER COLUMN organization_id
+SET NOT NULL;
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 13ddad32af5..56632a68c39 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -6113,6 +6113,7 @@
"enable_payment_response_hash",
"redirect_to_merchant_with_http_post",
"primary_business_details",
+ "organization_id",
"is_recon_enabled",
"recon_status"
],
@@ -6241,8 +6242,7 @@
},
"organization_id": {
"type": "string",
- "description": "The organization id merchant is associated with",
- "nullable": true
+ "description": "The organization id merchant is associated with"
},
"is_recon_enabled": {
"type": "boolean",
|
refactor
|
make `organization_id` as mandatory (#2458)
|
c0d910f50ebe9cf387b08ecbdb86f2f60346c0cb
|
2024-02-06 14:46:02
|
Narayan Bhat
|
fix(merchant_connector_account): change error to DuplicateMerchantAccount (#3496)
| false
|
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 364c5b9b212..024ef653faa 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1234,7 +1234,7 @@ pub async fn update_payment_connector(
connector_type: Some(req.connector_type),
connector_name: None,
merchant_connector_id: None,
- connector_label: req.connector_label,
+ connector_label: req.connector_label.clone(),
connector_account_details: req
.connector_account_details
.async_lift(|inner| {
@@ -1264,10 +1264,25 @@ pub async fn update_payment_connector(
status: Some(connector_status),
};
+ // Profile id should always be present
+ let profile_id = mca
+ .profile_id
+ .clone()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .into_report()
+ .attach_printable("Missing `profile_id` in merchant connector account")?;
+
+ let request_connector_label = req.connector_label;
+
let updated_mca = db
.update_merchant_connector_account(mca, payment_connector.into(), &key_store)
.await
- .change_context(errors::ApiErrorResponse::InternalServerError)
+ .change_context(
+ errors::ApiErrorResponse::DuplicateMerchantConnectorAccount {
+ profile_id,
+ connector_name: request_connector_label.unwrap_or_default(),
+ },
+ )
.attach_printable_lazy(|| {
format!("Failed while updating MerchantConnectorAccount: id: {merchant_connector_id}")
})?;
|
fix
|
change error to DuplicateMerchantAccount (#3496)
|
fc2e4514a3ec294d603a18868e9247330b6172cf
|
2023-04-17 23:58:09
|
Prasunna Soppa
|
feat(bank_redirects): modify api contract for sofort (#880)
| false
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index e2a9fb705e3..7cf78433f3b 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -520,6 +520,9 @@ pub enum BankRedirectData {
bank_name: api_enums::BankNames,
},
Sofort {
+ /// The billing details for bank redirection
+ billing_details: BankRedirectBilling,
+
/// The country for bank payment
#[schema(value_type = Country, example = "US")]
country: api_enums::CountryCode,
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 1be3d1dc161..aa3c74f0b92 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -701,6 +701,7 @@ fn get_sofort_extra_details(
if let api_models::payments::BankRedirectData::Sofort {
country,
preferred_language,
+ ..
} = b
{
(
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index b00cc61f820..1440fe6a1d1 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -508,6 +508,7 @@ fn get_bank_specific_data(
payments::BankRedirectData::Sofort {
country,
preferred_language,
+ ..
} => Some(BankSpecificData::Sofort {
country: country.to_owned(),
preferred_language: preferred_language.to_owned(),
|
feat
|
modify api contract for sofort (#880)
|
c333fb7fc02cf19d74ca80093552e4c4628f248a
|
2023-08-09 01:56:27
|
Hrithikesh
|
feat(router): add support for multiple partial capture (#1721)
| false
|
diff --git a/Cargo.lock b/Cargo.lock
index 1840cefa6b6..c020039a10e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -297,12 +297,6 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
-[[package]]
-name = "adler32"
-version = "1.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "aae1277d39aeec15cb388266ecc24b11c80469deae6067e17a1a7aa9e5c1f234"
-
[[package]]
name = "ahash"
version = "0.7.6"
@@ -385,14 +379,15 @@ dependencies = [
"cards",
"common_enums",
"common_utils",
- "error-stack",
+ "frunk",
+ "frunk_core",
"masking",
"mime",
"reqwest",
"router_derive",
"serde",
"serde_json",
- "strum 0.24.1",
+ "strum",
"time 0.3.22",
"url",
"utoipa",
@@ -1165,12 +1160,6 @@ version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c676a478f63e9fa2dd5368a42f28bba0d6c560b775f38583c8bbaa7fcd67c9c"
-[[package]]
-name = "bytemuck"
-version = "1.13.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "17febce684fd15d89027105661fec94afb475cb995fbc59d2865198446ba2eea"
-
[[package]]
name = "byteorder"
version = "1.4.3"
@@ -1287,12 +1276,6 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
-[[package]]
-name = "checked_int_cast"
-version = "1.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "17cc5e6b5ab06331c33589842070416baa137e8b0eb912b008cfd4a78ada7919"
-
[[package]]
name = "chrono"
version = "0.4.26"
@@ -1349,23 +1332,15 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2da6da31387c7e4ef160ffab6d5e7f00c42626fe39aea70a7b0f1773f7dd6c1b"
-[[package]]
-name = "color_quant"
-version = "1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
-
[[package]]
name = "common_enums"
version = "0.1.0"
dependencies = [
- "common_utils",
"diesel",
"router_derive",
"serde",
"serde_json",
- "strum 0.25.0",
- "time 0.3.22",
+ "strum",
"utoipa",
]
@@ -1518,17 +1493,6 @@ dependencies = [
"crossbeam-utils",
]
-[[package]]
-name = "crossbeam-deque"
-version = "0.8.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ce6fd6f855243022dcecf8702fef0c297d4338e226845fe067f6341ad9fa0cef"
-dependencies = [
- "cfg-if",
- "crossbeam-epoch",
- "crossbeam-utils",
-]
-
[[package]]
name = "crossbeam-epoch"
version = "0.9.15"
@@ -1663,16 +1627,6 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eaa37046cc0f6c3cc6090fbdbf73ef0b8ef4cfcc37f6befc0020f63e8cf121e1"
-[[package]]
-name = "deflate"
-version = "0.8.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "73770f8e1fe7d64df17ca66ad28994a0a623ea497fa69486e14984e715c5d174"
-dependencies = [
- "adler32",
- "byteorder",
-]
-
[[package]]
name = "derive_deref"
version = "1.1.1"
@@ -1725,27 +1679,6 @@ dependencies = [
"syn 2.0.18",
]
-[[package]]
-name = "diesel_models"
-version = "0.1.0"
-dependencies = [
- "async-bb8-diesel",
- "common_enums",
- "common_utils",
- "diesel",
- "error-stack",
- "frunk",
- "frunk_core",
- "masking",
- "router_derive",
- "router_env",
- "serde",
- "serde_json",
- "strum 0.24.1",
- "thiserror",
- "time 0.3.22",
-]
-
[[package]]
name = "diesel_table_macro_syntax"
version = "0.1.0"
@@ -1808,7 +1741,6 @@ dependencies = [
"common_utils",
"config",
"diesel",
- "diesel_models",
"error-stack",
"external_services",
"masking",
@@ -1818,6 +1750,7 @@ dependencies = [
"serde",
"serde_json",
"serde_path_to_error",
+ "storage_models",
"thiserror",
"tokio",
]
@@ -1978,7 +1911,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b9429470923de8e8cbd4d2dc513535400b4b3fef0319fb5c4e1f520a7bef743"
dependencies = [
"crc32fast",
- "miniz_oxide 0.7.1",
+ "miniz_oxide",
]
[[package]]
@@ -2266,16 +2199,6 @@ dependencies = [
"wasi 0.11.0+wasi-snapshot-preview1",
]
-[[package]]
-name = "gif"
-version = "0.11.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3edd93c6756b4dfaf2709eafcc345ba2636565295c198a9cfbf75fa5e3e00b06"
-dependencies = [
- "color_quant",
- "weezl",
-]
-
[[package]]
name = "git2"
version = "0.17.2"
@@ -2541,25 +2464,6 @@ dependencies = [
"unicode-normalization",
]
-[[package]]
-name = "image"
-version = "0.23.14"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "24ffcb7e7244a9bf19d35bf2883b9c080c4ced3c07a9895572178cdb8f13f6a1"
-dependencies = [
- "bytemuck",
- "byteorder",
- "color_quant",
- "gif",
- "jpeg-decoder",
- "num-iter",
- "num-rational",
- "num-traits",
- "png",
- "scoped_threadpool",
- "tiff",
-]
-
[[package]]
name = "indexmap"
version = "1.9.3"
@@ -2664,15 +2568,6 @@ dependencies = [
"time 0.3.22",
]
-[[package]]
-name = "jpeg-decoder"
-version = "0.1.22"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "229d53d58899083193af11e15917b5640cd40b29ff475a1fe4ef725deb02d0f2"
-dependencies = [
- "rayon",
-]
-
[[package]]
name = "js-sys"
version = "0.3.64"
@@ -2956,25 +2851,6 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
-[[package]]
-name = "miniz_oxide"
-version = "0.3.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "791daaae1ed6889560f8c4359194f56648355540573244a5448a83ba1ecc7435"
-dependencies = [
- "adler32",
-]
-
-[[package]]
-name = "miniz_oxide"
-version = "0.4.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a92518e98c078586bc6c934028adcca4c92a53d6a958196de835170a01d84e4b"
-dependencies = [
- "adler",
- "autocfg",
-]
-
[[package]]
name = "miniz_oxide"
version = "0.7.1"
@@ -3089,28 +2965,6 @@ dependencies = [
"num-traits",
]
-[[package]]
-name = "num-iter"
-version = "0.1.43"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7d03e6c028c5dc5cac6e2dec0efda81fc887605bb3d884578bb6d6bf7514e252"
-dependencies = [
- "autocfg",
- "num-integer",
- "num-traits",
-]
-
-[[package]]
-name = "num-rational"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "12ac428b1cb17fce6f731001d307d351ec70a6d202fc2e60f7d4c5e42d8f4f07"
-dependencies = [
- "autocfg",
- "num-integer",
- "num-traits",
-]
-
[[package]]
name = "num-traits"
version = "0.2.15"
@@ -3452,18 +3306,6 @@ version = "0.3.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964"
-[[package]]
-name = "png"
-version = "0.16.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3c3287920cb847dee3de33d301c463fba14dda99db24214ddf93f83d3021f4c6"
-dependencies = [
- "bitflags 1.3.2",
- "crc32fast",
- "deflate",
- "miniz_oxide 0.3.7",
-]
-
[[package]]
name = "polling"
version = "2.8.0"
@@ -3598,16 +3440,6 @@ dependencies = [
"unicase",
]
-[[package]]
-name = "qrcode"
-version = "0.12.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "16d2f1455f3630c6e5107b4f2b94e74d76dea80736de0981fd27644216cff57f"
-dependencies = [
- "checked_int_cast",
- "image",
-]
-
[[package]]
name = "quanta"
version = "0.11.1"
@@ -3749,28 +3581,6 @@ dependencies = [
"bitflags 1.3.2",
]
-[[package]]
-name = "rayon"
-version = "1.7.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1d2df5196e37bcc87abebc0053e20787d73847bb33134a69841207dd0a47f03b"
-dependencies = [
- "either",
- "rayon-core",
-]
-
-[[package]]
-name = "rayon-core"
-version = "1.11.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4b8f95bd6966f5c87776639160a66bd8ab9895d9d4ab01ddba9fc60661aebe8d"
-dependencies = [
- "crossbeam-channel",
- "crossbeam-deque",
- "crossbeam-utils",
- "num_cpus",
-]
-
[[package]]
name = "redis-protocol"
version = "4.1.0"
@@ -3971,15 +3781,15 @@ dependencies = [
"crc32fast",
"derive_deref",
"diesel",
- "diesel_models",
"dyn-clone",
"encoding_rs",
"error-stack",
"external_services",
+ "frunk",
+ "frunk_core",
"futures",
"hex",
"http",
- "image",
"infer 0.13.0",
"josekit",
"jsonwebtoken",
@@ -3992,7 +3802,6 @@ dependencies = [
"nanoid",
"num_cpus",
"once_cell",
- "qrcode",
"rand 0.8.5",
"redis_interface",
"regex",
@@ -4010,7 +3819,8 @@ dependencies = [
"serial_test",
"signal-hook",
"signal-hook-tokio",
- "strum 0.24.1",
+ "storage_models",
+ "strum",
"test_utils",
"thirtyfour",
"thiserror",
@@ -4035,7 +3845,7 @@ dependencies = [
"quote",
"serde",
"serde_json",
- "strum 0.24.1",
+ "strum",
"syn 1.0.109",
]
@@ -4053,7 +3863,7 @@ dependencies = [
"serde",
"serde_json",
"serde_path_to_error",
- "strum 0.24.1",
+ "strum",
"time 0.3.22",
"tokio",
"tracing",
@@ -4232,12 +4042,6 @@ dependencies = [
"parking_lot",
]
-[[package]]
-name = "scoped_threadpool"
-version = "0.1.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1d51f5df5af43ab3f1360b429fa5e0152ac5ce8c0bd6485cae490332e96846a8"
-
[[package]]
name = "scopeguard"
version = "1.1.0"
@@ -4583,6 +4387,27 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"
+[[package]]
+name = "storage_models"
+version = "0.1.0"
+dependencies = [
+ "async-bb8-diesel",
+ "common_enums",
+ "common_utils",
+ "diesel",
+ "error-stack",
+ "frunk",
+ "frunk_core",
+ "masking",
+ "router_derive",
+ "router_env",
+ "serde",
+ "serde_json",
+ "strum",
+ "thiserror",
+ "time 0.3.22",
+]
+
[[package]]
name = "stringmatch"
version = "0.4.0"
@@ -4604,16 +4429,7 @@ version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "063e6045c0e62079840579a7e47a355ae92f60eb74daaf156fb1e84ba164e63f"
dependencies = [
- "strum_macros 0.24.3",
-]
-
-[[package]]
-name = "strum"
-version = "0.25.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "290d54ea6f91c969195bdbcd7442c8c2a2ba87da8bf60a7ee86a235d4bc1e125"
-dependencies = [
- "strum_macros 0.25.1",
+ "strum_macros",
]
[[package]]
@@ -4629,19 +4445,6 @@ dependencies = [
"syn 1.0.109",
]
-[[package]]
-name = "strum_macros"
-version = "0.25.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6069ca09d878a33f883cc06aaa9718ede171841d3832450354410b718b097232"
-dependencies = [
- "heck",
- "proc-macro2",
- "quote",
- "rustversion",
- "syn 2.0.18",
-]
-
[[package]]
name = "subtle"
version = "2.4.1"
@@ -4835,17 +4638,6 @@ dependencies = [
"once_cell",
]
-[[package]]
-name = "tiff"
-version = "0.6.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9a53f4706d65497df0c4349241deddf35f84cee19c87ed86ea8ca590f4464437"
-dependencies = [
- "jpeg-decoder",
- "miniz_oxide 0.4.4",
- "weezl",
-]
-
[[package]]
name = "time"
version = "0.1.45"
@@ -5572,12 +5364,6 @@ dependencies = [
"webpki",
]
-[[package]]
-name = "weezl"
-version = "0.1.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9193164d4de03a926d909d3bc7c30543cecb35400c02114792c2cae20d5e2dbb"
-
[[package]]
name = "winapi"
version = "0.3.9"
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 0e658f46927..53e9f66928d 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -85,6 +85,34 @@ pub enum AuthenticationType {
NoThreeDs,
}
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Default,
+ Eq,
+ PartialEq,
+ serde::Deserialize,
+ serde::Serialize,
+ strum::Display,
+ strum::EnumString,
+ Hash,
+)]
+#[router_derive::diesel_enum(storage_type = "pg_enum")]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum CaptureStatus {
+ // Capture request initiated
+ #[default]
+ Started,
+ // Capture request was successful
+ Charged,
+ // Capture is pending at connector side
+ Pending,
+ // Capture request failed
+ Failed,
+}
+
#[derive(
Clone,
Copy,
@@ -756,6 +784,7 @@ pub enum IntentStatus {
#[default]
RequiresConfirmation,
RequiresCapture,
+ PartiallyCaptured,
}
#[derive(
diff --git a/crates/diesel_models/src/capture.rs b/crates/diesel_models/src/capture.rs
new file mode 100644
index 00000000000..a747960b139
--- /dev/null
+++ b/crates/diesel_models/src/capture.rs
@@ -0,0 +1,121 @@
+use diesel::{AsChangeset, Identifiable, Insertable, Queryable};
+use serde::{Deserialize, Serialize};
+use time::PrimitiveDateTime;
+
+use crate::{enums as storage_enums, schema::captures};
+
+#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize)]
+#[diesel(table_name = captures)]
+#[diesel(primary_key(capture_id))]
+pub struct Capture {
+ pub capture_id: String,
+ pub payment_id: String,
+ pub merchant_id: String,
+ pub status: storage_enums::CaptureStatus,
+ pub amount: i64,
+ pub currency: Option<storage_enums::Currency>,
+ pub connector: Option<String>,
+ pub error_message: Option<String>,
+ pub error_code: Option<String>,
+ pub error_reason: Option<String>,
+ pub tax_amount: Option<i64>,
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub created_at: PrimitiveDateTime,
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub modified_at: PrimitiveDateTime,
+ pub authorized_attempt_id: String,
+ pub connector_transaction_id: Option<String>,
+ pub capture_sequence: i16,
+}
+
+#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)]
+#[diesel(table_name = captures)]
+pub struct CaptureNew {
+ pub capture_id: String,
+ pub payment_id: String,
+ pub merchant_id: String,
+ pub status: storage_enums::CaptureStatus,
+ pub amount: i64,
+ pub currency: Option<storage_enums::Currency>,
+ pub connector: Option<String>,
+ pub error_message: Option<String>,
+ pub error_code: Option<String>,
+ pub error_reason: Option<String>,
+ pub tax_amount: Option<i64>,
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub created_at: PrimitiveDateTime,
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub modified_at: PrimitiveDateTime,
+ pub authorized_attempt_id: String,
+ pub connector_transaction_id: Option<String>,
+ pub capture_sequence: i16,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub enum CaptureUpdate {
+ ResponseUpdate {
+ status: storage_enums::CaptureStatus,
+ connector_transaction_id: Option<String>,
+ },
+ ErrorUpdate {
+ status: storage_enums::CaptureStatus,
+ error_code: Option<String>,
+ error_message: Option<String>,
+ error_reason: Option<String>,
+ },
+}
+
+#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
+#[diesel(table_name = captures)]
+pub struct CaptureUpdateInternal {
+ pub status: Option<storage_enums::CaptureStatus>,
+ pub error_message: Option<String>,
+ pub error_code: Option<String>,
+ pub error_reason: Option<String>,
+ pub modified_at: Option<PrimitiveDateTime>,
+ pub connector_transaction_id: Option<String>,
+}
+
+impl CaptureUpdate {
+ pub fn apply_changeset(self, source: Capture) -> Capture {
+ let capture_update: CaptureUpdateInternal = self.into();
+ Capture {
+ status: capture_update.status.unwrap_or(source.status),
+ error_message: capture_update.error_message.or(source.error_message),
+ error_code: capture_update.error_code.or(source.error_code),
+ error_reason: capture_update.error_reason.or(source.error_reason),
+ modified_at: common_utils::date_time::now(),
+ ..source
+ }
+ }
+}
+
+impl From<CaptureUpdate> for CaptureUpdateInternal {
+ fn from(payment_attempt_child_update: CaptureUpdate) -> Self {
+ let now = Some(common_utils::date_time::now());
+ match payment_attempt_child_update {
+ CaptureUpdate::ResponseUpdate {
+ status,
+ connector_transaction_id,
+ } => Self {
+ status: Some(status),
+ connector_transaction_id,
+ modified_at: now,
+ ..Self::default()
+ },
+ CaptureUpdate::ErrorUpdate {
+ status,
+ error_code,
+ error_message,
+ error_reason,
+ } => Self {
+ status: Some(status),
+ error_code,
+ error_message,
+ error_reason,
+ modified_at: now,
+ ..Self::default()
+ },
+ }
+ }
+}
diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs
index 22e226a18ab..34f87e65520 100644
--- a/crates/diesel_models/src/enums.rs
+++ b/crates/diesel_models/src/enums.rs
@@ -2,10 +2,10 @@
pub mod diesel_exports {
pub use super::{
DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType,
- DbCaptureMethod as CaptureMethod, DbConnectorType as ConnectorType,
- DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDisputeStage as DisputeStage,
- DbDisputeStatus as DisputeStatus, DbEventClass as EventClass,
- DbEventObjectType as EventObjectType, DbEventType as EventType,
+ DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus,
+ DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency,
+ DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus,
+ DbEventClass as EventClass, DbEventObjectType as EventObjectType, DbEventType as EventType,
DbFraudCheckStatus as FraudCheckStatus, DbFraudCheckType as FraudCheckType,
DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus,
DbMandateStatus as MandateStatus, DbMandateType as MandateType,
diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs
index 6f277d90941..72eba52117b 100644
--- a/crates/diesel_models/src/lib.rs
+++ b/crates/diesel_models/src/lib.rs
@@ -1,5 +1,6 @@
pub mod address;
pub mod api_keys;
+pub mod capture;
pub mod cards_info;
pub mod configs;
pub mod connector_response;
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index 06e47a6fe3c..6ab17c34a06 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -53,6 +53,7 @@ pub struct PaymentAttempt {
// providing a location to store mandate details intermediately for transaction
pub mandate_details: Option<storage_enums::MandateDataType>,
pub error_reason: Option<String>,
+ pub multiple_capture_count: Option<i16>,
// reference to the payment at connector side
pub connector_response_reference_id: Option<String>,
}
@@ -112,6 +113,7 @@ pub struct PaymentAttemptNew {
pub mandate_details: Option<storage_enums::MandateDataType>,
pub error_reason: Option<String>,
pub connector_response_reference_id: Option<String>,
+ pub multiple_capture_count: Option<i16>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -191,6 +193,10 @@ pub enum PaymentAttemptUpdate {
error_message: Option<Option<String>>,
error_reason: Option<Option<String>>,
},
+ MultipleCaptureUpdate {
+ status: Option<storage_enums::AttemptStatus>,
+ multiple_capture_count: Option<i16>,
+ },
PreprocessingUpdate {
status: storage_enums::AttemptStatus,
payment_method_id: Option<Option<String>>,
@@ -230,6 +236,7 @@ pub struct PaymentAttemptUpdateInternal {
error_reason: Option<Option<String>>,
capture_method: Option<storage_enums::CaptureMethod>,
connector_response_reference_id: Option<String>,
+ multiple_capture_count: Option<i16>,
}
impl PaymentAttemptUpdate {
@@ -437,6 +444,14 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
connector_response_reference_id,
..Default::default()
},
+ PaymentAttemptUpdate::MultipleCaptureUpdate {
+ status,
+ multiple_capture_count,
+ } => Self {
+ status,
+ multiple_capture_count,
+ ..Default::default()
+ },
}
}
}
diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs
index 42825a983e1..ce24054080e 100644
--- a/crates/diesel_models/src/query.rs
+++ b/crates/diesel_models/src/query.rs
@@ -1,5 +1,6 @@
pub mod address;
pub mod api_keys;
+mod capture;
pub mod cards_info;
pub mod configs;
pub mod connector_response;
diff --git a/crates/diesel_models/src/query/capture.rs b/crates/diesel_models/src/query/capture.rs
new file mode 100644
index 00000000000..26623b01605
--- /dev/null
+++ b/crates/diesel_models/src/query/capture.rs
@@ -0,0 +1,78 @@
+use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table};
+use router_env::{instrument, tracing};
+
+use super::generics;
+use crate::{
+ capture::{Capture, CaptureNew, CaptureUpdate, CaptureUpdateInternal},
+ errors,
+ schema::captures::dsl,
+ PgPooledConn, StorageResult,
+};
+
+impl CaptureNew {
+ #[instrument(skip(conn))]
+ pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Capture> {
+ generics::generic_insert(conn, self).await
+ }
+}
+
+impl Capture {
+ #[instrument(skip(conn))]
+ pub async fn find_by_capture_id(conn: &PgPooledConn, capture_id: &str) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::capture_id.eq(capture_id.to_owned()),
+ )
+ .await
+ }
+ #[instrument(skip(conn))]
+ pub async fn update_with_capture_id(
+ self,
+ conn: &PgPooledConn,
+ capture: CaptureUpdate,
+ ) -> StorageResult<Self> {
+ match generics::generic_update_with_unique_predicate_get_result::<
+ <Self as HasTable>::Table,
+ _,
+ _,
+ _,
+ >(
+ conn,
+ dsl::capture_id.eq(self.capture_id.to_owned()),
+ CaptureUpdateInternal::from(capture),
+ )
+ .await
+ {
+ Err(error) => match error.current_context() {
+ errors::DatabaseError::NoFieldsToUpdate => Ok(self),
+ _ => Err(error),
+ },
+ result => result,
+ }
+ }
+
+ #[instrument(skip(conn))]
+ pub async fn find_all_by_merchant_id_payment_id_authorized_attempt_id(
+ merchant_id: &str,
+ payment_id: &str,
+ authorized_attempt_id: &str,
+ conn: &PgPooledConn,
+ ) -> StorageResult<Vec<Self>> {
+ generics::generic_filter::<
+ <Self as HasTable>::Table,
+ _,
+ <<Self as HasTable>::Table as Table>::PrimaryKey,
+ _,
+ >(
+ conn,
+ dsl::authorized_attempt_id
+ .eq(authorized_attempt_id.to_owned())
+ .and(dsl::merchant_id.eq(merchant_id.to_owned()))
+ .and(dsl::payment_id.eq(payment_id.to_owned())),
+ None,
+ None,
+ None,
+ )
+ .await
+ }
+}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 9a1eeeac45d..c70ad59cfd7 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -53,6 +53,39 @@ diesel::table! {
}
}
+diesel::table! {
+ use diesel::sql_types::*;
+ use crate::enums::diesel_exports::*;
+
+ captures (capture_id) {
+ #[max_length = 64]
+ capture_id -> Varchar,
+ #[max_length = 64]
+ payment_id -> Varchar,
+ #[max_length = 64]
+ merchant_id -> Varchar,
+ status -> CaptureStatus,
+ amount -> Int8,
+ currency -> Nullable<Currency>,
+ #[max_length = 255]
+ connector -> Nullable<Varchar>,
+ #[max_length = 255]
+ error_message -> Nullable<Varchar>,
+ #[max_length = 255]
+ error_code -> Nullable<Varchar>,
+ #[max_length = 255]
+ error_reason -> Nullable<Varchar>,
+ tax_amount -> Nullable<Int8>,
+ created_at -> Timestamp,
+ modified_at -> Timestamp,
+ #[max_length = 64]
+ authorized_attempt_id -> Varchar,
+ #[max_length = 128]
+ connector_transaction_id -> Nullable<Varchar>,
+ capture_sequence -> Int2,
+ }
+}
+
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
@@ -466,6 +499,7 @@ diesel::table! {
preprocessing_step_id -> Nullable<Varchar>,
mandate_details -> Nullable<Jsonb>,
error_reason -> Nullable<Text>,
+ multiple_capture_count -> Nullable<Int2>,
#[max_length = 128]
connector_response_reference_id -> Nullable<Varchar>,
}
@@ -718,6 +752,7 @@ diesel::table! {
diesel::allow_tables_to_appear_in_same_query!(
address,
api_keys,
+ captures,
cards_info,
configs,
connector_response,
diff --git a/crates/router/build.rs b/crates/router/build.rs
index db161588939..167ca918407 100644
--- a/crates/router/build.rs
+++ b/crates/router/build.rs
@@ -2,7 +2,7 @@ fn main() {
// Set thread stack size to 4 MiB for debug builds
// Reference: https://doc.rust-lang.org/std/thread/#stack-size
#[cfg(debug_assertions)]
- println!("cargo:rustc-env=RUST_MIN_STACK=4194304"); // 4 * 1024 * 1024 = 4 MiB
+ println!("cargo:rustc-env=RUST_MIN_STACK=6291456"); // 6 * 1024 * 1024 = 6 MiB
#[cfg(feature = "vergen")]
router_env::vergen::generate_cargo_instructions();
diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs
index 170e5bea595..8bc66328333 100644
--- a/crates/router/src/compatibility/stripe/payment_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs
@@ -387,11 +387,12 @@ impl From<api_enums::IntentStatus> for StripePaymentStatus {
api_enums::IntentStatus::Succeeded => Self::Succeeded,
api_enums::IntentStatus::Failed => Self::Canceled,
api_enums::IntentStatus::Processing => Self::Processing,
- api_enums::IntentStatus::RequiresCustomerAction => Self::RequiresAction,
- api_enums::IntentStatus::RequiresMerchantAction => Self::RequiresAction,
+ api_enums::IntentStatus::RequiresCustomerAction
+ | api_enums::IntentStatus::RequiresMerchantAction => Self::RequiresAction,
api_enums::IntentStatus::RequiresPaymentMethod => Self::RequiresPaymentMethod,
api_enums::IntentStatus::RequiresConfirmation => Self::RequiresConfirmation,
- api_enums::IntentStatus::RequiresCapture => Self::RequiresCapture,
+ api_enums::IntentStatus::RequiresCapture
+ | api_enums::IntentStatus::PartiallyCaptured => Self::RequiresCapture,
api_enums::IntentStatus::Cancelled => Self::Canceled,
}
}
diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs
index a7699323a40..896183da0d6 100644
--- a/crates/router/src/compatibility/stripe/setup_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs
@@ -308,7 +308,8 @@ impl From<api_enums::IntentStatus> for StripeSetupStatus {
api_enums::IntentStatus::RequiresMerchantAction => Self::RequiresAction,
api_enums::IntentStatus::RequiresPaymentMethod => Self::RequiresPaymentMethod,
api_enums::IntentStatus::RequiresConfirmation => Self::RequiresConfirmation,
- api_enums::IntentStatus::RequiresCapture => {
+ api_enums::IntentStatus::RequiresCapture
+ | api_enums::IntentStatus::PartiallyCaptured => {
logger::error!("Invalid status change");
Self::Canceled
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 90411677b63..9465bdf8a2b 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -6,7 +6,7 @@ pub mod operations;
pub mod tokenization;
pub mod transformers;
-use std::{fmt::Debug, marker::PhantomData, ops::Deref, time::Instant};
+use std::{collections::HashMap, fmt::Debug, marker::PhantomData, ops::Deref, time::Instant};
use api_models::payments::FrmMessage;
use common_utils::pii;
@@ -1082,6 +1082,7 @@ where
pub flow: PhantomData<F>,
pub payment_intent: storage::PaymentIntent,
pub payment_attempt: storage::PaymentAttempt,
+ pub multiple_capture_data: Option<MultipleCaptureData>,
pub connector_response: storage::ConnectorResponse,
pub amount: api::Amount,
pub mandate_id: Option<api_models::payments::MandateIds>,
@@ -1108,6 +1109,96 @@ where
pub frm_message: Option<FrmMessage>,
}
+#[derive(Clone)]
+pub struct MultipleCaptureData {
+ previous_captures: Vec<storage::Capture>,
+ current_capture: storage::Capture,
+}
+
+impl MultipleCaptureData {
+ fn get_previously_blocked_amount(&self) -> i64 {
+ self.previous_captures
+ .iter()
+ .fold(0, |accumulator, capture| {
+ accumulator
+ + match capture.status {
+ storage_enums::CaptureStatus::Charged
+ | storage_enums::CaptureStatus::Pending => capture.amount,
+ storage_enums::CaptureStatus::Started
+ | storage_enums::CaptureStatus::Failed => 0,
+ }
+ })
+ }
+ fn get_total_blocked_amount(&self) -> i64 {
+ self.get_previously_blocked_amount()
+ + match self.current_capture.status {
+ api_models::enums::CaptureStatus::Charged
+ | api_models::enums::CaptureStatus::Pending => self.current_capture.amount,
+ api_models::enums::CaptureStatus::Failed
+ | api_models::enums::CaptureStatus::Started => 0,
+ }
+ }
+ fn get_previously_charged_amount(&self) -> i64 {
+ self.previous_captures
+ .iter()
+ .fold(0, |accumulator, capture| {
+ accumulator
+ + match capture.status {
+ storage_enums::CaptureStatus::Charged => capture.amount,
+ storage_enums::CaptureStatus::Pending
+ | storage_enums::CaptureStatus::Started
+ | storage_enums::CaptureStatus::Failed => 0,
+ }
+ })
+ }
+ fn get_total_charged_amount(&self) -> i64 {
+ self.get_previously_charged_amount()
+ + match self.current_capture.status {
+ storage_enums::CaptureStatus::Charged => self.current_capture.amount,
+ storage_enums::CaptureStatus::Pending
+ | storage_enums::CaptureStatus::Started
+ | storage_enums::CaptureStatus::Failed => 0,
+ }
+ }
+ fn get_captures_count(&self) -> RouterResult<i16> {
+ i16::try_from(1 + self.previous_captures.len())
+ .into_report()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while converting from usize to i16")
+ }
+ fn get_status_count(&self) -> HashMap<storage_enums::CaptureStatus, i16> {
+ let mut hash_map: HashMap<storage_enums::CaptureStatus, i16> = HashMap::new();
+ hash_map.insert(storage_enums::CaptureStatus::Charged, 0);
+ hash_map.insert(storage_enums::CaptureStatus::Pending, 0);
+ hash_map.insert(storage_enums::CaptureStatus::Started, 0);
+ hash_map.insert(storage_enums::CaptureStatus::Failed, 0);
+ hash_map
+ .entry(self.current_capture.status)
+ .and_modify(|count| *count += 1);
+ self.previous_captures
+ .iter()
+ .fold(hash_map, |mut accumulator, capture| {
+ let current_capture_status = capture.status;
+ accumulator
+ .entry(current_capture_status)
+ .and_modify(|count| *count += 1);
+ accumulator
+ })
+ }
+ fn get_attempt_status(&self, authorized_amount: i64) -> storage_enums::AttemptStatus {
+ let total_captured_amount = self.get_total_charged_amount();
+ if authorized_amount == total_captured_amount {
+ return storage_enums::AttemptStatus::Charged;
+ }
+ let status_count_map = self.get_status_count();
+ if status_count_map.get(&storage_enums::CaptureStatus::Charged) > Some(&0) {
+ storage_enums::AttemptStatus::PartialCharged
+ } else {
+ storage_enums::AttemptStatus::CaptureInitiated
+ }
+ }
+}
+
#[derive(Debug, Default, Clone)]
pub struct RecurringMandatePaymentData {
pub payment_method_type: Option<storage_enums::PaymentMethodType>, //required for making recurring payment using saved payment method through stripe
@@ -1194,6 +1285,7 @@ pub fn should_call_connector<Op: Debug, F: Clone>(
matches!(
payment_data.payment_intent.status,
storage_enums::IntentStatus::RequiresCapture
+ | storage_enums::IntentStatus::PartiallyCaptured
)
}
"CompleteAuthorize" => true,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 78be0a15181..3954cc6a7ed 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1345,7 +1345,7 @@ pub(crate) fn validate_capture_method(
field_name: "capture_method".to_string(),
current_flow: "captured".to_string(),
current_value: capture_method.to_string(),
- states: "manual_single, manual_multiple, scheduled".to_string()
+ states: "manual, manual_multiple, scheduled".to_string()
}))
},
)
@@ -1354,13 +1354,14 @@ pub(crate) fn validate_capture_method(
#[instrument(skip_all)]
pub(crate) fn validate_status(status: storage_enums::IntentStatus) -> RouterResult<()> {
utils::when(
- status != storage_enums::IntentStatus::RequiresCapture,
+ status != storage_enums::IntentStatus::RequiresCapture
+ && status != storage_enums::IntentStatus::PartiallyCaptured,
|| {
Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState {
field_name: "payment.status".to_string(),
current_flow: "captured".to_string(),
current_value: status.to_string(),
- states: "requires_capture".to_string()
+ states: "requires_capture, partially captured".to_string()
}))
},
)
@@ -2488,6 +2489,7 @@ pub fn get_attempt_type(
}
enums::IntentStatus::Cancelled
| enums::IntentStatus::RequiresCapture
+ | enums::IntentStatus::PartiallyCaptured
| enums::IntentStatus::Processing
| enums::IntentStatus::Succeeded => {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
@@ -2577,6 +2579,7 @@ impl AttemptType {
mandate_details: old_payment_attempt.mandate_details,
preprocessing_step_id: None,
error_reason: None,
+ multiple_capture_count: None,
connector_response_reference_id: None,
}
}
@@ -2697,6 +2700,7 @@ pub fn is_manual_retry_allowed(
},
enums::IntentStatus::Cancelled
| enums::IntentStatus::RequiresCapture
+ | enums::IntentStatus::PartiallyCaptured
| enums::IntentStatus::Processing
| enums::IntentStatus::Succeeded => Some(false),
diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs
index e72e430285e..1a6dc8ee8e6 100644
--- a/crates/router/src/core/payments/operations/payment_cancel.rs
+++ b/crates/router/src/core/payments/operations/payment_cancel.rs
@@ -162,6 +162,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest>
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
+ multiple_capture_data: None,
redirect_response: None,
frm_message: None,
},
diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs
index 6f40bc95605..028b5c9a226 100644
--- a/crates/router/src/core/payments/operations/payment_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_capture.rs
@@ -3,6 +3,7 @@ use std::marker::PhantomData;
use api_models::enums::CancelTransaction;
use async_trait::async_trait;
use common_utils::ext_traits::AsyncExt;
+use diesel_models::connector_response::ConnectorResponse;
use error_stack::ResultExt;
use router_env::{instrument, tracing};
@@ -18,7 +19,7 @@ use crate::{
types::{
api::{self, PaymentIdTypeExt},
domain,
- storage::{self, enums},
+ storage::{self, enums, ConnectorResponseExt, PaymentAttemptExt},
},
utils::OptionExt,
};
@@ -84,20 +85,83 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu
helpers::validate_capture_method(capture_method)?;
+ let (multiple_capture_data, connector_response) =
+ if capture_method == enums::CaptureMethod::ManualMultiple {
+ let amount_to_capture = request
+ .amount_to_capture
+ .get_required_value("amount_to_capture")?;
+ let previous_captures = db
+ .find_all_captures_by_merchant_id_payment_id_authorized_attempt_id(
+ &payment_attempt.merchant_id,
+ &payment_attempt.payment_id,
+ &payment_attempt.attempt_id,
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ let previously_blocked_amount =
+ previous_captures.iter().fold(0, |accumulator, capture| {
+ accumulator
+ + match capture.status {
+ enums::CaptureStatus::Charged | enums::CaptureStatus::Pending => {
+ capture.amount
+ }
+ enums::CaptureStatus::Started | enums::CaptureStatus::Failed => 0,
+ }
+ });
+ helpers::validate_amount_to_capture(
+ payment_attempt.amount - previously_blocked_amount,
+ Some(amount_to_capture),
+ )?;
+
+ let capture = db
+ .insert_capture(
+ payment_attempt
+ .make_new_capture(amount_to_capture, enums::CaptureStatus::Started),
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::DuplicatePayment {
+ payment_id: payment_id.clone(),
+ })?;
+ let new_connector_response = db
+ .insert_connector_response(
+ ConnectorResponse::make_new_connector_response(
+ capture.payment_id.clone(),
+ capture.merchant_id.clone(),
+ capture.capture_id.clone(),
+ capture.connector.clone(),
+ ),
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::DuplicatePayment {
+ payment_id: payment_id.clone(),
+ })?;
+ (
+ Some(payments::MultipleCaptureData {
+ previous_captures,
+ current_capture: capture,
+ }),
+ new_connector_response,
+ )
+ } else {
+ let connector_response = db
+ .find_connector_response_by_payment_id_merchant_id_attempt_id(
+ &payment_attempt.payment_id,
+ &payment_attempt.merchant_id,
+ &payment_attempt.attempt_id,
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ (None, connector_response)
+ };
+
currency = payment_attempt.currency.get_required_value("currency")?;
amount = payment_attempt.amount.into();
- let connector_response = db
- .find_connector_response_by_payment_id_merchant_id_attempt_id(
- &payment_attempt.payment_id,
- &payment_attempt.merchant_id,
- &payment_attempt.attempt_id,
- storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
-
let shipping_address = helpers::get_address_for_payment_request(
db,
None,
@@ -167,6 +231,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
+ multiple_capture_data,
redirect_response: None,
frm_message: None,
},
@@ -182,10 +247,10 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRe
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
- _db: &dyn StorageInterface,
- payment_data: payments::PaymentData<F>,
+ db: &dyn StorageInterface,
+ mut payment_data: payments::PaymentData<F>,
_customer: Option<domain::Customer>,
- _storage_scheme: enums::MerchantStorageScheme,
+ storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_mechant_key_store: &domain::MerchantKeyStore,
_should_cancel_transaction: Option<CancelTransaction>,
@@ -196,6 +261,27 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRe
where
F: 'b + Send,
{
+ payment_data.payment_attempt = match &payment_data.multiple_capture_data {
+ Some(multiple_capture_data) => {
+ let mut updated_payment_attempt = db
+ .update_payment_attempt_with_attempt_id(
+ payment_data.payment_attempt,
+ storage::PaymentAttemptUpdate::MultipleCaptureUpdate {
+ status: None,
+ multiple_capture_count: Some(
+ multiple_capture_data.current_capture.capture_sequence,
+ ),
+ },
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ updated_payment_attempt.amount_to_capture =
+ Some(multiple_capture_data.current_capture.amount);
+ updated_payment_attempt
+ }
+ None => payment_data.payment_attempt,
+ };
Ok((Box::new(self), payment_data))
}
}
diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
index 6dc4e5a4d54..bab7c2cfc08 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -234,6 +234,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co
connector_customer_id: None,
recurring_mandate_payment_data,
ephemeral_key: None,
+ multiple_capture_data: None,
redirect_response,
frm_message: None,
},
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 53454f6e4d4..3349e9170f8 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -290,6 +290,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
connector_customer_id: None,
recurring_mandate_payment_data,
ephemeral_key: None,
+ multiple_capture_data: None,
redirect_response: None,
frm_message: None,
},
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index d5a9af98d67..810f5261501 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -269,6 +269,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
connector_customer_id: None,
recurring_mandate_payment_data,
ephemeral_key,
+ multiple_capture_data: None,
redirect_response: None,
frm_message: None,
},
diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs
index b3d7f59e2a7..d0860fd27e2 100644
--- a/crates/router/src/core/payments/operations/payment_method_validate.rs
+++ b/crates/router/src/core/payments/operations/payment_method_validate.rs
@@ -188,6 +188,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::VerifyRequest> for Paym
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
+ multiple_capture_data: None,
redirect_response: None,
frm_message: None,
},
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 2f03a28c299..870de1bfad8 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -16,7 +16,7 @@ use crate::{
types::{
self, api,
storage::{self, enums},
- transformers::ForeignInto,
+ transformers::{ForeignFrom, ForeignTryFrom},
},
utils,
};
@@ -295,22 +295,47 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
router_data: types::RouterData<F, T, types::PaymentsResponseData>,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentData<F>> {
- let (payment_attempt_update, connector_response_update) = match router_data.response.clone() {
- Err(err) => (
- Some(storage::PaymentAttemptUpdate::ErrorUpdate {
- connector: None,
- status: match err.status_code {
- 500..=511 => storage::enums::AttemptStatus::Pending,
- _ => storage::enums::AttemptStatus::Failure,
- },
- error_message: Some(Some(err.message)),
- error_code: Some(Some(err.code)),
- error_reason: Some(err.reason),
- }),
- Some(storage::ConnectorResponseUpdate::ErrorUpdate {
- connector_name: Some(router_data.connector.clone()),
- }),
- ),
+ let (capture_update, mut payment_attempt_update, connector_response_update) = match router_data
+ .response
+ .clone()
+ {
+ Err(err) => {
+ let (capture_update, attempt_update) = match payment_data.multiple_capture_data {
+ Some(_) => (
+ Some(storage::CaptureUpdate::ErrorUpdate {
+ status: match err.status_code {
+ 500..=511 => storage::enums::CaptureStatus::Pending,
+ _ => storage::enums::CaptureStatus::Failed,
+ },
+ error_code: Some(err.code),
+ error_message: Some(err.message),
+ error_reason: err.reason,
+ }),
+ // attempt status will depend on collective capture status
+ None,
+ ),
+ None => (
+ None,
+ Some(storage::PaymentAttemptUpdate::ErrorUpdate {
+ connector: None,
+ status: match err.status_code {
+ 500..=511 => storage::enums::AttemptStatus::Pending,
+ _ => storage::enums::AttemptStatus::Failure,
+ },
+ error_message: Some(Some(err.message)),
+ error_code: Some(Some(err.code)),
+ error_reason: Some(err.reason),
+ }),
+ ),
+ };
+ (
+ capture_update,
+ attempt_update,
+ Some(storage::ConnectorResponseUpdate::ErrorUpdate {
+ connector_name: Some(router_data.connector.clone()),
+ }),
+ )
+ }
Ok(payments_response) => match payments_response {
types::PaymentsResponseData::PreProcessingResponse {
pre_processing_id,
@@ -339,7 +364,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
connector_response_reference_id,
};
- (Some(payment_attempt_update), None)
+ (None, Some(payment_attempt_update), None)
}
types::PaymentsResponseData::TransactionResponse {
resource_id,
@@ -374,23 +399,38 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
metrics::SUCCESSFUL_PAYMENT.add(&metrics::CONTEXT, 1, &[]);
}
- let payment_attempt_update = storage::PaymentAttemptUpdate::ResponseUpdate {
- status: router_data.status,
- connector: None,
- connector_transaction_id: connector_transaction_id.clone(),
- authentication_type: None,
- payment_method_id: Some(router_data.payment_method_id),
- mandate_id: payment_data
- .mandate_id
- .clone()
- .map(|mandate| mandate.mandate_id),
- connector_metadata,
- payment_token: None,
- error_code: error_status.clone(),
- error_message: error_status.clone(),
- error_reason: error_status,
- connector_response_reference_id,
- };
+ let (capture_update, payment_attempt_update) =
+ match payment_data.multiple_capture_data {
+ Some(_) => (
+ //if payment_data.multiple_capture_data will be Some only for multiple partial capture.
+ Some(storage::CaptureUpdate::ResponseUpdate {
+ status: enums::CaptureStatus::foreign_try_from(router_data.status)?,
+ connector_transaction_id: connector_transaction_id.clone(),
+ }),
+ // attempt status will depend on collective capture status
+ None,
+ ),
+ None => (
+ None,
+ Some(storage::PaymentAttemptUpdate::ResponseUpdate {
+ status: router_data.status,
+ connector: None,
+ connector_transaction_id: connector_transaction_id.clone(),
+ authentication_type: None,
+ payment_method_id: Some(router_data.payment_method_id),
+ mandate_id: payment_data
+ .mandate_id
+ .clone()
+ .map(|mandate| mandate.mandate_id),
+ connector_metadata,
+ payment_token: None,
+ error_code: error_status.clone(),
+ error_message: error_status.clone(),
+ error_reason: error_status,
+ connector_response_reference_id,
+ }),
+ ),
+ };
let connector_response_update = storage::ConnectorResponseUpdate::ResponseUpdate {
connector_transaction_id,
@@ -400,7 +440,8 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
};
(
- Some(payment_attempt_update),
+ capture_update,
+ payment_attempt_update,
Some(connector_response_update),
)
}
@@ -415,6 +456,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
| types::ResponseId::EncodedData(id) => Some(id),
};
(
+ None,
Some(storage::PaymentAttemptUpdate::UnresolvedResponseUpdate {
status: router_data.status,
connector: None,
@@ -428,13 +470,38 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
None,
)
}
- types::PaymentsResponseData::SessionResponse { .. } => (None, None),
- types::PaymentsResponseData::SessionTokenResponse { .. } => (None, None),
- types::PaymentsResponseData::TokenizationResponse { .. } => (None, None),
- types::PaymentsResponseData::ConnectorCustomerResponse { .. } => (None, None),
- types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => (None, None),
+ types::PaymentsResponseData::SessionResponse { .. } => (None, None, None),
+ types::PaymentsResponseData::SessionTokenResponse { .. } => (None, None, None),
+ types::PaymentsResponseData::TokenizationResponse { .. } => (None, None, None),
+ types::PaymentsResponseData::ConnectorCustomerResponse { .. } => (None, None, None),
+ types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => (None, None, None),
},
};
+ payment_data.multiple_capture_data = match capture_update
+ .zip(payment_data.multiple_capture_data)
+ {
+ Some((capture_update, mut multiple_capture_data)) => {
+ let updated_capture = db
+ .update_capture_with_capture_id(
+ multiple_capture_data.current_capture,
+ capture_update,
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ multiple_capture_data.current_capture = updated_capture;
+
+ let authorized_amount = payment_data.payment_attempt.amount;
+
+ payment_attempt_update = Some(storage::PaymentAttemptUpdate::MultipleCaptureUpdate {
+ status: Some(multiple_capture_data.get_attempt_status(authorized_amount)),
+ multiple_capture_count: Some(multiple_capture_data.get_captures_count()?),
+ });
+ Some(multiple_capture_data)
+ }
+ None => None,
+ };
payment_data.payment_attempt = match payment_attempt_update {
Some(payment_attempt_update) => db
@@ -459,24 +526,18 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?,
None => payment_data.connector_response,
};
- let amount = router_data.request.get_capture_amount();
-
- let amount_captured = router_data.amount_captured.or_else(|| {
- if router_data.status == enums::AttemptStatus::Charged {
- amount
- } else {
- None
- }
- });
+ let amount_captured = get_total_amount_captured(
+ router_data.request,
+ router_data.amount_captured,
+ router_data.status,
+ &payment_data,
+ );
let payment_intent_update = match &router_data.response {
- Err(err) => storage::PaymentIntentUpdate::PGStatusUpdate {
- status: match err.status_code {
- 500..=511 => enums::IntentStatus::Processing,
- _ => enums::IntentStatus::Failed,
- },
+ Err(_) => storage::PaymentIntentUpdate::PGStatusUpdate {
+ status: enums::IntentStatus::foreign_from(payment_data.payment_attempt.status),
},
Ok(_) => storage::PaymentIntentUpdate::ResponseUpdate {
- status: router_data.status.foreign_into(),
+ status: enums::IntentStatus::foreign_from(payment_data.payment_attempt.status),
return_url: router_data.return_url.clone(),
amount_captured,
},
@@ -502,3 +563,28 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
Ok(payment_data)
}
+
+fn get_total_amount_captured<F: Clone, T: types::Capturable>(
+ request: T,
+ amount_captured: Option<i64>,
+ router_data_status: enums::AttemptStatus,
+ payment_data: &PaymentData<F>,
+) -> Option<i64> {
+ match &payment_data.multiple_capture_data {
+ Some(multiple_capture_data) => {
+ //multiple capture
+ Some(multiple_capture_data.get_total_blocked_amount())
+ }
+ None => {
+ //Non multiple capture
+ let amount = request.get_capture_amount();
+ amount_captured.or_else(|| {
+ if router_data_status == enums::AttemptStatus::Charged {
+ amount
+ } else {
+ None
+ }
+ })
+ }
+ }
+}
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 88e9c6184f6..f795e4b439a 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -179,6 +179,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest>
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
+ multiple_capture_data: None,
redirect_response: None,
frm_message: None,
},
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index 3610926cea6..03eb5294b13 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -152,6 +152,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
+ multiple_capture_data: None,
redirect_response: None,
frm_message: None,
},
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index abf56937138..bbb9b72765d 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -353,6 +353,7 @@ async fn get_tracker_for_sync<
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
+ multiple_capture_data: None,
redirect_response: None,
frm_message,
},
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 57c8d583c81..61b9afce8b5 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -338,6 +338,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
connector_customer_id: None,
recurring_mandate_payment_data,
ephemeral_key: None,
+ multiple_capture_data: None,
redirect_response: None,
frm_message: None,
},
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 04a0848aba4..9f34255ae1e 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -943,6 +943,10 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCaptureD
.ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?,
payment_amount: payment_data.amount.into(),
connector_meta: payment_data.payment_attempt.connector_metadata,
+ capture_method: payment_data
+ .payment_attempt
+ .capture_method
+ .unwrap_or_default(),
})
}
}
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index 00669d9ce78..7e20d1dae7e 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -1,6 +1,7 @@
pub mod address;
pub mod api_keys;
pub mod cache;
+pub mod capture;
pub mod cards_info;
pub mod configs;
pub mod connector_response;
@@ -49,6 +50,7 @@ pub trait StorageInterface:
+ address::AddressInterface
+ api_keys::ApiKeyInterface
+ configs::ConfigInterface
+ + capture::CaptureInterface
+ connector_response::ConnectorResponseInterface
+ customers::CustomerInterface
+ dispute::DisputeInterface
@@ -122,6 +124,7 @@ pub struct MockDb {
disputes: Arc<Mutex<Vec<storage::Dispute>>>,
lockers: Arc<Mutex<Vec<storage::LockerMockUp>>>,
mandates: Arc<Mutex<Vec<storage::Mandate>>>,
+ captures: Arc<Mutex<Vec<storage::Capture>>>,
merchant_key_store: Arc<Mutex<Vec<storage::MerchantKeyStore>>>,
}
@@ -147,6 +150,7 @@ impl MockDb {
disputes: Default::default(),
lockers: Default::default(),
mandates: Default::default(),
+ captures: Default::default(),
merchant_key_store: Default::default(),
}
}
diff --git a/crates/router/src/db/capture.rs b/crates/router/src/db/capture.rs
new file mode 100644
index 00000000000..41840e1ec3b
--- /dev/null
+++ b/crates/router/src/db/capture.rs
@@ -0,0 +1,220 @@
+use super::MockDb;
+use crate::{
+ core::errors::{self, CustomResult},
+ types::storage::{self as types, enums},
+};
+
+#[async_trait::async_trait]
+pub trait CaptureInterface {
+ async fn insert_capture(
+ &self,
+ capture: types::CaptureNew,
+ storage_scheme: enums::MerchantStorageScheme,
+ ) -> CustomResult<types::Capture, errors::StorageError>;
+
+ async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id(
+ &self,
+ merchant_id: &str,
+ payment_id: &str,
+ authorized_attempt_id: &str,
+ storage_scheme: enums::MerchantStorageScheme,
+ ) -> CustomResult<Vec<types::Capture>, errors::StorageError>;
+
+ async fn update_capture_with_capture_id(
+ &self,
+ this: types::Capture,
+ capture: types::CaptureUpdate,
+ storage_scheme: enums::MerchantStorageScheme,
+ ) -> CustomResult<types::Capture, errors::StorageError>;
+}
+
+#[cfg(feature = "kv_store")]
+mod storage {
+ use error_stack::IntoReport;
+
+ use super::CaptureInterface;
+ use crate::{
+ connection,
+ core::errors::{self, CustomResult},
+ services::Store,
+ types::storage::{capture::*, enums},
+ };
+
+ #[async_trait::async_trait]
+ impl CaptureInterface for Store {
+ async fn insert_capture(
+ &self,
+ capture: CaptureNew,
+ _storage_scheme: enums::MerchantStorageScheme,
+ ) -> CustomResult<Capture, errors::StorageError> {
+ let db_call = || async {
+ let conn = connection::pg_connection_write(self).await?;
+ capture
+ .insert(&conn)
+ .await
+ .map_err(Into::into)
+ .into_report()
+ };
+ db_call().await
+ }
+
+ async fn update_capture_with_capture_id(
+ &self,
+ this: Capture,
+ capture: CaptureUpdate,
+ _storage_scheme: enums::MerchantStorageScheme,
+ ) -> CustomResult<Capture, errors::StorageError> {
+ let db_call = || async {
+ let conn = connection::pg_connection_write(self).await?;
+ this.update_with_capture_id(&conn, capture)
+ .await
+ .map_err(Into::into)
+ .into_report()
+ };
+ db_call().await
+ }
+
+ async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id(
+ &self,
+ merchant_id: &str,
+ payment_id: &str,
+ authorized_attempt_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
+ ) -> CustomResult<Vec<Capture>, errors::StorageError> {
+ let db_call = || async {
+ let conn = connection::pg_connection_read(self).await?;
+ Capture::find_all_by_merchant_id_payment_id_authorized_attempt_id(
+ merchant_id,
+ payment_id,
+ authorized_attempt_id,
+ &conn,
+ )
+ .await
+ .map_err(Into::into)
+ .into_report()
+ };
+ db_call().await
+ }
+ }
+}
+
+#[cfg(not(feature = "kv_store"))]
+mod storage {
+ use error_stack::IntoReport;
+
+ use super::CaptureInterface;
+ use crate::{
+ connection,
+ core::errors::{self, CustomResult},
+ services::Store,
+ types::storage::{capture::*, enums},
+ };
+
+ #[async_trait::async_trait]
+ impl CaptureInterface for Store {
+ async fn insert_capture(
+ &self,
+ capture: CaptureNew,
+ _storage_scheme: enums::MerchantStorageScheme,
+ ) -> CustomResult<Capture, errors::StorageError> {
+ let db_call = || async {
+ let conn = connection::pg_connection_write(self).await?;
+ capture
+ .insert(&conn)
+ .await
+ .map_err(Into::into)
+ .into_report()
+ };
+ db_call().await
+ }
+
+ async fn update_capture_with_capture_id(
+ &self,
+ this: Capture,
+ capture: CaptureUpdate,
+ _storage_scheme: enums::MerchantStorageScheme,
+ ) -> CustomResult<Capture, errors::StorageError> {
+ let db_call = || async {
+ let conn = connection::pg_connection_write(self).await?;
+ this.update_with_capture_id(&conn, capture)
+ .await
+ .map_err(Into::into)
+ .into_report()
+ };
+ db_call().await
+ }
+
+ async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id(
+ &self,
+ merchant_id: &str,
+ payment_id: &str,
+ authorized_attempt_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
+ ) -> CustomResult<Vec<Capture>, errors::StorageError> {
+ let db_call = || async {
+ let conn = connection::pg_connection_read(self).await?;
+ Capture::find_all_by_merchant_id_payment_id_authorized_attempt_id(
+ merchant_id,
+ payment_id,
+ authorized_attempt_id,
+ &conn,
+ )
+ .await
+ .map_err(Into::into)
+ .into_report()
+ };
+ db_call().await
+ }
+ }
+}
+
+#[async_trait::async_trait]
+impl CaptureInterface for MockDb {
+ async fn insert_capture(
+ &self,
+ capture: types::CaptureNew,
+ _storage_scheme: enums::MerchantStorageScheme,
+ ) -> CustomResult<types::Capture, errors::StorageError> {
+ let mut captures = self.captures.lock().await;
+ let capture = types::Capture {
+ capture_id: capture.capture_id,
+ payment_id: capture.payment_id,
+ merchant_id: capture.merchant_id,
+ status: capture.status,
+ amount: capture.amount,
+ currency: capture.currency,
+ connector: capture.connector,
+ error_message: capture.error_message,
+ error_code: capture.error_code,
+ error_reason: capture.error_reason,
+ tax_amount: capture.tax_amount,
+ created_at: capture.created_at,
+ modified_at: capture.modified_at,
+ authorized_attempt_id: capture.authorized_attempt_id,
+ capture_sequence: capture.capture_sequence,
+ connector_transaction_id: capture.connector_transaction_id,
+ };
+ captures.push(capture.clone());
+ Ok(capture)
+ }
+
+ async fn update_capture_with_capture_id(
+ &self,
+ _this: types::Capture,
+ _capture: types::CaptureUpdate,
+ _storage_scheme: enums::MerchantStorageScheme,
+ ) -> CustomResult<types::Capture, errors::StorageError> {
+ //Implement function for `MockDb`
+ Err(errors::StorageError::MockDbError)?
+ }
+ async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id(
+ &self,
+ _merchant_id: &str,
+ _payment_id: &str,
+ _authorized_attempt_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
+ ) -> CustomResult<Vec<types::Capture>, errors::StorageError> {
+ //Implement function for `MockDb`
+ Err(errors::StorageError::MockDbError)?
+ }
+}
diff --git a/crates/router/src/db/payment_attempt.rs b/crates/router/src/db/payment_attempt.rs
index 702463aba79..7230fa78949 100644
--- a/crates/router/src/db/payment_attempt.rs
+++ b/crates/router/src/db/payment_attempt.rs
@@ -365,6 +365,7 @@ impl PaymentAttemptInterface for MockDb {
mandate_details: payment_attempt.mandate_details,
preprocessing_step_id: payment_attempt.preprocessing_step_id,
error_reason: payment_attempt.error_reason,
+ multiple_capture_count: payment_attempt.multiple_capture_count,
connector_response_reference_id: None,
};
payment_attempts.push(payment_attempt.clone());
@@ -504,6 +505,7 @@ mod storage {
mandate_details: payment_attempt.mandate_details.clone(),
preprocessing_step_id: payment_attempt.preprocessing_step_id.clone(),
error_reason: payment_attempt.error_reason.clone(),
+ multiple_capture_count: payment_attempt.multiple_capture_count,
connector_response_reference_id: None,
};
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index cdb9ebd6e54..9c1e8b0b6d8 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -330,6 +330,7 @@ pub struct PaymentsCaptureData {
pub currency: storage_enums::Currency,
pub connector_transaction_id: String,
pub payment_amount: i64,
+ pub capture_method: storage_enums::CaptureMethod,
pub connector_meta: Option<serde_json::Value>,
}
diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs
index 0b66ac7d8a0..46e3eac5fbf 100644
--- a/crates/router/src/types/storage.rs
+++ b/crates/router/src/types/storage.rs
@@ -1,5 +1,6 @@
pub mod address;
pub mod api_keys;
+pub mod capture;
pub mod cards_info;
pub mod configs;
pub mod connector_response;
@@ -27,8 +28,8 @@ pub mod refund;
pub mod reverse_lookup;
pub use self::{
- address::*, api_keys::*, cards_info::*, configs::*, connector_response::*, customers::*,
- dispute::*, ephemeral_key::*, events::*, file::*, locker_mock_up::*, mandate::*,
+ address::*, api_keys::*, capture::*, cards_info::*, configs::*, connector_response::*,
+ customers::*, dispute::*, ephemeral_key::*, events::*, file::*, locker_mock_up::*, mandate::*,
merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_attempt::*,
payment_intent::*, payment_method::*, payout_attempt::*, payouts::*, process_tracker::*,
refund::*, reverse_lookup::*,
diff --git a/crates/router/src/types/storage/capture.rs b/crates/router/src/types/storage/capture.rs
new file mode 100644
index 00000000000..7e093e9a747
--- /dev/null
+++ b/crates/router/src/types/storage/capture.rs
@@ -0,0 +1 @@
+pub use diesel_models::capture::*;
diff --git a/crates/router/src/types/storage/connector_response.rs b/crates/router/src/types/storage/connector_response.rs
index e5780c3c06c..1017d406a99 100644
--- a/crates/router/src/types/storage/connector_response.rs
+++ b/crates/router/src/types/storage/connector_response.rs
@@ -2,3 +2,34 @@ pub use diesel_models::connector_response::{
ConnectorResponse, ConnectorResponseNew, ConnectorResponseUpdate,
ConnectorResponseUpdateInternal,
};
+
+pub trait ConnectorResponseExt {
+ fn make_new_connector_response(
+ payment_id: String,
+ merchant_id: String,
+ attempt_id: String,
+ connector: Option<String>,
+ ) -> ConnectorResponseNew;
+}
+
+impl ConnectorResponseExt for ConnectorResponse {
+ fn make_new_connector_response(
+ payment_id: String,
+ merchant_id: String,
+ attempt_id: String,
+ connector: Option<String>,
+ ) -> ConnectorResponseNew {
+ let now = common_utils::date_time::now();
+ ConnectorResponseNew {
+ payment_id,
+ merchant_id,
+ attempt_id,
+ created_at: now,
+ modified_at: now,
+ connector_name: connector,
+ connector_transaction_id: None,
+ authentication_data: None,
+ encoded_data: None,
+ }
+ }
+}
diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs
index 4bc7d3d1104..76134ee8cbc 100644
--- a/crates/router/src/types/storage/payment_attempt.rs
+++ b/crates/router/src/types/storage/payment_attempt.rs
@@ -1,6 +1,7 @@
pub use diesel_models::payment_attempt::{
PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate, PaymentAttemptUpdateInternal,
};
+use diesel_models::{capture::CaptureNew, enums};
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingData {
@@ -11,6 +12,49 @@ pub struct RoutingData {
#[cfg(feature = "kv_store")]
impl crate::utils::storage_partitioning::KvStorePartition for PaymentAttempt {}
+pub trait PaymentAttemptExt {
+ fn make_new_capture(
+ &self,
+ capture_amount: i64,
+ capture_status: enums::CaptureStatus,
+ ) -> CaptureNew;
+
+ fn get_next_capture_id(&self) -> String;
+}
+
+impl PaymentAttemptExt for PaymentAttempt {
+ fn make_new_capture(
+ &self,
+ capture_amount: i64,
+ capture_status: enums::CaptureStatus,
+ ) -> CaptureNew {
+ let capture_sequence = self.multiple_capture_count.unwrap_or_default() + 1;
+ let now = common_utils::date_time::now();
+ CaptureNew {
+ payment_id: self.payment_id.clone(),
+ merchant_id: self.merchant_id.clone(),
+ capture_id: self.get_next_capture_id(),
+ status: capture_status,
+ amount: capture_amount,
+ currency: self.currency,
+ connector: self.connector.clone(),
+ error_message: None,
+ tax_amount: None,
+ created_at: now,
+ modified_at: now,
+ error_code: None,
+ error_reason: None,
+ authorized_attempt_id: self.attempt_id.clone(),
+ capture_sequence,
+ connector_transaction_id: None,
+ }
+ }
+ fn get_next_capture_id(&self) -> String {
+ let next_sequence_number = self.multiple_capture_count.unwrap_or_default() + 1;
+ format!("{}_{}", self.attempt_id.clone(), next_sequence_number)
+ }
+}
+
#[cfg(test)]
#[cfg(feature = "dummy_connector")]
mod tests {
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 16eac03ac18..80574fe9462 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -76,8 +76,8 @@ impl ForeignFrom<storage_enums::AttemptStatus> for storage_enums::IntentStatus {
}
storage_enums::AttemptStatus::Unresolved => Self::RequiresMerchantAction,
- storage_enums::AttemptStatus::PartialCharged
- | storage_enums::AttemptStatus::Started
+ storage_enums::AttemptStatus::PartialCharged => Self::PartiallyCaptured,
+ storage_enums::AttemptStatus::Started
| storage_enums::AttemptStatus::AuthenticationSuccessful
| storage_enums::AttemptStatus::Authorizing
| storage_enums::AttemptStatus::CodInitiated
@@ -96,6 +96,45 @@ impl ForeignFrom<storage_enums::AttemptStatus> for storage_enums::IntentStatus {
}
}
+impl ForeignTryFrom<storage_enums::AttemptStatus> for storage_enums::CaptureStatus {
+ type Error = error_stack::Report<errors::ApiErrorResponse>;
+
+ fn foreign_try_from(
+ attempt_status: storage_enums::AttemptStatus,
+ ) -> errors::RouterResult<Self> {
+ match attempt_status {
+ storage_enums::AttemptStatus::Charged
+ | storage_enums::AttemptStatus::PartialCharged => Ok(Self::Charged),
+ storage_enums::AttemptStatus::Pending
+ | storage_enums::AttemptStatus::CaptureInitiated => Ok(Self::Pending),
+ storage_enums::AttemptStatus::Failure
+ | storage_enums::AttemptStatus::CaptureFailed => Ok(Self::Failed),
+
+ storage_enums::AttemptStatus::Started
+ | storage_enums::AttemptStatus::AuthenticationFailed
+ | storage_enums::AttemptStatus::RouterDeclined
+ | storage_enums::AttemptStatus::AuthenticationPending
+ | storage_enums::AttemptStatus::AuthenticationSuccessful
+ | storage_enums::AttemptStatus::Authorized
+ | storage_enums::AttemptStatus::AuthorizationFailed
+ | storage_enums::AttemptStatus::Authorizing
+ | storage_enums::AttemptStatus::CodInitiated
+ | storage_enums::AttemptStatus::Voided
+ | storage_enums::AttemptStatus::VoidInitiated
+ | storage_enums::AttemptStatus::VoidFailed
+ | storage_enums::AttemptStatus::AutoRefunded
+ | storage_enums::AttemptStatus::Unresolved
+ | storage_enums::AttemptStatus::PaymentMethodAwaited
+ | storage_enums::AttemptStatus::ConfirmationAwaited
+ | storage_enums::AttemptStatus::DeviceDataCollectionPending => {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "AttemptStatus must be one of these for multiple partial captures [Charged, PartialCharged, Pending, CaptureInitiated, Failure, CaptureFailed]".into(),
+ }.into())
+ }
+ }
+ }
+}
+
impl ForeignFrom<api_models::payments::MandateType> for storage_enums::MandateDataType {
fn foreign_from(from: api_models::payments::MandateType) -> Self {
match from {
diff --git a/migrations/2023-07-07-091223_create_captures_table/down.sql b/migrations/2023-07-07-091223_create_captures_table/down.sql
new file mode 100644
index 00000000000..b0795cc2ce6
--- /dev/null
+++ b/migrations/2023-07-07-091223_create_captures_table/down.sql
@@ -0,0 +1,15 @@
+
+DROP INDEX captures_merchant_id_payment_id_authorized_attempt_id_index;
+DROP INDEX captures_connector_transaction_id_index;
+
+DROP TABLE captures;
+DROP TYPE "CaptureStatus";
+
+DELETE FROM pg_enum
+WHERE enumlabel = 'partially_captured'
+AND enumtypid = (
+ SELECT oid FROM pg_type WHERE typname = 'IntentStatus'
+);
+
+ALTER TABLE payment_attempt
+DROP COLUMN multiple_capture_count;
\ No newline at end of file
diff --git a/migrations/2023-07-07-091223_create_captures_table/up.sql b/migrations/2023-07-07-091223_create_captures_table/up.sql
new file mode 100644
index 00000000000..d477931a2bb
--- /dev/null
+++ b/migrations/2023-07-07-091223_create_captures_table/up.sql
@@ -0,0 +1,38 @@
+
+CREATE TYPE "CaptureStatus" AS ENUM (
+ 'started',
+ 'charged',
+ 'pending',
+ 'failed'
+);
+ALTER TYPE "IntentStatus" ADD VALUE If NOT EXISTS 'partially_captured' AFTER 'requires_capture';
+CREATE TABLE captures(
+ capture_id VARCHAR(64) NOT NULL PRIMARY KEY,
+ payment_id VARCHAR(64) NOT NULL,
+ merchant_id VARCHAR(64) NOT NULL,
+ status "CaptureStatus" NOT NULL,
+ amount BIGINT NOT NULL,
+ currency "Currency",
+ connector VARCHAR(255),
+ error_message VARCHAR(255),
+ error_code VARCHAR(255),
+ error_reason VARCHAR(255),
+ tax_amount BIGINT,
+ created_at TIMESTAMP NOT NULL,
+ modified_at TIMESTAMP NOT NULL,
+ authorized_attempt_id VARCHAR(64) NOT NULL,
+ connector_transaction_id VARCHAR(128),
+ capture_sequence SMALLINT NOT NULL
+);
+
+CREATE INDEX captures_merchant_id_payment_id_authorized_attempt_id_index ON captures (
+ merchant_id,
+ payment_id,
+ authorized_attempt_id
+);
+CREATE INDEX captures_connector_transaction_id_index ON captures (
+ connector_transaction_id
+);
+
+ALTER TABLE payment_attempt
+ADD COLUMN multiple_capture_count SMALLINT; --number of captures available for this payment attempt in captures table
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 948ed7518ad..ac28e9563d4 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -5484,7 +5484,8 @@
"requires_merchant_action",
"requires_payment_method",
"requires_confirmation",
- "requires_capture"
+ "requires_capture",
+ "partially_captured"
]
},
"KakaoPayRedirection": {
|
feat
|
add support for multiple partial capture (#1721)
|
d6a3e508e28af74146ee38178f33f162274324f1
|
2022-12-19 18:43:04
|
ItsMeShashank
|
feat(router): add straight-through routing connector selection in payments (#153)
| false
|
diff --git a/add_connector.md b/add_connector.md
index 7ef93e82ce6..14868530fb0 100644
--- a/add_connector.md
+++ b/add_connector.md
@@ -293,7 +293,7 @@ Feel free to connect with us in case of queries and also if you want to confirm
Add connector name in :
-- `crates/router/src/types/connector.rs` in Connector enum
+- `crates/api_models/src/enums.rs` in Connector enum (in alphabetical order)
- `crates/router/src/types/api/mod.rs` convert_connector function
Configure the Connectors API credentials using the PaymentConnectors API.
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 01b79e688e1..9da929e51c8 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -468,6 +468,34 @@ pub enum MandateStatus {
Revoked,
}
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Default,
+ Eq,
+ PartialEq,
+ serde::Deserialize,
+ serde::Serialize,
+ strum::Display,
+ strum::EnumString,
+ frunk::LabelledGeneric,
+)]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum Connector {
+ Aci,
+ Adyen,
+ Applepay,
+ Authorizedotnet,
+ Braintree,
+ Checkout,
+ #[default]
+ Dummy,
+ Klarna,
+ Stripe,
+}
+
impl From<AttemptStatus> for IntentStatus {
fn from(s: AttemptStatus) -> Self {
match s {
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 5b2ff66c609..f4d2131a802 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -22,6 +22,7 @@ pub struct PaymentsRequest {
pub merchant_id: Option<String>,
#[serde(default, deserialize_with = "amount::deserialize_option")]
pub amount: Option<Amount>,
+ pub connector: Option<api_enums::Connector>,
pub currency: Option<String>,
pub capture_method: Option<api_enums::CaptureMethod>,
pub amount_to_capture: Option<i64>,
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs
index 65b411be7a7..3790e6d95d0 100644
--- a/crates/router/src/compatibility/stripe/errors.rs
+++ b/crates/router/src/compatibility/stripe/errors.rs
@@ -349,6 +349,7 @@ impl From<ApiErrorResponse> for ErrorCode {
ApiErrorResponse::RefundFailed { data } => ErrorCode::RefundFailed, // Nothing at stripe to map
ApiErrorResponse::InternalServerError => ErrorCode::InternalServerError, // not a stripe code
+ ApiErrorResponse::IncorrectConnectorNameGiven => ErrorCode::InternalServerError,
ApiErrorResponse::MandateActive => ErrorCode::MandateActive, //not a stripe code
ApiErrorResponse::CustomerRedacted => ErrorCode::CustomerRedacted, //not a stripe code
ApiErrorResponse::DuplicateRefundRequest => ErrorCode::DuplicateRefundRequest,
diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs
index 60bb699a005..3cead5fd8ca 100644
--- a/crates/router/src/compatibility/stripe/payment_intents.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents.rs
@@ -47,12 +47,14 @@ pub async fn payment_intents_create(
&req,
create_payment_req,
|state, merchant_account, req| {
+ let connector = req.connector;
payments::payments_core::<Authorize, api_types::PaymentsResponse, _, _, _>(
state,
merchant_account,
payments::PaymentCreate,
req,
api::AuthFlow::Merchant,
+ connector,
payments::CallConnectorAction::Trigger,
)
},
@@ -101,6 +103,7 @@ pub async fn payment_intents_retrieve(
payments::PaymentStatus,
payload,
auth_flow,
+ None,
payments::CallConnectorAction::Trigger,
)
},
@@ -149,12 +152,14 @@ pub async fn payment_intents_update(
&req,
payload,
|state, merchant_account, req| {
+ let connector = req.connector;
payments::payments_core::<Authorize, api_types::PaymentsResponse, _, _, _>(
state,
merchant_account,
payments::PaymentUpdate,
req,
auth_flow,
+ connector,
payments::CallConnectorAction::Trigger,
)
},
@@ -204,12 +209,14 @@ pub async fn payment_intents_confirm(
&req,
payload,
|state, merchant_account, req| {
+ let connector = req.connector;
payments::payments_core::<Authorize, api_types::PaymentsResponse, _, _, _>(
state,
merchant_account,
payments::PaymentConfirm,
req,
auth_flow,
+ connector,
payments::CallConnectorAction::Trigger,
)
},
@@ -257,6 +264,7 @@ pub async fn payment_intents_capture(
payments::PaymentCapture,
payload,
api::AuthFlow::Merchant,
+ None,
payments::CallConnectorAction::Trigger,
)
},
@@ -310,6 +318,7 @@ pub async fn payment_intents_cancel(
payments::PaymentCancel,
req,
auth_flow,
+ None,
payments::CallConnectorAction::Trigger,
)
},
diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs
index f4cf0933d73..8738d66d717 100644
--- a/crates/router/src/compatibility/stripe/payment_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs
@@ -114,6 +114,7 @@ impl From<Shipping> for Address {
#[derive(Default, PartialEq, Eq, Deserialize, Clone)]
pub(crate) struct StripePaymentIntentRequest {
pub(crate) amount: Option<i64>, //amount in cents, hence passed as integer
+ pub(crate) connector: Option<api_enums::Connector>,
pub(crate) currency: Option<String>,
#[serde(rename = "amount_to_capture")]
pub(crate) amount_capturable: Option<i64>,
@@ -137,6 +138,7 @@ impl From<StripePaymentIntentRequest> for PaymentsRequest {
fn from(item: StripePaymentIntentRequest) -> Self {
PaymentsRequest {
amount: item.amount.map(|amount| amount.into()),
+ connector: item.connector,
currency: item.currency.as_ref().map(|c| c.to_uppercase()),
capture_method: item.capture_method,
amount_to_capture: item.amount_capturable,
diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rs
index bf410e19307..6a0cec28bea 100644
--- a/crates/router/src/compatibility/stripe/setup_intents.rs
+++ b/crates/router/src/compatibility/stripe/setup_intents.rs
@@ -43,12 +43,14 @@ pub async fn setup_intents_create(
&req,
create_payment_req,
|state, merchant_account, req| {
+ let connector = req.connector;
payments::payments_core::<Verify, api_types::PaymentsResponse, _, _, _>(
state,
merchant_account,
payments::PaymentCreate,
req,
api::AuthFlow::Merchant,
+ connector,
payments::CallConnectorAction::Trigger,
)
},
@@ -97,6 +99,7 @@ pub async fn setup_intents_retrieve(
payments::PaymentStatus,
payload,
auth_flow,
+ None,
payments::CallConnectorAction::Trigger,
)
},
@@ -145,12 +148,14 @@ pub async fn setup_intents_update(
&req,
payload,
|state, merchant_account, req| {
+ let connector = req.connector;
payments::payments_core::<Verify, api_types::PaymentsResponse, _, _, _>(
state,
merchant_account,
payments::PaymentUpdate,
req,
auth_flow,
+ connector,
payments::CallConnectorAction::Trigger,
)
},
@@ -200,12 +205,14 @@ pub async fn setup_intents_confirm(
&req,
payload,
|state, merchant_account, req| {
+ let connector = req.connector;
payments::payments_core::<Verify, api_types::PaymentsResponse, _, _, _>(
state,
merchant_account,
payments::PaymentConfirm,
req,
auth_flow,
+ connector,
payments::CallConnectorAction::Trigger,
)
},
diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs
index bfeabd7b1da..95f631953e9 100644
--- a/crates/router/src/core/errors/api_error_response.rs
+++ b/crates/router/src/core/errors/api_error_response.rs
@@ -123,6 +123,8 @@ pub enum ApiErrorResponse {
PaymentNotSucceeded,
#[error(error_type= ErrorType::ObjectNotFound, code = "RE_05", message = "Successful payment not found for the given payment id")]
SuccessfulPaymentNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "RE_05", message = "The connector provided in the request is incorrect or not available")]
+ IncorrectConnectorNameGiven,
#[error(error_type = ErrorType::ObjectNotFound, code = "RE_05", message = "Address does not exist in our records.")]
AddressNotFound,
#[error(error_type = ErrorType::ValidationError, code = "RE_03", message = "Mandate Validation Failed" )]
@@ -183,6 +185,7 @@ impl actix_web::ResponseError for ApiErrorResponse {
| ApiErrorResponse::ClientSecretNotGiven
| ApiErrorResponse::ClientSecretInvalid
| ApiErrorResponse::SuccessfulPaymentNotFound
+ | ApiErrorResponse::IncorrectConnectorNameGiven
| ApiErrorResponse::ResourceIdNotFound
| ApiErrorResponse::AddressNotFound => StatusCode::BAD_REQUEST, // 400
ApiErrorResponse::DuplicateMerchantAccount
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 3b7a9e75ee4..337a0c84009 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -25,15 +25,14 @@ use crate::{
payments,
},
db::StorageInterface,
- logger,
- pii::{Email, Secret},
+ logger, pii,
routes::AppState,
scheduler::utils as pt_utils,
services,
types::{
self,
- api::{self, PaymentIdTypeExt, PaymentsResponse, PaymentsRetrieveRequest},
- storage::{self, enums, ProcessTrackerExt},
+ api::{self, enums as api_enums},
+ storage::{self, enums as storage_enums},
transformers::ForeignInto,
},
utils::{self, OptionExt},
@@ -45,6 +44,7 @@ pub async fn payments_operation_core<F, Req, Op, FData>(
merchant_account: storage::MerchantAccount,
operation: Op,
req: Req,
+ use_connector: Option<api_enums::Connector>,
call_connector_action: CallConnectorAction,
) -> RouterResult<(PaymentData<F>, Req, Option<storage::Customer>)>
where
@@ -106,6 +106,7 @@ where
validate_result.storage_scheme,
)
.await?;
+
payment_data.payment_method_data = payment_method_data;
if let Some(token) = payment_token {
payment_data.token = Some(token)
@@ -113,7 +114,7 @@ where
let connector_details = operation
.to_domain()?
- .get_connector(&merchant_account, state)
+ .get_connector(&merchant_account, state, use_connector)
.await?;
if let api::ConnectorCallType::Single(ref connector) = connector_details {
@@ -175,6 +176,7 @@ pub async fn payments_core<F, Res, Req, Op, FData>(
operation: Op,
req: Req,
auth_flow: services::AuthFlow,
+ use_connector: Option<api_enums::Connector>,
call_connector_action: CallConnectorAction,
) -> RouterResponse<Res>
where
@@ -199,9 +201,11 @@ where
merchant_account,
operation.clone(),
req,
+ use_connector,
call_connector_action,
)
.await?;
+
Res::generate_response(
Some(req),
payment_data,
@@ -220,7 +224,7 @@ fn is_start_pay<Op: Debug>(operation: &Op) -> bool {
pub async fn handle_payments_redirect_response<'a, F>(
state: &AppState,
merchant_account: storage::MerchantAccount,
- req: PaymentsRetrieveRequest,
+ req: api::PaymentsRetrieveRequest,
) -> RouterResponse<api::RedirectionResponse>
where
F: Send + Clone + 'a,
@@ -229,11 +233,10 @@ where
let query_params = req.param.clone().get_required_value("param")?;
- let resource_id = req.resource_id.get_payment_intent_id().change_context(
- errors::ApiErrorResponse::MissingRequiredField {
+ let resource_id = api::PaymentIdTypeExt::get_payment_intent_id(&req.resource_id)
+ .change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_id".to_string(),
- },
- )?;
+ })?;
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
@@ -277,15 +280,16 @@ where
pub async fn payments_response_for_redirection_flows<'a>(
state: &AppState,
merchant_account: storage::MerchantAccount,
- req: PaymentsRetrieveRequest,
+ req: api::PaymentsRetrieveRequest,
flow_type: CallConnectorAction,
-) -> RouterResponse<PaymentsResponse> {
+) -> RouterResponse<api::PaymentsResponse> {
payments_core::<api::PSync, api::PaymentsResponse, _, _, _>(
state,
merchant_account,
payments::PaymentStatus,
req,
services::api::AuthFlow::Merchant,
+ None,
flow_type,
)
.await
@@ -433,7 +437,7 @@ where
pub enum CallConnectorAction {
Trigger,
Avoid,
- StatusUpdate(enums::AttemptStatus),
+ StatusUpdate(storage_enums::AttemptStatus),
HandleResponse(Vec<u8>),
}
@@ -453,7 +457,7 @@ where
pub payment_attempt: storage::PaymentAttempt,
pub connector_response: storage::ConnectorResponse,
pub amount: api::Amount,
- pub currency: enums::Currency,
+ pub currency: storage_enums::Currency,
pub mandate_id: Option<String>,
pub setup_mandate: Option<api::MandateData>,
pub address: PaymentAddress,
@@ -463,21 +467,21 @@ where
pub payment_method_data: Option<api::PaymentMethod>,
pub refunds: Vec<storage::Refund>,
pub sessions_token: Vec<api::SessionToken>,
- pub card_cvc: Option<Secret<String>>,
+ pub card_cvc: Option<pii::Secret<String>>,
}
#[derive(Debug)]
pub struct CustomerDetails {
pub customer_id: Option<String>,
pub name: Option<masking::Secret<String, masking::WithType>>,
- pub email: Option<masking::Secret<String, Email>>,
+ pub email: Option<masking::Secret<String, pii::Email>>,
pub phone: Option<masking::Secret<String, masking::WithType>>,
pub phone_country_code: Option<String>,
}
pub fn if_not_create_change_operation<'a, Op, F>(
is_update: bool,
- status: enums::IntentStatus,
+ status: storage_enums::IntentStatus,
current: &'a Op,
) -> BoxedOperation<F, api::PaymentsRequest>
where
@@ -486,9 +490,9 @@ where
&'a Op: Operation<F, api::PaymentsRequest>,
{
match status {
- enums::IntentStatus::RequiresConfirmation
- | enums::IntentStatus::RequiresCustomerAction
- | enums::IntentStatus::RequiresPaymentMethod => {
+ storage_enums::IntentStatus::RequiresConfirmation
+ | storage_enums::IntentStatus::RequiresCustomerAction
+ | storage_enums::IntentStatus::RequiresPaymentMethod => {
if is_update {
Box::new(&PaymentUpdate)
} else {
@@ -525,7 +529,7 @@ pub fn should_call_connector<Op: Debug, F: Clone>(
"PaymentStart" => {
!matches!(
payment_data.payment_intent.status,
- enums::IntentStatus::Failed | enums::IntentStatus::Succeeded
+ storage_enums::IntentStatus::Failed | storage_enums::IntentStatus::Succeeded
) && payment_data
.connector_response
.authentication_data
@@ -534,20 +538,20 @@ pub fn should_call_connector<Op: Debug, F: Clone>(
"PaymentStatus" => {
matches!(
payment_data.payment_intent.status,
- enums::IntentStatus::Failed
- | enums::IntentStatus::Processing
- | enums::IntentStatus::Succeeded
- | enums::IntentStatus::RequiresCustomerAction
+ storage_enums::IntentStatus::Failed
+ | storage_enums::IntentStatus::Processing
+ | storage_enums::IntentStatus::Succeeded
+ | storage_enums::IntentStatus::RequiresCustomerAction
) && payment_data.force_sync.unwrap_or(false)
}
"PaymentCancel" => matches!(
payment_data.payment_intent.status,
- enums::IntentStatus::RequiresCapture
+ storage_enums::IntentStatus::RequiresCapture
),
"PaymentCapture" => {
matches!(
payment_data.payment_intent.status,
- enums::IntentStatus::RequiresCapture
+ storage_enums::IntentStatus::RequiresCapture
)
}
"PaymentSession" => true,
@@ -602,13 +606,14 @@ pub async fn add_process_sync_task(
&payment_attempt.txn_id,
&payment_attempt.merchant_id,
);
- let process_tracker_entry = storage::ProcessTracker::make_process_tracker_new(
- process_tracker_id,
- task,
- runner,
- tracking_data,
- schedule_time,
- )?;
+ let process_tracker_entry =
+ <storage::ProcessTracker as storage::ProcessTrackerExt>::make_process_tracker_new(
+ process_tracker_id,
+ task,
+ runner,
+ tracking_data,
+ schedule_time,
+ )?;
db.insert_process(process_tracker_entry).await?;
Ok(())
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index c363dbd8a29..8ce4becbca4 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -620,43 +620,52 @@ pub async fn get_customer_from_details(
pub async fn get_connector_default(
merchant_account: &storage::MerchantAccount,
state: &AppState,
+ request_connector: Option<api_enums::Connector>,
) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
let connectors = &state.conf.connectors;
- let vec_val: Vec<serde_json::Value> = merchant_account
- .custom_routing_rules
- .clone()
- .parse_value("CustomRoutingRulesVec")
- .change_context(errors::ConnectorError::RoutingRulesParsingError)
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
- let custom_routing_rules: api::CustomRoutingRules = vec_val[0]
- .clone()
- .parse_value("CustomRoutingRules")
- .change_context(errors::ConnectorError::RoutingRulesParsingError)
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
- let connector_names = custom_routing_rules
- .connectors_pecking_order
- .unwrap_or_else(|| vec!["stripe".to_string()]);
-
- //use routing rules if configured by merchant else query MCA as per PM
- let connector_list: types::ConnectorsList = types::ConnectorsList {
- connectors: connector_names,
- };
+ if let Some(connector) = request_connector {
+ let connector_data = api::ConnectorData::get_connector_by_name(
+ connectors,
+ &connector.to_string(),
+ api::GetToken::Connector,
+ )?;
+ Ok(api::ConnectorCallType::Single(connector_data))
+ } else {
+ let vec_val: Vec<serde_json::Value> = merchant_account
+ .custom_routing_rules
+ .clone()
+ .parse_value("CustomRoutingRulesVec")
+ .change_context(errors::ConnectorError::RoutingRulesParsingError)
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ let custom_routing_rules: api::CustomRoutingRules = vec_val[0]
+ .clone()
+ .parse_value("CustomRoutingRules")
+ .change_context(errors::ConnectorError::RoutingRulesParsingError)
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ let connector_names = custom_routing_rules
+ .connectors_pecking_order
+ .unwrap_or_else(|| vec!["stripe".to_string()]);
- let connector_name = connector_list
- .connectors
- .first()
- .get_required_value("connectors")
- .change_context(errors::ConnectorError::FailedToObtainPreferredConnector)
- .change_context(errors::ApiErrorResponse::InternalServerError)?
- .as_str();
-
- let connector_data = api::ConnectorData::get_connector_by_name(
- connectors,
- connector_name,
- api::GetToken::Connector,
- )?;
+ //use routing rules if configured by merchant else query MCA as per PM
+ let connector_list: types::ConnectorsList = types::ConnectorsList {
+ connectors: connector_names,
+ };
- Ok(api::ConnectorCallType::Single(connector_data))
+ let connector_name = connector_list
+ .connectors
+ .first()
+ .get_required_value("connectors")
+ .change_context(errors::ConnectorError::FailedToObtainPreferredConnector)
+ .change_context(errors::ApiErrorResponse::InternalServerError)?
+ .as_str();
+
+ let connector_data = api::ConnectorData::get_connector_by_name(
+ connectors,
+ connector_name,
+ api::GetToken::Connector,
+ )?;
+ Ok(api::ConnectorCallType::Single(connector_data))
+ }
}
#[instrument(skip_all)]
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index 602191a6a7b..cf7a20a41b2 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -30,7 +30,8 @@ use crate::{
pii::Secret,
routes::AppState,
types::{
- self, api,
+ self,
+ api::{self, enums as api_enums},
storage::{self, enums},
PaymentsResponseData,
},
@@ -138,6 +139,7 @@ pub trait Domain<F: Clone, R>: Send + Sync {
&'a self,
merchant_account: &storage::MerchantAccount,
state: &AppState,
+ request_connector: Option<api_enums::Connector>,
) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse>;
}
@@ -204,8 +206,9 @@ where
&'a self,
merchant_account: &storage::MerchantAccount,
state: &AppState,
+ request_connector: Option<api_enums::Connector>,
) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
- helpers::get_connector_default(merchant_account, state).await
+ helpers::get_connector_default(merchant_account, state, request_connector).await
}
#[instrument(skip_all)]
@@ -291,8 +294,9 @@ where
&'a self,
merchant_account: &storage::MerchantAccount,
state: &AppState,
+ request_connector: Option<api_enums::Connector>,
) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
- helpers::get_connector_default(merchant_account, state).await
+ helpers::get_connector_default(merchant_account, state, request_connector).await
}
}
@@ -350,7 +354,8 @@ where
&'a self,
merchant_account: &storage::MerchantAccount,
state: &AppState,
+ request_connector: Option<api_enums::Connector>,
) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
- helpers::get_connector_default(merchant_account, state).await
+ helpers::get_connector_default(merchant_account, state, request_connector).await
}
}
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index cc4ca66605c..55550948c0d 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -17,7 +17,7 @@ use crate::{
routes::AppState,
types::{
self,
- api::{self, PaymentIdTypeExt},
+ api::{self, enums as api_enums, PaymentIdTypeExt},
storage::{self, enums},
transformers::ForeignInto,
},
@@ -243,8 +243,9 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm {
&'a self,
merchant_account: &storage::MerchantAccount,
state: &AppState,
+ request_connector: Option<api_enums::Connector>,
) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
- helpers::get_connector_default(merchant_account, state).await
+ helpers::get_connector_default(merchant_account, state, request_connector).await
}
}
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index c8cd30ea227..91eae8f7cd0 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -19,7 +19,7 @@ use crate::{
routes::AppState,
types::{
self,
- api::{self, PaymentIdTypeExt},
+ api::{self, enums as api_enums, PaymentIdTypeExt},
storage::{
self,
enums::{self, IntentStatus},
@@ -290,8 +290,9 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentCreate {
&'a self,
merchant_account: &storage::MerchantAccount,
state: &AppState,
+ request_connector: Option<api_enums::Connector>,
) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
- helpers::get_connector_default(merchant_account, state).await
+ helpers::get_connector_default(merchant_account, state, request_connector).await
}
}
diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs
index cf3974c7d11..56291719c14 100644
--- a/crates/router/src/core/payments/operations/payment_method_validate.rs
+++ b/crates/router/src/core/payments/operations/payment_method_validate.rs
@@ -265,8 +265,9 @@ where
&'a self,
merchant_account: &storage::MerchantAccount,
state: &AppState,
+ request_connector: Option<api_enums::Connector>,
) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
- helpers::get_connector_default(merchant_account, state).await
+ helpers::get_connector_default(merchant_account, state, request_connector).await
}
}
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index b94929e47ec..1f68feeb16e 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -16,7 +16,7 @@ use crate::{
pii::Secret,
routes::AppState,
types::{
- api::{self, PaymentIdTypeExt},
+ api::{self, enums as api_enums, PaymentIdTypeExt},
storage::{self, enums},
transformers::ForeignInto,
},
@@ -257,6 +257,7 @@ where
&'a self,
merchant_account: &storage::MerchantAccount,
state: &AppState,
+ _request_connector: Option<api_enums::Connector>,
) -> RouterResult<api::ConnectorCallType> {
let connectors = &state.conf.connectors;
let db = &state.store;
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index 701b0ef27a9..4afc084372e 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -15,7 +15,7 @@ use crate::{
pii::Secret,
routes::AppState,
types::{
- api::{self, PaymentIdTypeExt},
+ api::{self, enums as api_enums, PaymentIdTypeExt},
storage::{self, enums, Customer},
transformers::ForeignInto,
},
@@ -265,7 +265,8 @@ where
&'a self,
merchant_account: &storage::MerchantAccount,
state: &AppState,
+ request_connector: Option<api_enums::Connector>,
) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
- helpers::get_connector_default(merchant_account, state).await
+ helpers::get_connector_default(merchant_account, state, request_connector).await
}
}
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index c3845182f3b..68b5c03db18 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -15,7 +15,7 @@ use crate::{
db::StorageInterface,
routes::AppState,
types::{
- api,
+ api::{self, enums as api_enums},
storage::{self, enums},
transformers::ForeignInto,
},
@@ -117,8 +117,9 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus {
&'a self,
merchant_account: &storage::MerchantAccount,
state: &AppState,
+ request_connector: Option<api_enums::Connector>,
) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
- helpers::get_connector_default(merchant_account, state).await
+ helpers::get_connector_default(merchant_account, state, request_connector).await
}
}
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 2bbea287826..4340dee17cb 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -16,7 +16,7 @@ use crate::{
db::StorageInterface,
routes::AppState,
types::{
- api::{self, PaymentIdTypeExt},
+ api::{self, enums as api_enums, PaymentIdTypeExt},
storage::{self, enums},
transformers::ForeignInto,
},
@@ -237,8 +237,9 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentUpdate {
&'a self,
merchant_account: &storage::MerchantAccount,
state: &AppState,
+ request_connector: Option<api_enums::Connector>,
) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
- helpers::get_connector_default(merchant_account, state).await
+ helpers::get_connector_default(merchant_account, state, request_connector).await
}
}
diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs
index 386e62dc621..3f8ebd8c386 100644
--- a/crates/router/src/core/webhooks.rs
+++ b/crates/router/src/core/webhooks.rs
@@ -52,6 +52,7 @@ async fn payments_incoming_webhook_flow(
param: None,
},
services::AuthFlow::Merchant,
+ None,
consume_or_trigger_flow,
)
.await
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index adbde39af08..dc919991285 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -46,6 +46,7 @@ pub async fn payments_create(
|state, merchant_account, req| {
// TODO: Change for making it possible for the flow to be inferred internally or through validation layer
async {
+ let connector = req.connector;
match req.amount.as_ref() {
Some(api_types::Amount::Value(_)) | None => {
payments::payments_core::<Authorize, PaymentsResponse, _, _, _>(
@@ -54,10 +55,12 @@ pub async fn payments_create(
payments::PaymentCreate,
req,
api::AuthFlow::Merchant,
+ connector,
payments::CallConnectorAction::Trigger,
)
.await
}
+
Some(api_types::Amount::Zero) => {
payments::payments_core::<Verify, PaymentsResponse, _, _, _>(
state,
@@ -65,6 +68,7 @@ pub async fn payments_create(
payments::PaymentCreate,
req,
api::AuthFlow::Merchant,
+ connector,
payments::CallConnectorAction::Trigger,
)
.await
@@ -100,6 +104,7 @@ pub async fn payments_start(
payments::operations::PaymentStart,
req,
api::AuthFlow::Client,
+ None,
payments::CallConnectorAction::Trigger,
)
},
@@ -140,6 +145,7 @@ pub async fn payments_retrieve(
payments::PaymentStatus,
req,
api::AuthFlow::Merchant,
+ None,
payments::CallConnectorAction::Trigger,
)
},
@@ -179,12 +185,14 @@ pub async fn payments_update(
&req,
payload,
|state, merchant_account, req| {
+ let connector = req.connector;
payments::payments_core::<Authorize, PaymentsResponse, _, _, _>(
state,
merchant_account,
payments::PaymentUpdate,
req,
auth_flow,
+ connector,
payments::CallConnectorAction::Trigger,
)
},
@@ -223,12 +231,14 @@ pub async fn payments_confirm(
&req,
payload,
|state, merchant_account, req| {
+ let connector = req.connector;
payments::payments_core::<Authorize, PaymentsResponse, _, _, _>(
state,
merchant_account,
payments::PaymentConfirm,
req,
auth_flow,
+ connector,
payments::CallConnectorAction::Trigger,
)
},
@@ -261,6 +271,7 @@ pub(crate) async fn payments_capture(
payments::PaymentCapture,
payload,
api::AuthFlow::Merchant,
+ None,
payments::CallConnectorAction::Trigger,
)
},
@@ -288,6 +299,7 @@ pub(crate) async fn payments_connector_session(
payments::PaymentSession,
payload,
api::AuthFlow::Merchant,
+ None,
payments::CallConnectorAction::Trigger,
)
},
@@ -347,6 +359,7 @@ pub async fn payments_cancel(
payments::PaymentCancel,
req,
api::AuthFlow::Merchant,
+ None,
payments::CallConnectorAction::Trigger,
)
},
diff --git a/crates/router/src/scheduler/workflows/payment_sync.rs b/crates/router/src/scheduler/workflows/payment_sync.rs
index df8597797e8..48824d6d367 100644
--- a/crates/router/src/scheduler/workflows/payment_sync.rs
+++ b/crates/router/src/scheduler/workflows/payment_sync.rs
@@ -41,6 +41,7 @@ impl ProcessTrackerWorkflow for PaymentsSyncWorkflow {
merchant_account.clone(),
operations::PaymentStatus,
tracking_data.clone(),
+ None,
payment_flows::CallConnectorAction::Trigger,
)
.await?;
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 391c4333e5b..f991c4415c3 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -13,9 +13,9 @@ pub mod transformers;
use std::marker::PhantomData;
+pub use api_models::enums::Connector;
use error_stack::{IntoReport, ResultExt};
-pub use self::connector::Connector;
use self::{api::payments, storage::enums as storage_enums};
pub use crate::core::payments::PaymentAddress;
use crate::{core::errors, services};
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index d97c252f360..5aeddbac5a8 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -17,7 +17,7 @@ use crate::{
connector,
core::errors::{self, CustomResult},
services::ConnectorRedirectResponse,
- types,
+ types::{self, api::enums as api_enums},
};
pub trait ConnectorCommon {
@@ -82,6 +82,12 @@ pub enum ConnectorCallType {
Multiple(Vec<ConnectorData>),
}
+impl ConnectorCallType {
+ pub fn is_single(&self) -> bool {
+ matches!(self, Self::Single(_))
+ }
+}
+
impl ConnectorData {
pub fn get_connector_by_name(
connectors: &Connectors,
@@ -89,7 +95,7 @@ impl ConnectorData {
connector_type: GetToken,
) -> CustomResult<ConnectorData, errors::ApiErrorResponse> {
let connector = Self::convert_connector(connectors, name)?;
- let connector_name = types::Connector::from_str(name)
+ let connector_name = api_enums::Connector::from_str(name)
.into_report()
.change_context(errors::ConnectorError::InvalidConnectorName)
.attach_printable_lazy(|| format!("unable to parse connector name {connector:?}"))
diff --git a/crates/router/src/types/connector.rs b/crates/router/src/types/connector.rs
index d8ff63d5d1a..8b137891791 100644
--- a/crates/router/src/types/connector.rs
+++ b/crates/router/src/types/connector.rs
@@ -1,14 +1 @@
-#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, strum::Display, strum::EnumString)]
-#[strum(serialize_all = "snake_case")]
-pub enum Connector {
- Adyen,
- Stripe,
- Checkout,
- Aci,
- Authorizedotnet,
- Braintree,
- Klarna,
- Applepay,
- #[default]
- Dummy,
-}
+
diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs
index 22a784165b2..0ccfd74d18c 100644
--- a/crates/router/tests/payments.rs
+++ b/crates/router/tests/payments.rs
@@ -289,6 +289,7 @@ async fn payments_create_core() {
)),
merchant_id: Some("jarnura".to_string()),
amount: Some(6540.into()),
+ connector: None,
currency: Some("USD".to_string()),
capture_method: Some(api_enums::CaptureMethod::Automatic),
amount_to_capture: Some(6540),
@@ -354,6 +355,7 @@ async fn payments_create_core() {
payments::PaymentCreate,
req,
services::AuthFlow::Merchant,
+ None,
payments::CallConnectorAction::Trigger,
)
.await
@@ -446,6 +448,7 @@ async fn payments_create_core_adyen_no_redirect() {
payment_id: Some(api::PaymentIdType::PaymentIntentId(payment_id.clone())),
merchant_id: Some(merchant_id.clone()),
amount: Some(6540.into()),
+ connector: None,
currency: Some("USD".to_string()),
capture_method: Some(api_enums::CaptureMethod::Automatic),
amount_to_capture: Some(6540),
@@ -510,6 +513,7 @@ async fn payments_create_core_adyen_no_redirect() {
payments::PaymentCreate,
req,
services::AuthFlow::Merchant,
+ None,
payments::CallConnectorAction::Trigger,
)
.await
diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs
index 02b914d3c23..7a3041efcfd 100644
--- a/crates/router/tests/payments2.rs
+++ b/crates/router/tests/payments2.rs
@@ -106,6 +106,7 @@ async fn payments_create_core() {
payments::PaymentCreate,
req,
services::AuthFlow::Merchant,
+ None,
payments::CallConnectorAction::Trigger,
)
.await
@@ -201,6 +202,7 @@ async fn payments_create_core_adyen_no_redirect() {
payment_id: Some(api::PaymentIdType::PaymentIntentId(payment_id.clone())),
merchant_id: Some(merchant_id.clone()),
amount: Some(6540.into()),
+ connector: None,
currency: Some("USD".to_string()),
capture_method: Some(api_enums::CaptureMethod::Automatic),
amount_to_capture: Some(6540),
@@ -265,6 +267,7 @@ async fn payments_create_core_adyen_no_redirect() {
payments::PaymentCreate,
req,
services::AuthFlow::Merchant,
+ None,
payments::CallConnectorAction::Trigger,
)
.await
|
feat
|
add straight-through routing connector selection in payments (#153)
|
9e2868ccf86854135a6f0668985d92fae72e82ed
|
2023-07-26 14:42:37
|
Pa1NarK
|
ci(postman): Remove Giropay postman tests (#1788)
| false
|
diff --git a/postman/worldline.postman_collection.json b/postman/worldline.postman_collection.json
index 7326d1239b4..5cce53a0009 100644
--- a/postman/worldline.postman_collection.json
+++ b/postman/worldline.postman_collection.json
@@ -1,10 +1,9 @@
{
"info": {
- "_postman_id": "2bc5bc9e-60a9-4518-8805-24a1a13fed15",
+ "_postman_id": "e8447b00-0e11-4b9b-aa98-b7c1fda3e9fa",
"name": "Worldline Collection",
"description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [[email protected]](mailto:[email protected])",
- "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
- "_exporter_id": "25737662"
+ "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
@@ -140,7 +139,7 @@
],
"body": {
"mode": "raw",
- "raw": "{\n \"merchant_id\": \"postman_merchant_GHAction_{{$guid}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://duck.com\",\n \"webhook_details\": {\n \"webhook_version\": \"1.0.1\",\n \"webhook_username\": \"ekart_retail\",\n \"webhook_password\": \"password_ekart@123\",\n \"payment_created_enabled\": true,\n \"payment_succeeded_enabled\": true,\n \"payment_failed_enabled\": true\n },\n \"routing_algorithm\": {\n \"type\": \"single\",\n \"data\": \"worldline\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}",
+ "raw": "{\n \"merchant_id\": \"merchant_{{$guid}}\",\n \"locker_id\": \"m0010\",\n \"merchant_name\": \"NewAge Retailer\",\n \"merchant_details\": {\n \"primary_contact_person\": \"John Test\",\n \"primary_email\": \"[email protected]\",\n \"primary_phone\": \"sunt laborum\",\n \"secondary_contact_person\": \"John Test2\",\n \"secondary_email\": \"[email protected]\",\n \"secondary_phone\": \"cillum do dolor id\",\n \"website\": \"www.example.com\",\n \"about_business\": \"Online Retail with a wide selection of organic products for North America\",\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\"\n }\n },\n \"return_url\": \"https://duck.com\",\n \"webhook_details\": {\n \"webhook_version\": \"1.0.1\",\n \"webhook_username\": \"ekart_retail\",\n \"webhook_password\": \"password_ekart@123\",\n \"payment_created_enabled\": true,\n \"payment_succeeded_enabled\": true,\n \"payment_failed_enabled\": true\n },\n \"routing_algorithm\": {\n \"type\": \"single\",\n \"data\": \"worldline\"\n },\n \"sub_merchants_enabled\": false,\n \"metadata\": {\n \"city\": \"NY\",\n \"unit\": \"245\"\n }\n}",
"options": {
"raw": {
"language": "json"
@@ -2282,329 +2281,6 @@
"response": []
}
]
- },
- {
- "name": "Scenario18-Bank Redirect-giropay",
- "item": [
- {
- "name": "Payments - Create",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx ",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
- "});",
- "",
- "// Validate if response has JSON Body ",
- "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {jsonData = pm.response.json();}catch(e){}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
- "};",
- "",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
- "};",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
- "};",
- "",
- "// Response body should have value \"requires_payment_method\" for \"status\"",
- "if (jsonData?.status) {",
- "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\", function() {",
- " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");",
- "})};",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\n \"amount\": 1000,\n \"currency\": \"EUR\",\n \"confirm\": false,\n \"capture_method\": \"automatic\",\n \"capture_on\": \"2022-09-10T10:11:12Z\",\n \"amount_to_capture\": 1000,\n \"customer_id\": \"StripeCustomer\",\n \"email\": \"[email protected]\",\n \"name\": \"John Doe\",\n \"phone\": \"999999999\",\n \"phone_country_code\": \"+65\",\n \"description\": \"Its my first payment request\",\n \"authentication_type\": \"three_ds\",\n \"return_url\": \"https://google.com\",\n \"payment_method\": \"bank_redirect\",\n \"payment_method_type\": \"giropay\",\n \"payment_method_data\": {\n \"bank_redirect\": {\n \"giropay\" : {\n \"billing_details\": {\n \"billing_name\": \"LOL\"\n },\n \"bank_account_bic\": null,\n \"bank_account_iban\": \"DE46940594210000012345\"\n }\n }\n },\n \"billing\": {\n \"address\": {\n \"first_name\": \"John\",\n \"last_name\": \"Doe\",\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"DE\"\n }\n },\n \"browser_info\": {\n \"user_agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\n \"accept_header\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"language\": \"nl-NL\",\n \"color_depth\": 24,\n \"screen_height\": 723,\n \"screen_width\": 1536,\n \"time_zone\": 0,\n \"java_enabled\": true,\n \"java_script_enabled\": true,\n \"ip_address\": \"127.0.0.1\"\n },\n \"shipping\": {\n \"address\": {\n \"line1\": \"1467\",\n \"line2\": \"Harrison Street\",\n \"line3\": \"Harrison Street\",\n \"city\": \"San Fransico\",\n \"state\": \"California\",\n \"zip\": \"94122\",\n \"country\": \"US\",\n \"first_name\": \"John\",\n \"last_name\": \"Doe\"\n }\n },\n \"statement_descriptor_name\": \"joseph\",\n \"statement_descriptor_suffix\": \"JS\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
- },
- "response": []
- },
- {
- "name": "Payments - Confirm",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx ",
- "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
- "});",
- "",
- "",
- "",
- "// Validate if response has JSON Body ",
- "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {jsonData = pm.response.json();}catch(e){}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
- "};",
- "",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
- "};",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
- "};",
- "",
- "// Response body should have value \"requires_customer_action\" for \"status\"",
- "if (jsonData?.status) {",
- "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\", function() {",
- " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
- "})};",
- "",
- "",
- "// Response body should have \"next_action.redirect_to_url\"",
- "pm.test(\"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\", function() {",
- " pm.expect((typeof jsonData.next_action.redirect_to_url !== \"undefined\")).to.be.true;",
- "});",
- "",
- "// Response body should have value \"giropay\" for \"payment_method_type\"",
- "if (jsonData?.payment_method_type) {",
- "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'giropay'\", function() {",
- " pm.expect(jsonData.payment_method_type).to.eql(\"giropay\");",
- "})};",
- "",
- "",
- "// Response body should have value \"stripe\" for \"connector\"",
- "if (jsonData?.connector) {",
- "pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'worldline'\", function() {",
- " pm.expect(jsonData.connector).to.eql(\"worldline\");",
- "})};"
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\n \"payment_method\": \"bank_redirect\",\n \"payment_method_type\": \"giropay\",\n \"payment_method_data\": {\n \"bank_redirect\": {\n \"giropay\" : {\n \"billing_details\": {\n \"billing_name\": \"LOL\"\n },\n \"bank_account_bic\": null,\n \"bank_account_iban\": \"DE46940594210000012345\"\n }\n }\n }\n}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{baseUrl}}/payments/:id/confirm",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id",
- "confirm"
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
- ]
- },
- "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
- },
- "response": []
- },
- {
- "name": "Payments - Retrieve",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx ",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
- "});",
- "",
- "// Validate if response has JSON Body ",
- "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {jsonData = pm.response.json();}catch(e){}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
- "};",
- "",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
- "};",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
- "};",
- "",
- "// Response body should have value \"requires_customer_action\" for \"status\"",
- "if (jsonData?.status) {",
- "pm.test(\"[POST]::/payments:id - Content check if value for 'status' matches 'requires_customer_action'\", function() {",
- " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
- "})};"
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "GET",
- "header": [
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id"
- ],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
- ]
- },
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
- },
- "response": []
- }
- ]
}
]
},
@@ -4013,18 +3689,7 @@
"script": {
"type": "text/javascript",
"exec": [
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {jsonData = pm.response.json();}catch(e){}",
- "",
- "// Log Payment ID",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(\"[INFO] payment_id: \" + jsonData.payment_id);",
- "}",
- "",
- "// Log X Request ID",
- "console.log(\"[INFO] x-request-id: \" + pm.response.headers.get('x-request-id'));"
+ ""
]
}
}
|
ci
|
Remove Giropay postman tests (#1788)
|
d302b286b8282488f6e0b3bb6259bb2c9930b3dd
|
2023-03-21 11:03:03
|
Nishant Joshi
|
feat(router): adding metrics for tracking behavior throughout the `router` crate (#768)
| false
|
diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs
index f7cdfc6149d..ba2832d7a47 100644
--- a/crates/router/src/core/api_keys.rs
+++ b/crates/router/src/core/api_keys.rs
@@ -10,6 +10,7 @@ use crate::{
consts,
core::errors::{self, RouterResponse, StorageErrorExt},
db::StorageInterface,
+ routes::metrics,
services::ApplicationResponse,
types::{api, storage, transformers::ForeignInto},
utils,
@@ -147,6 +148,8 @@ pub async fn create_api_key(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert new API key")?;
+ metrics::API_KEY_CREATED.add(&metrics::CONTEXT, 1, &[]);
+
Ok(ApplicationResponse::Json(
(api_key, plaintext_api_key).foreign_into(),
))
@@ -191,6 +194,8 @@ pub async fn revoke_api_key(
.await
.map_err(|err| err.to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound))?;
+ metrics::API_KEY_REVOKED.add(&metrics::CONTEXT, 1, &[]);
+
Ok(ApplicationResponse::Json(api::RevokeApiKeyResponse {
key_id: key_id.to_owned(),
revoked,
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index 1ef57d3794e..f3832404e63 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -10,7 +10,7 @@ use crate::{
},
db::StorageInterface,
pii::PeekInterface,
- routes::AppState,
+ routes::{metrics, AppState},
services,
types::{
api::customers::{self, CustomerRequestExt},
@@ -222,6 +222,7 @@ pub async fn delete_customer(
address_deleted: true,
payment_methods_deleted: true,
};
+ metrics::CUSTOMER_REDACTED.add(&metrics::CONTEXT, 1, &[]);
Ok(services::ApplicationResponse::Json(response))
}
diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs
index 32d7ea076c8..3b638059ba8 100644
--- a/crates/router/src/core/mandate.rs
+++ b/crates/router/src/core/mandate.rs
@@ -6,7 +6,7 @@ use super::payments::helpers;
use crate::{
core::errors::{self, RouterResponse, StorageErrorExt},
db::StorageInterface,
- routes::AppState,
+ routes::{metrics, AppState},
services,
types::{
self,
@@ -135,7 +135,14 @@ where
.await
.change_context(errors::ApiErrorResponse::MandateNotFound),
}?;
-
+ metrics::SUBSEQUENT_MANDATE_PAYMENT.add(
+ &metrics::CONTEXT,
+ 1,
+ &[metrics::request::add_attributes(
+ "connector",
+ mandate.connector,
+ )],
+ );
resp.payment_method_id = Some(mandate.payment_method_id);
}
None => {
@@ -167,6 +174,7 @@ where
payment_method_id,
mandate_reference,
) {
+ let connector = new_mandate_data.connector.clone();
logger::debug!("{:?}", new_mandate_data);
resp.request
.set_mandate_id(api_models::payments::MandateIds {
@@ -182,6 +190,11 @@ where
errors::ApiErrorResponse::DuplicateRefundRequest,
)
})?;
+ metrics::MANDATE_COUNT.add(
+ &metrics::CONTEXT,
+ 1,
+ &[metrics::request::add_attributes("connector", connector)],
+ );
};
} else if resp.request.get_setup_future_usage().is_some() {
helpers::call_payment_method(
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index d7bfee11786..515111e1336 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -19,7 +19,7 @@ use error_stack::{report, ResultExt};
use router_env::{instrument, tracing};
#[cfg(feature = "basilisk")]
-use crate::scheduler::metrics;
+use crate::scheduler::metrics as scheduler_metrics;
use crate::{
configs::settings,
core::{
@@ -29,7 +29,8 @@ use crate::{
},
db, logger,
pii::prelude::*,
- routes, services,
+ routes::{self, metrics},
+ services,
types::{
api::{self, PaymentMethodCreateExt},
storage::{self, enums},
@@ -159,14 +160,25 @@ pub async fn add_card_to_locker(
customer_id: String,
merchant_account: &storage::MerchantAccount,
) -> errors::CustomResult<api::PaymentMethodResponse, errors::VaultError> {
- match state.conf.locker.locker_setup {
- settings::LockerSetup::BasiliskLocker => {
- add_card_hs(state, req, card, customer_id, merchant_account).await
- }
- settings::LockerSetup::LegacyLocker => {
- add_card(state, req, card, customer_id, merchant_account).await
- }
- }
+ metrics::STORED_TO_LOCKER.add(&metrics::CONTEXT, 1, &[]);
+ metrics::request::record_card_operation_time(
+ async {
+ match state.conf.locker.locker_setup {
+ settings::LockerSetup::BasiliskLocker => {
+ add_card_hs(state, req, card, customer_id, merchant_account).await
+ }
+ settings::LockerSetup::LegacyLocker => {
+ add_card(state, req, card, customer_id, merchant_account).await
+ }
+ }
+ .map_err(|error| {
+ metrics::CARD_LOCKER_FAILURES.add(&metrics::CONTEXT, 1, &[]);
+ error
+ })
+ },
+ &metrics::CARD_ADD_TIME,
+ )
+ .await
}
pub async fn get_card_from_locker(
@@ -176,22 +188,34 @@ pub async fn get_card_from_locker(
card_reference: &str,
locker_id: Option<String>,
) -> errors::RouterResult<payment_methods::Card> {
- match state.conf.locker.locker_setup {
- settings::LockerSetup::LegacyLocker => {
- get_card_from_legacy_locker(
- state,
- &locker_id.get_required_value("locker_id")?,
- card_reference,
- )
- .await
- }
- settings::LockerSetup::BasiliskLocker => {
- get_card_from_hs_locker(state, customer_id, merchant_id, card_reference)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed while getting card from basilisk_hs")
- }
- }
+ metrics::GET_FROM_LOCKER.add(&metrics::CONTEXT, 1, &[]);
+
+ metrics::request::record_card_operation_time(
+ async {
+ match state.conf.locker.locker_setup {
+ settings::LockerSetup::LegacyLocker => {
+ get_card_from_legacy_locker(
+ state,
+ &locker_id.get_required_value("locker_id")?,
+ card_reference,
+ )
+ .await
+ }
+ settings::LockerSetup::BasiliskLocker => {
+ get_card_from_hs_locker(state, customer_id, merchant_id, card_reference)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while getting card from basilisk_hs")
+ }
+ }
+ .map_err(|error| {
+ metrics::CARD_LOCKER_FAILURES.add(&metrics::CONTEXT, 1, &[]);
+ error
+ })
+ },
+ &metrics::CARD_GET_TIME,
+ )
+ .await
}
pub async fn delete_card_from_locker(
@@ -200,14 +224,27 @@ pub async fn delete_card_from_locker(
merchant_id: &str,
card_reference: &str,
) -> errors::RouterResult<payment_methods::DeleteCardResp> {
- match state.conf.locker.locker_setup {
- settings::LockerSetup::LegacyLocker => {
- delete_card(state, merchant_id, card_reference).await
- }
- settings::LockerSetup::BasiliskLocker => {
- delete_card_from_hs_locker(state, customer_id, merchant_id, card_reference).await
- }
- }
+ metrics::DELETE_FROM_LOCKER.add(&metrics::CONTEXT, 1, &[]);
+
+ metrics::request::record_card_operation_time(
+ async {
+ match state.conf.locker.locker_setup {
+ settings::LockerSetup::LegacyLocker => {
+ delete_card(state, merchant_id, card_reference).await
+ }
+ settings::LockerSetup::BasiliskLocker => {
+ delete_card_from_hs_locker(state, customer_id, merchant_id, card_reference)
+ .await
+ }
+ }
+ .map_err(|error| {
+ metrics::CARD_LOCKER_FAILURES.add(&metrics::CONTEXT, 1, &[]);
+ error
+ })
+ },
+ &metrics::CARD_DELETE_TIME,
+ )
+ .await
}
#[instrument(skip_all)]
@@ -1659,7 +1696,7 @@ impl BasiliskCardSupport {
enums::PaymentMethod::Card,
)
.await?;
- metrics::TOKENIZED_DATA_COUNT.add(&metrics::CONTEXT, 1, &[]);
+ scheduler_metrics::TOKENIZED_DATA_COUNT.add(&metrics::CONTEXT, 1, &[]);
Ok(card)
}
}
diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs
index 6e809a0f684..c24e0dde93b 100644
--- a/crates/router/src/core/payment_methods/vault.rs
+++ b/crates/router/src/core/payment_methods/vault.rs
@@ -5,6 +5,8 @@ use josekit::jwe;
use masking::PeekInterface;
use router_env::{instrument, tracing};
+#[cfg(feature = "basilisk")]
+use crate::routes::metrics;
use crate::{
configs::settings,
core::errors::{self, CustomResult, RouterResult},
@@ -24,7 +26,7 @@ use crate::{
#[cfg(feature = "basilisk")]
use crate::{
db,
- scheduler::{metrics, process_data, utils as process_tracker_utils},
+ scheduler::{metrics as scheduler_metrics, process_data, utils as process_tracker_utils},
types::storage::ProcessTrackerExt,
};
#[cfg(feature = "basilisk")]
@@ -367,7 +369,7 @@ impl Vault {
let lookup_key = create_tokenize(state, value1, Some(value2), lookup_key).await?;
add_delete_tokenized_data_task(&*state.store, &lookup_key, pm).await?;
- metrics::TOKENIZED_DATA_COUNT.add(&metrics::CONTEXT, 1, &[]);
+ scheduler_metrics::TOKENIZED_DATA_COUNT.add(&metrics::CONTEXT, 1, &[]);
Ok(lookup_key)
}
@@ -437,6 +439,7 @@ pub async fn create_tokenize(
value2: Option<String>,
lookup_key: String,
) -> RouterResult<String> {
+ metrics::CREATED_TOKENIZED_CARD.add(&metrics::CONTEXT, 1, &[]);
let payload_to_be_encrypted = api::TokenizePayloadRequest {
value1,
value2: value2.unwrap_or_default(),
@@ -499,9 +502,12 @@ pub async fn create_tokenize(
)?;
Ok(get_response.lookup_key)
}
- Err(err) => Err(errors::ApiErrorResponse::InternalServerError)
- .into_report()
- .attach_printable(format!("Got 4xx from the basilisk locker: {err:?}")),
+ Err(err) => {
+ metrics::TEMP_LOCKER_FAILURES.add(&metrics::CONTEXT, 1, &[]);
+ Err(errors::ApiErrorResponse::InternalServerError)
+ .into_report()
+ .attach_printable(format!("Got 4xx from the basilisk locker: {err:?}"))
+ }
}
}
@@ -511,6 +517,7 @@ pub async fn get_tokenized_data(
lookup_key: &str,
should_get_value2: bool,
) -> RouterResult<api::TokenizePayloadRequest> {
+ metrics::GET_TOKENIZED_CARD.add(&metrics::CONTEXT, 1, &[]);
let payload_to_be_encrypted = api::GetTokenizePayloadRequest {
lookup_key: lookup_key.to_string(),
get_value2: should_get_value2,
@@ -566,9 +573,12 @@ pub async fn get_tokenized_data(
.attach_printable("Error getting TokenizePayloadRequest from tokenize response")?;
Ok(get_response)
}
- Err(err) => Err(errors::ApiErrorResponse::InternalServerError)
- .into_report()
- .attach_printable(format!("Got 4xx from the basilisk locker: {err:?}")),
+ Err(err) => {
+ metrics::TEMP_LOCKER_FAILURES.add(&metrics::CONTEXT, 1, &[]);
+ Err(errors::ApiErrorResponse::InternalServerError)
+ .into_report()
+ .attach_printable(format!("Got 4xx from the basilisk locker: {err:?}"))
+ }
}
}
@@ -577,6 +587,7 @@ pub async fn delete_tokenized_data(
state: &routes::AppState,
lookup_key: &str,
) -> RouterResult<String> {
+ metrics::DELETED_TOKENIZED_CARD.add(&metrics::CONTEXT, 1, &[]);
let payload_to_be_encrypted = api::DeleteTokenizeByTokenRequest {
lookup_key: lookup_key.to_string(),
service_name: VAULT_SERVICE_NAME.to_string(),
@@ -635,9 +646,12 @@ pub async fn delete_tokenized_data(
)?;
Ok(delete_response)
}
- Err(err) => Err(errors::ApiErrorResponse::InternalServerError)
- .into_report()
- .attach_printable(format!("Got 4xx from the basilisk locker: {err:?}")),
+ Err(err) => {
+ metrics::TEMP_LOCKER_FAILURES.add(&metrics::CONTEXT, 1, &[]);
+ Err(errors::ApiErrorResponse::InternalServerError)
+ .into_report()
+ .attach_printable(format!("Got 4xx from the basilisk locker: {err:?}"))
+ }
}
}
@@ -721,14 +735,14 @@ pub async fn start_tokenize_data_workflow(
logger::error!("Error: Deleting Card From Locker : {}", resp);
retry_delete_tokenize(db, &delete_tokenize_data.pm, tokenize_tracker.to_owned())
.await?;
- metrics::RETRIED_DELETE_DATA_COUNT.add(&metrics::CONTEXT, 1, &[]);
+ scheduler_metrics::RETRIED_DELETE_DATA_COUNT.add(&metrics::CONTEXT, 1, &[]);
}
}
Err(err) => {
logger::error!("Err: Deleting Card From Locker : {}", err);
retry_delete_tokenize(db, &delete_tokenize_data.pm, tokenize_tracker.to_owned())
.await?;
- metrics::RETRIED_DELETE_DATA_COUNT.add(&metrics::CONTEXT, 1, &[]);
+ scheduler_metrics::RETRIED_DELETE_DATA_COUNT.add(&metrics::CONTEXT, 1, &[]);
}
}
Ok(())
diff --git a/crates/router/src/core/payments/access_token.rs b/crates/router/src/core/payments/access_token.rs
index 0ff7a1baeee..3bf162192bb 100644
--- a/crates/router/src/core/payments/access_token.rs
+++ b/crates/router/src/core/payments/access_token.rs
@@ -8,7 +8,7 @@ use crate::{
errors::{self, RouterResult},
payments,
},
- routes::AppState,
+ routes::{metrics, AppState},
services,
types::{self, api as api_types, storage, transformers::ForeignInto},
};
@@ -180,6 +180,13 @@ pub async fn refresh_connector_auth(
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not refresh access token")?;
-
+ metrics::ACCESS_TOKEN_CREATION.add(
+ &metrics::CONTEXT,
+ 1,
+ &[metrics::request::add_attributes(
+ "connector",
+ connector.connector_name.to_string(),
+ )],
+ );
Ok(access_token_router_data.response)
}
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index a63508ac7a8..642b9fb867e 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -7,8 +7,7 @@ use crate::{
mandate,
payments::{self, access_token, transformers, PaymentData},
},
- routes::AppState,
- scheduler::metrics,
+ routes::{metrics, AppState},
services,
types::{self, api, storage},
};
diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs
index 40ba12c072b..276cc6b9bdc 100644
--- a/crates/router/src/core/payments/flows/cancel_flow.rs
+++ b/crates/router/src/core/payments/flows/cancel_flow.rs
@@ -6,7 +6,7 @@ use crate::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, transformers, PaymentData},
},
- routes::AppState,
+ routes::{metrics, AppState},
services,
types::{self, api, storage},
};
@@ -43,6 +43,14 @@ impl Feature<api::Void, types::PaymentsCancelData>
call_connector_action: payments::CallConnectorAction,
_merchant_account: &storage::MerchantAccount,
) -> RouterResult<Self> {
+ metrics::PAYMENT_CANCEL_COUNT.add(
+ &metrics::CONTEXT,
+ 1,
+ &[metrics::request::add_attributes(
+ "connector",
+ connector.connector_name.to_string(),
+ )],
+ );
self.decide_flow(
state,
connector,
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index 8f3a408f32d..e4d85883e2d 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -8,7 +8,8 @@ use crate::{
errors::{self, ConnectorErrorExt, RouterResult},
payments::{self, access_token, transformers, PaymentData},
},
- routes, services,
+ routes::{self, metrics},
+ services,
types::{self, api, storage},
utils::OptionExt,
};
@@ -44,6 +45,14 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio
call_connector_action: payments::CallConnectorAction,
_merchant_account: &storage::MerchantAccount,
) -> RouterResult<Self> {
+ metrics::SESSION_TOKEN_CREATED.add(
+ &metrics::CONTEXT,
+ 1,
+ &[metrics::request::add_attributes(
+ "connector",
+ connector.connector_name.to_string(),
+ )],
+ );
self.decide_flow(
state,
connector,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 8901eb20854..e6af0924201 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -20,8 +20,8 @@ use crate::{
payment_methods::{cards, vault},
},
db::StorageInterface,
- routes::AppState,
- scheduler::{metrics, workflows::payment_sync},
+ routes::{metrics, AppState},
+ scheduler::{metrics as scheduler_metrics, workflows::payment_sync},
services,
types::{
api::{self, enums as api_enums, CustomerAcceptanceExt, MandateValidationFieldsExt},
@@ -483,7 +483,7 @@ where
match schedule_time {
Some(stime) => {
- metrics::TASKS_ADDED_COUNT.add(&metrics::CONTEXT, 1, &[]); // Metrics
+ scheduler_metrics::TASKS_ADDED_COUNT.add(&metrics::CONTEXT, 1, &[]); // Metrics
super::add_process_sync_task(&*state.store, payment_attempt, stime)
.await
.into_report()
@@ -663,6 +663,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>(
..storage::CustomerNew::default()
};
+ metrics::CUSTOMER_CREATED.add(&metrics::CONTEXT, 1, &[]);
db.insert_customer(new_customer).await
}
})
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 1455c03883a..27134555b3c 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -10,6 +10,7 @@ use crate::{
payments::PaymentData,
},
db::StorageInterface,
+ routes::metrics,
services::RedirectForm,
types::{
self, api,
@@ -323,6 +324,10 @@ async fn payment_response_update_tracker<F: Clone, T>(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not parse the connector response")?;
+ if router_data.status == enums::AttemptStatus::Charged {
+ metrics::SUCCESSFUL_PAYMENT.add(&metrics::CONTEXT, 1, &[]);
+ }
+
let payment_attempt_update = storage::PaymentAttemptUpdate::ResponseUpdate {
status: router_data.status,
connector: Some(router_data.connector),
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 74800cc70d0..426ed72e627 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -11,7 +11,7 @@ use crate::{
utils as core_utils,
},
db, logger,
- routes::AppState,
+ routes::{metrics, AppState},
scheduler::{process_data, utils as process_tracker_utils, workflows::payment_sync},
services,
types::{
@@ -98,6 +98,16 @@ pub async fn trigger_refund_to_gateway(
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)?;
let connector_id = connector.to_string();
+
+ metrics::REFUND_COUNT.add(
+ &metrics::CONTEXT,
+ 1,
+ &[metrics::request::add_attributes(
+ "connector",
+ connector.to_string(),
+ )],
+ );
+
let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_id,
@@ -164,13 +174,25 @@ pub async fn trigger_refund_to_gateway(
refund_error_message: Some(err.message),
refund_error_code: Some(err.code),
},
- Ok(response) => storage::RefundUpdate::Update {
- connector_refund_id: response.connector_refund_id,
- refund_status: response.refund_status,
- sent_to_gateway: true,
- refund_error_message: None,
- refund_arn: "".to_string(),
- },
+ Ok(response) => {
+ if response.refund_status == storage_models::enums::RefundStatus::Success {
+ metrics::SUCCESSFUL_REFUND.add(
+ &metrics::CONTEXT,
+ 1,
+ &[metrics::request::add_attributes(
+ "connector",
+ connector.connector_name.to_string(),
+ )],
+ )
+ }
+ storage::RefundUpdate::Update {
+ connector_refund_id: response.connector_refund_id,
+ refund_status: response.refund_status,
+ sent_to_gateway: true,
+ refund_error_message: None,
+ refund_arn: "".to_string(),
+ }
+ }
};
let response = state
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index 744dfd52618..d542595d585 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -29,7 +29,9 @@ pub async fn merchant_account_create(
req: HttpRequest,
json_payload: web::Json<admin::MerchantAccountCreate>,
) -> HttpResponse {
+ let flow = Flow::MerchantsAccountCreate;
api::server_wrap(
+ flow,
state.get_ref(),
&req,
json_payload.into_inner(),
@@ -60,11 +62,13 @@ pub async fn retrieve_merchant_account(
req: HttpRequest,
mid: web::Path<String>,
) -> HttpResponse {
+ let flow = Flow::MerchantsAccountRetrieve;
let payload = web::Json(admin::MerchantId {
merchant_id: mid.into_inner(),
})
.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
payload,
@@ -97,8 +101,10 @@ pub async fn update_merchant_account(
mid: web::Path<String>,
json_payload: web::Json<admin::MerchantAccountUpdate>,
) -> HttpResponse {
+ let flow = Flow::MerchantsAccountUpdate;
let merchant_id = mid.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
json_payload.into_inner(),
@@ -130,11 +136,13 @@ pub async fn delete_merchant_account(
req: HttpRequest,
mid: web::Path<String>,
) -> HttpResponse {
+ let flow = Flow::MerchantsAccountDelete;
let payload = web::Json(admin::MerchantId {
merchant_id: mid.into_inner(),
})
.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
payload,
@@ -166,8 +174,10 @@ pub async fn payment_connector_create(
path: web::Path<String>,
json_payload: web::Json<admin::MerchantConnector>,
) -> HttpResponse {
+ let flow = Flow::MerchantConnectorsCreate;
let merchant_id = path.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
json_payload.into_inner(),
@@ -202,6 +212,7 @@ pub async fn payment_connector_retrieve(
req: HttpRequest,
path: web::Path<(String, String)>,
) -> HttpResponse {
+ let flow = Flow::MerchantConnectorsRetrieve;
let (merchant_id, merchant_connector_id) = path.into_inner();
let payload = web::Json(admin::MerchantConnectorId {
merchant_id,
@@ -209,6 +220,7 @@ pub async fn payment_connector_retrieve(
})
.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
payload,
@@ -244,8 +256,10 @@ pub async fn payment_connector_list(
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
+ let flow = Flow::MerchantConnectorsList;
let merchant_id = path.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
merchant_id,
@@ -282,8 +296,10 @@ pub async fn payment_connector_update(
path: web::Path<(String, String)>,
json_payload: web::Json<admin::MerchantConnector>,
) -> HttpResponse {
+ let flow = Flow::MerchantConnectorsUpdate;
let (merchant_id, merchant_connector_id) = path.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
json_payload.into_inner(),
@@ -320,6 +336,7 @@ pub async fn payment_connector_delete(
req: HttpRequest,
path: web::Path<(String, String)>,
) -> HttpResponse {
+ let flow = Flow::MerchantConnectorsDelete;
let (merchant_id, merchant_connector_id) = path.into_inner();
let payload = web::Json(admin::MerchantConnectorId {
merchant_id,
@@ -327,6 +344,7 @@ pub async fn payment_connector_delete(
})
.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
payload,
@@ -348,9 +366,11 @@ pub async fn merchant_account_toggle_kv(
path: web::Path<String>,
json_payload: web::Json<admin::ToggleKVRequest>,
) -> HttpResponse {
+ let flow = Flow::ConfigKeyUpdate;
let payload = json_payload.into_inner();
let merchant_id = path.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
(merchant_id, payload),
@@ -371,8 +391,10 @@ pub async fn merchant_account_kv_status(
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
+ let flow = Flow::ConfigKeyFetch;
let merchant_id = path.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
merchant_id,
diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs
index 700c44a1511..629fd519335 100644
--- a/crates/router/src/routes/api_keys.rs
+++ b/crates/router/src/routes/api_keys.rs
@@ -32,10 +32,12 @@ pub async fn api_key_create(
path: web::Path<String>,
json_payload: web::Json<api_types::CreateApiKeyRequest>,
) -> impl Responder {
+ let flow = Flow::ApiKeyCreate;
let payload = json_payload.into_inner();
let merchant_id = path.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
payload,
@@ -79,9 +81,11 @@ pub async fn api_key_retrieve(
req: HttpRequest,
path: web::Path<(String, String)>,
) -> impl Responder {
+ let flow = Flow::ApiKeyRetrieve;
let (_merchant_id, key_id) = path.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
&key_id,
@@ -117,10 +121,12 @@ pub async fn api_key_update(
path: web::Path<(String, String)>,
json_payload: web::Json<api_types::UpdateApiKeyRequest>,
) -> impl Responder {
+ let flow = Flow::ApiKeyUpdate;
let (_merchant_id, key_id) = path.into_inner();
let payload = json_payload.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
(&key_id, payload),
@@ -155,9 +161,11 @@ pub async fn api_key_revoke(
req: HttpRequest,
path: web::Path<(String, String)>,
) -> impl Responder {
+ let flow = Flow::ApiKeyRevoke;
let (_merchant_id, key_id) = path.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
&key_id,
@@ -192,12 +200,14 @@ pub async fn api_key_list(
path: web::Path<String>,
query: web::Query<api_types::ListApiKeyConstraints>,
) -> impl Responder {
+ let flow = Flow::ApiKeyList;
let list_api_key_constraints = query.into_inner();
let limit = list_api_key_constraints.limit;
let offset = list_api_key_constraints.skip;
let merchant_id = path.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
(limit, offset, merchant_id),
diff --git a/crates/router/src/routes/configs.rs b/crates/router/src/routes/configs.rs
index be38027f80f..96c1c5a7db9 100644
--- a/crates/router/src/routes/configs.rs
+++ b/crates/router/src/routes/configs.rs
@@ -14,9 +14,11 @@ pub async fn config_key_retrieve(
req: HttpRequest,
path: web::Path<String>,
) -> impl Responder {
+ let flow = Flow::ConfigKeyFetch;
let key = path.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
&key,
@@ -33,11 +35,13 @@ pub async fn config_key_update(
path: web::Path<String>,
json_payload: web::Json<api_types::ConfigUpdate>,
) -> impl Responder {
+ let flow = Flow::ConfigKeyUpdate;
let mut payload = json_payload.into_inner();
let key = path.into_inner();
payload.key = key;
api::server_wrap(
+ flow,
state.get_ref(),
&req,
&payload,
diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs
index af5b7b0433f..58d06439e59 100644
--- a/crates/router/src/routes/customers.rs
+++ b/crates/router/src/routes/customers.rs
@@ -29,7 +29,9 @@ pub async fn customers_create(
req: HttpRequest,
json_payload: web::Json<customers::CustomerRequest>,
) -> HttpResponse {
+ let flow = Flow::CustomersCreate;
api::server_wrap(
+ flow,
state.get_ref(),
&req,
json_payload.into_inner(),
@@ -60,6 +62,7 @@ pub async fn customers_retrieve(
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
+ let flow = Flow::CustomersRetrieve;
let payload = web::Json(customers::CustomerId {
customer_id: path.into_inner(),
})
@@ -72,6 +75,7 @@ pub async fn customers_retrieve(
};
api::server_wrap(
+ flow,
state.get_ref(),
&req,
payload,
@@ -104,9 +108,11 @@ pub async fn customers_update(
path: web::Path<String>,
mut json_payload: web::Json<customers::CustomerRequest>,
) -> HttpResponse {
+ let flow = Flow::CustomersUpdate;
let customer_id = path.into_inner();
json_payload.customer_id = customer_id;
api::server_wrap(
+ flow,
state.get_ref(),
&req,
json_payload.into_inner(),
@@ -137,11 +143,13 @@ pub async fn customers_delete(
req: HttpRequest,
path: web::Path<String>,
) -> impl Responder {
+ let flow = Flow::CustomersCreate;
let payload = web::Json(customers::CustomerId {
customer_id: path.into_inner(),
})
.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
payload,
@@ -157,11 +165,13 @@ pub async fn get_customer_mandates(
req: HttpRequest,
path: web::Path<String>,
) -> impl Responder {
+ let flow = Flow::CustomersGetMandates;
let customer_id = customers::CustomerId {
customer_id: path.into_inner(),
};
api::server_wrap(
+ flow,
state.get_ref(),
&req,
customer_id,
diff --git a/crates/router/src/routes/ephemeral_key.rs b/crates/router/src/routes/ephemeral_key.rs
index 398aa7004fa..bd5ca361bfa 100644
--- a/crates/router/src/routes/ephemeral_key.rs
+++ b/crates/router/src/routes/ephemeral_key.rs
@@ -14,8 +14,10 @@ pub async fn ephemeral_key_create(
req: HttpRequest,
json_payload: web::Json<customers::CustomerId>,
) -> HttpResponse {
+ let flow = Flow::EphemeralKeyCreate;
let payload = json_payload.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
payload,
@@ -33,8 +35,10 @@ pub async fn ephemeral_key_delete(
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
+ let flow = Flow::EphemeralKeyDelete;
let payload = path.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
payload,
diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs
index 1cf8ff98586..b980f082122 100644
--- a/crates/router/src/routes/mandates.rs
+++ b/crates/router/src/routes/mandates.rs
@@ -32,10 +32,12 @@ pub async fn get_mandate(
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
+ let flow = Flow::MandatesRetrieve;
let mandate_id = mandates::MandateId {
mandate_id: path.into_inner(),
};
api::server_wrap(
+ flow,
state.get_ref(),
&req,
mandate_id,
@@ -69,10 +71,12 @@ pub async fn revoke_mandate(
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
+ let flow = Flow::MandatesRevoke;
let mandate_id = mandates::MandateId {
mandate_id: path.into_inner(),
};
api::server_wrap(
+ flow,
state.get_ref(),
&req,
mandate_id,
diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs
index 73ae14f5e69..133a01bb5cd 100644
--- a/crates/router/src/routes/metrics.rs
+++ b/crates/router/src/routes/metrics.rs
@@ -1,4 +1,4 @@
-use router_env::{counter_metric, global_meter, metrics_context};
+use router_env::{counter_metric, global_meter, histogram_metric, metrics_context};
metrics_context!(CONTEXT);
global_meter!(GLOBAL_METER, "ROUTER_API");
@@ -7,3 +7,66 @@ counter_metric!(HEALTH_METRIC, GLOBAL_METER); // No. of health API hits
counter_metric!(KV_MISS, GLOBAL_METER); // No. of KV misses
#[cfg(feature = "kms")]
counter_metric!(AWS_KMS_FAILURES, GLOBAL_METER); // No. of AWS KMS API failures
+
+// API Level Metrics
+counter_metric!(REQUESTS_RECEIVED, GLOBAL_METER);
+counter_metric!(FAILED_REQUEST, GLOBAL_METER);
+histogram_metric!(REQUEST_TIME, GLOBAL_METER);
+
+// Operation Level Metrics
+counter_metric!(PAYMENT_COUNT, GLOBAL_METER);
+counter_metric!(SUCCESSFUL_PAYMENT, GLOBAL_METER);
+
+counter_metric!(REFUND_COUNT, GLOBAL_METER);
+counter_metric!(SUCCESSFUL_REFUND, GLOBAL_METER);
+
+counter_metric!(PAYMENT_CANCEL_COUNT, GLOBAL_METER);
+counter_metric!(SUCCESSFUL_CANCEL, GLOBAL_METER);
+
+counter_metric!(MANDATE_COUNT, GLOBAL_METER);
+counter_metric!(SUBSEQUENT_MANDATE_PAYMENT, GLOBAL_METER);
+
+counter_metric!(RETRY_COUNT, GLOBAL_METER);
+
+counter_metric!(STORED_TO_LOCKER, GLOBAL_METER);
+counter_metric!(GET_FROM_LOCKER, GLOBAL_METER);
+counter_metric!(DELETE_FROM_LOCKER, GLOBAL_METER);
+
+counter_metric!(CREATED_TOKENIZED_CARD, GLOBAL_METER);
+counter_metric!(DELETED_TOKENIZED_CARD, GLOBAL_METER);
+counter_metric!(GET_TOKENIZED_CARD, GLOBAL_METER);
+
+counter_metric!(CUSTOMER_CREATED, GLOBAL_METER);
+counter_metric!(CUSTOMER_REDACTED, GLOBAL_METER);
+
+counter_metric!(API_KEY_CREATED, GLOBAL_METER);
+counter_metric!(API_KEY_REVOKED, GLOBAL_METER);
+
+// Flow Specific Metrics
+
+counter_metric!(ACCESS_TOKEN_CREATION, GLOBAL_METER);
+histogram_metric!(CONNECTOR_REQUEST_TIME, GLOBAL_METER);
+counter_metric!(SESSION_TOKEN_CREATED, GLOBAL_METER);
+
+counter_metric!(CONNECTOR_CALL_COUNT, GLOBAL_METER); // Attributes needed
+
+counter_metric!(THREE_DS_PAYMENT_COUNT, GLOBAL_METER);
+counter_metric!(THREE_DS_DOWNGRADE_COUNT, GLOBAL_METER);
+
+counter_metric!(RESPONSE_DESERIALIZATION_FAILURE, GLOBAL_METER);
+counter_metric!(CONNECTOR_ERROR_RESPONSE_COUNT, GLOBAL_METER);
+counter_metric!(REQUEST_TIMEOUT_COUNT, GLOBAL_METER);
+
+// Connector Level Metric
+counter_metric!(REQUEST_BUILD_FAILURE, GLOBAL_METER);
+counter_metric!(UNIMPLEMENTED_FLOW, GLOBAL_METER);
+
+// Service Level
+counter_metric!(CARD_LOCKER_FAILURES, GLOBAL_METER);
+counter_metric!(TEMP_LOCKER_FAILURES, GLOBAL_METER);
+histogram_metric!(CARD_ADD_TIME, GLOBAL_METER);
+histogram_metric!(CARD_GET_TIME, GLOBAL_METER);
+histogram_metric!(CARD_DELETE_TIME, GLOBAL_METER);
+
+pub mod request;
+pub mod utils;
diff --git a/crates/router/src/routes/metrics/request.rs b/crates/router/src/routes/metrics/request.rs
new file mode 100644
index 00000000000..487db67b1e1
--- /dev/null
+++ b/crates/router/src/routes/metrics/request.rs
@@ -0,0 +1,36 @@
+use super::utils as metric_utils;
+
+pub async fn record_request_time_metric<F, R>(future: F, flow: router_env::Flow) -> R
+where
+ F: futures::Future<Output = R>,
+{
+ let key = "request_type";
+ super::REQUESTS_RECEIVED.add(&super::CONTEXT, 1, &[add_attributes(key, flow.to_string())]);
+ let (result, time) = metric_utils::time_future(future).await;
+ super::REQUEST_TIME.record(
+ &super::CONTEXT,
+ time.as_secs_f64(),
+ &[add_attributes(key, flow.to_string())],
+ );
+ result
+}
+
+#[inline]
+pub async fn record_card_operation_time<F, R>(
+ future: F,
+ metric: &once_cell::sync::Lazy<router_env::opentelemetry::metrics::Histogram<f64>>,
+) -> R
+where
+ F: futures::Future<Output = R>,
+{
+ let (result, time) = metric_utils::time_future(future).await;
+ metric.record(&super::CONTEXT, time.as_secs_f64(), &[]);
+ result
+}
+
+pub fn add_attributes<T: Into<router_env::opentelemetry::Value>>(
+ key: &'static str,
+ value: T,
+) -> router_env::opentelemetry::KeyValue {
+ router_env::opentelemetry::KeyValue::new(key, value)
+}
diff --git a/crates/router/src/routes/metrics/utils.rs b/crates/router/src/routes/metrics/utils.rs
new file mode 100644
index 00000000000..28bf2131f9e
--- /dev/null
+++ b/crates/router/src/routes/metrics/utils.rs
@@ -0,0 +1,12 @@
+use std::time;
+
+#[inline]
+pub async fn time_future<F, R>(future: F) -> (R, time::Duration)
+where
+ F: futures::Future<Output = R>,
+{
+ let start = time::Instant::now();
+ let result = future.await;
+ let time_spent = start.elapsed();
+ (result, time_spent)
+}
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index f2efc1db991..05f3d110e9d 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -29,7 +29,9 @@ pub async fn create_payment_method_api(
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodCreate>,
) -> HttpResponse {
+ let flow = Flow::PaymentMethodsCreate;
api::server_wrap(
+ flow,
state.get_ref(),
&req,
json_payload.into_inner(),
@@ -71,6 +73,7 @@ pub async fn list_payment_method_api(
req: HttpRequest,
json_payload: web::Query<payment_methods::PaymentMethodListRequest>,
) -> HttpResponse {
+ let flow = Flow::PaymentMethodsList;
let payload = json_payload.into_inner();
let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) {
@@ -79,6 +82,7 @@ pub async fn list_payment_method_api(
};
api::server_wrap(
+ flow,
state.get_ref(),
&req,
payload,
@@ -119,6 +123,7 @@ pub async fn list_customer_payment_method_api(
req: HttpRequest,
json_payload: web::Query<payment_methods::PaymentMethodListRequest>,
) -> HttpResponse {
+ let flow = Flow::CustomerPaymentMethodsList;
let customer_id = customer_id.into_inner().0;
let auth_type = match auth::is_ephemeral_auth(req.headers(), &*state.store, &customer_id).await
@@ -128,6 +133,7 @@ pub async fn list_customer_payment_method_api(
};
api::server_wrap(
+ flow,
state.get_ref(),
&req,
json_payload.into_inner(),
@@ -162,12 +168,14 @@ pub async fn payment_method_retrieve_api(
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
+ let flow = Flow::PaymentMethodsRetrieve;
let payload = web::Json(PaymentMethodId {
payment_method_id: path.into_inner(),
})
.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
payload,
@@ -202,9 +210,11 @@ pub async fn payment_method_update_api(
path: web::Path<String>,
json_payload: web::Json<payment_methods::PaymentMethodUpdate>,
) -> HttpResponse {
+ let flow = Flow::PaymentMethodsUpdate;
let payment_method_id = path.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
json_payload.into_inner(),
@@ -244,10 +254,12 @@ pub async fn payment_method_delete_api(
req: HttpRequest,
payment_method_id: web::Path<(String,)>,
) -> HttpResponse {
+ let flow = Flow::PaymentMethodsDelete;
let pm = PaymentMethodId {
payment_method_id: payment_method_id.into_inner().0,
};
api::server_wrap(
+ flow,
state.get_ref(),
&req,
pm,
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index ccfc18692ad..05e65e49100 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -34,6 +34,7 @@ pub async fn payments_create(
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsRequest>,
) -> impl Responder {
+ let flow = Flow::PaymentsCreate;
let payload = json_payload.into_inner();
if let Some(api_enums::CaptureMethod::Scheduled) = payload.capture_method {
@@ -41,6 +42,7 @@ pub async fn payments_create(
};
api::server_wrap(
+ flow,
state.get_ref(),
&req,
payload,
@@ -82,13 +84,14 @@ pub async fn payments_start(
req: actix_web::HttpRequest,
path: web::Path<(String, String, String)>,
) -> impl Responder {
+ let flow = Flow::PaymentsStart;
let (payment_id, merchant_id, attempt_id) = path.into_inner();
let payload = payment_types::PaymentsStartRequest {
payment_id: payment_id.clone(),
merchant_id: merchant_id.clone(),
attempt_id: attempt_id.clone(),
};
- api::server_wrap(
+ api::server_wrap(flow,
state.get_ref(),
&req,
payload,
@@ -133,6 +136,7 @@ pub async fn payments_retrieve(
path: web::Path<String>,
json_payload: web::Query<payment_types::PaymentRetrieveBody>,
) -> impl Responder {
+ let flow = Flow::PaymentsRetrieve;
let payload = payment_types::PaymentsRetrieveRequest {
resource_id: payment_types::PaymentIdType::PaymentIntentId(path.to_string()),
merchant_id: json_payload.merchant_id.clone(),
@@ -146,6 +150,7 @@ pub async fn payments_retrieve(
};
api::server_wrap(
+ flow,
state.get_ref(),
&req,
payload,
@@ -190,6 +195,7 @@ pub async fn payments_update(
json_payload: web::Json<payment_types::PaymentsRequest>,
path: web::Path<String>,
) -> impl Responder {
+ let flow = Flow::PaymentsUpdate;
let mut payload = json_payload.into_inner();
if let Some(api_enums::CaptureMethod::Scheduled) = payload.capture_method {
@@ -206,6 +212,7 @@ pub async fn payments_update(
};
api::server_wrap(
+ flow,
state.get_ref(),
&req,
payload,
@@ -249,6 +256,7 @@ pub async fn payments_confirm(
json_payload: web::Json<payment_types::PaymentsRequest>,
path: web::Path<String>,
) -> impl Responder {
+ let flow = Flow::PaymentsConfirm;
let mut payload = json_payload.into_inner();
if let Some(api_enums::CaptureMethod::Scheduled) = payload.capture_method {
@@ -266,6 +274,7 @@ pub async fn payments_confirm(
};
api::server_wrap(
+ flow,
state.get_ref(),
&req,
payload,
@@ -309,12 +318,14 @@ pub async fn payments_capture(
json_payload: web::Json<payment_types::PaymentsCaptureRequest>,
path: web::Path<String>,
) -> impl Responder {
+ let flow = Flow::PaymentsCapture;
let capture_payload = payment_types::PaymentsCaptureRequest {
payment_id: Some(path.into_inner()),
..json_payload.into_inner()
};
api::server_wrap(
+ flow,
state.get_ref(),
&req,
capture_payload,
@@ -354,9 +365,11 @@ pub async fn payments_connector_session(
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsSessionRequest>,
) -> impl Responder {
+ let flow = Flow::PaymentsSessionToken;
let sessions_payload = json_payload.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
sessions_payload,
@@ -405,6 +418,7 @@ pub async fn payments_redirect_response(
req: actix_web::HttpRequest,
path: web::Path<(String, String, String)>,
) -> impl Responder {
+ let flow = Flow::PaymentsRedirect;
let (payment_id, merchant_id, connector) = path.into_inner();
let param_string = req.query_string();
@@ -417,6 +431,7 @@ pub async fn payments_redirect_response(
connector: Some(connector),
};
api::server_wrap(
+ flow,
state.get_ref(),
&req,
payload,
@@ -439,6 +454,7 @@ pub async fn payments_complete_authorize(
json_payload: web::Form<serde_json::Value>,
path: web::Path<(String, String, String)>,
) -> impl Responder {
+ let flow = Flow::PaymentsRedirect;
let (payment_id, merchant_id, connector) = path.into_inner();
let param_string = req.query_string();
@@ -451,6 +467,7 @@ pub async fn payments_complete_authorize(
connector: Some(connector),
};
api::server_wrap(
+ flow,
state.get_ref(),
&req,
payload,
@@ -492,11 +509,13 @@ pub async fn payments_cancel(
json_payload: web::Json<payment_types::PaymentsCancelRequest>,
path: web::Path<String>,
) -> impl Responder {
+ let flow = Flow::PaymentsCancel;
let mut payload = json_payload.into_inner();
let payment_id = path.into_inner();
payload.payment_id = payment_id;
api::server_wrap(
+ flow,
state.get_ref(),
&req,
payload,
@@ -548,8 +567,10 @@ pub async fn payments_list(
req: actix_web::HttpRequest,
payload: web::Query<payment_types::PaymentListConstraints>,
) -> impl Responder {
+ let flow = Flow::PaymentsList;
let payload = payload.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
payload,
diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs
index 3c3408674b5..844c47837ab 100644
--- a/crates/router/src/routes/payouts.rs
+++ b/crates/router/src/routes/payouts.rs
@@ -7,36 +7,42 @@ use router_env::{instrument, tracing, Flow};
#[instrument(skip_all, fields(flow = ?Flow::PayoutsCreate))]
// #[post("/create")]
pub async fn payouts_create() -> impl Responder {
+ let _flow = Flow::PayoutsCreate;
http_response("create")
}
#[instrument(skip_all, fields(flow = ?Flow::PayoutsRetrieve))]
// #[get("/retrieve")]
pub async fn payouts_retrieve() -> impl Responder {
+ let _flow = Flow::PayoutsRetrieve;
http_response("retrieve")
}
#[instrument(skip_all, fields(flow = ?Flow::PayoutsUpdate))]
// #[post("/update")]
pub async fn payouts_update() -> impl Responder {
+ let _flow = Flow::PayoutsUpdate;
http_response("update")
}
#[instrument(skip_all, fields(flow = ?Flow::PayoutsReverse))]
// #[post("/reverse")]
pub async fn payouts_reverse() -> impl Responder {
+ let _flow = Flow::PayoutsReverse;
http_response("reverse")
}
#[instrument(skip_all, fields(flow = ?Flow::PayoutsCancel))]
// #[post("/cancel")]
pub async fn payouts_cancel() -> impl Responder {
+ let _flow = Flow::PayoutsCancel;
http_response("cancel")
}
#[instrument(skip_all, fields(flow = ?Flow::PayoutsAccounts))]
// #[get("/accounts")]
pub async fn payouts_accounts() -> impl Responder {
+ let _flow = Flow::PayoutsAccounts;
http_response("accounts")
}
diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs
index c1b60ab43a9..e59854919ce 100644
--- a/crates/router/src/routes/refunds.rs
+++ b/crates/router/src/routes/refunds.rs
@@ -30,7 +30,9 @@ pub async fn refunds_create(
req: HttpRequest,
json_payload: web::Json<refunds::RefundRequest>,
) -> HttpResponse {
+ let flow = Flow::RefundsCreate;
api::server_wrap(
+ flow,
state.get_ref(),
&req,
json_payload.into_inner(),
@@ -64,9 +66,11 @@ pub async fn refunds_retrieve(
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
+ let flow = Flow::RefundsRetrieve;
let refund_id = path.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
refund_id,
@@ -104,8 +108,10 @@ pub async fn refunds_update(
json_payload: web::Json<refunds::RefundUpdateRequest>,
path: web::Path<String>,
) -> HttpResponse {
+ let flow = Flow::RefundsUpdate;
let refund_id = path.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
json_payload.into_inner(),
@@ -148,7 +154,9 @@ pub async fn refunds_list(
req: HttpRequest,
payload: web::Query<api_models::refunds::RefundListRequest>,
) -> HttpResponse {
+ let flow = Flow::RefundsList;
api::server_wrap(
+ flow,
state.get_ref(),
&req,
payload.into_inner(),
diff --git a/crates/router/src/routes/webhooks.rs b/crates/router/src/routes/webhooks.rs
index ef1b74c54d9..e6c8801a40c 100644
--- a/crates/router/src/routes/webhooks.rs
+++ b/crates/router/src/routes/webhooks.rs
@@ -15,9 +15,11 @@ pub async fn receive_incoming_webhook<W: api_types::OutgoingWebhookType>(
body: web::Bytes,
path: web::Path<(String, String)>,
) -> impl Responder {
+ let flow = Flow::IncomingWebhookReceive;
let (merchant_id, connector_name) = path.into_inner();
api::server_wrap(
+ flow,
state.get_ref(),
&req,
body,
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 4a861d5e928..9fcd900ba4e 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -26,7 +26,7 @@ use crate::{
payments,
},
logger,
- routes::{app::AppStateInfo, AppState},
+ routes::{app::AppStateInfo, metrics, AppState},
services::authentication as auth,
types::{self, api, storage, ErrorResponse},
};
@@ -103,9 +103,17 @@ pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Re
fn build_request(
&self,
- _req: &types::RouterData<T, Req, Resp>,
+ req: &types::RouterData<T, Req, Resp>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ metrics::UNIMPLEMENTED_FLOW.add(
+ &metrics::CONTEXT,
+ 1,
+ &[metrics::request::add_attributes(
+ "connector",
+ req.connector.clone(),
+ )],
+ );
Ok(None)
}
@@ -179,7 +187,40 @@ where
Ok(router_data)
}
payments::CallConnectorAction::Trigger => {
- match connector_integration.build_request(req, &state.conf.connectors)? {
+ metrics::CONNECTOR_CALL_COUNT.add(
+ &metrics::CONTEXT,
+ 1,
+ &[
+ metrics::request::add_attributes("connector", req.connector.to_string()),
+ metrics::request::add_attributes(
+ "flow",
+ std::any::type_name::<T>()
+ .split("::")
+ .last()
+ .unwrap_or_default()
+ .to_string(),
+ ),
+ ],
+ );
+ match connector_integration
+ .build_request(req, &state.conf.connectors)
+ .map_err(|error| {
+ if matches!(
+ error.current_context(),
+ &errors::ConnectorError::RequestEncodingFailed
+ | &errors::ConnectorError::RequestEncodingFailedWithReason(_)
+ ) {
+ metrics::RESPONSE_DESERIALIZATION_FAILURE.add(
+ &metrics::CONTEXT,
+ 1,
+ &[metrics::request::add_attributes(
+ "connector",
+ req.connector.to_string(),
+ )],
+ )
+ }
+ error
+ })? {
Some(request) => {
logger::debug!(connector_request=?request);
let response = call_connector_api(state, request).await;
@@ -187,8 +228,32 @@ where
match response {
Ok(body) => {
let response = match body {
- Ok(body) => connector_integration.handle_response(req, body)?,
+ Ok(body) => connector_integration
+ .handle_response(req, body)
+ .map_err(|error| {
+ if error.current_context()
+ == &errors::ConnectorError::ResponseDeserializationFailed
+ {
+ metrics::RESPONSE_DESERIALIZATION_FAILURE.add(
+ &metrics::CONTEXT,
+ 1,
+ &[metrics::request::add_attributes(
+ "connector",
+ req.connector.to_string(),
+ )],
+ )
+ }
+ error
+ })?,
Err(body) => {
+ metrics::CONNECTOR_ERROR_RESPONSE_COUNT.add(
+ &metrics::CONTEXT,
+ 1,
+ &[metrics::request::add_attributes(
+ "connector",
+ req.connector.clone(),
+ )],
+ );
let error = connector_integration.get_error_response(body)?;
router_data.response = Err(error);
@@ -277,7 +342,10 @@ async fn send_request(
.send()
.await
.map_err(|error| match error {
- error if error.is_timeout() => errors::ApiClientError::RequestTimeoutReceived,
+ error if error.is_timeout() => {
+ metrics::REQUEST_BUILD_FAILURE.add(&metrics::CONTEXT, 1, &[]);
+ errors::ApiClientError::RequestTimeoutReceived
+ }
_ => errors::ApiClientError::RequestNotSent(error.to_string()),
})
.into_report()
@@ -454,6 +522,7 @@ where
fields(request_method, request_url_path)
)]
pub async fn server_wrap<'a, 'b, A, T, U, Q, F, Fut, E>(
+ flow: router_env::Flow,
state: &'b A,
request: &'a HttpRequest,
payload: T,
@@ -476,8 +545,12 @@ where
let start_instant = Instant::now();
logger::info!(tag = ?Tag::BeginRequest);
-
- let res = match server_wrap_util(state, request, payload, func, api_auth).await {
+ let res = match metrics::request::record_request_time_metric(
+ server_wrap_util(state, request, payload, func, api_auth),
+ flow,
+ )
+ .await
+ {
Ok(ApplicationResponse::Json(response)) => match serde_json::to_string(&response) {
Ok(res) => http_response_json(res),
Err(_) => http_response_err(
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 58800d7c3d4..dc0cab6a837 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -138,6 +138,8 @@ pub enum Flow {
PayoutsCancel,
/// Payouts accounts flow.
PayoutsAccounts,
+ /// Payments Redirect flow.
+ PaymentsRedirect,
/// Refunds create flow.
RefundsCreate,
/// Refunds retrieve flow.
|
feat
|
adding metrics for tracking behavior throughout the `router` crate (#768)
|
4dae29221f2d24a0f4299e641cfe22ab705fae25
|
2024-10-01 05:57:30
|
github-actions
|
chore(version): 2024.10.01.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 91fa92cb40c..d706486e920 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,23 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 2024.10.01.0
+
+### Features
+
+- **ci:** Add cypress tests to github ci ([#5183](https://github.com/juspay/hyperswitch/pull/5183)) ([`e4a35d3`](https://github.com/juspay/hyperswitch/commit/e4a35d366b7db151378d6c1f61e4d01d1c7ed37f))
+
+### Bug Fixes
+
+- **connector:**
+ - Update API endpoints for signifyd ([#5957](https://github.com/juspay/hyperswitch/pull/5957)) ([`b3e57d5`](https://github.com/juspay/hyperswitch/commit/b3e57d5b0e54c14322a37828e4aa66b7495f2bdf))
+ - [Adyen Platform] wasm configs and webhook status mapping ([#6161](https://github.com/juspay/hyperswitch/pull/6161)) ([`6b0f7e4`](https://github.com/juspay/hyperswitch/commit/6b0f7e4870886997ca300935e727283c739be486))
+- **payments_list:** Remove time range to filter payments attempts ([#6159](https://github.com/juspay/hyperswitch/pull/6159)) ([`da1f23d`](https://github.com/juspay/hyperswitch/commit/da1f23d2353c19f43f23f0938c1c73e109edc0c5))
+
+**Full Changelog:** [`2024.09.30.0...2024.10.01.0`](https://github.com/juspay/hyperswitch/compare/2024.09.30.0...2024.10.01.0)
+
+- - -
+
## 2024.09.30.0
### Features
|
chore
|
2024.10.01.0
|
5ee217175c13d24cd0365f8622209cdca5a7d2eb
|
2025-03-19 16:13:38
|
sweta-sharma
|
fix(connector): WASM fixed in Getnet (#7564)
| false
|
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index e166e2795c6..f9cbeb878c6 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -1687,7 +1687,7 @@ merchant_secret="Source verification key"
[[getnet.credit]]
payment_method_type = "UnionPay"
[[getnet.credit]]
- payment_method_type = "Rupay"
+ payment_method_type = "RuPay"
[[getnet.credit]]
payment_method_type = "Maestro"
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index 1555814a5ee..da8299d2b24 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -1405,7 +1405,7 @@ merchant_secret="Source verification key"
[[getnet.credit]]
payment_method_type = "UnionPay"
[[getnet.credit]]
- payment_method_type = "Rupay"
+ payment_method_type = "RuPay"
[[getnet.credit]]
payment_method_type = "Maestro"
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index 45fc6d51eef..19b70441e01 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -1637,7 +1637,7 @@ merchant_secret="Source verification key"
[[getnet.credit]]
payment_method_type = "UnionPay"
[[getnet.credit]]
- payment_method_type = "Rupay"
+ payment_method_type = "RuPay"
[[getnet.credit]]
payment_method_type = "Maestro"
|
fix
|
WASM fixed in Getnet (#7564)
|
02074dfc23f1a126e76935ba5311c6aed6590ca5
|
2024-01-30 12:35:42
|
Amisha Prabhat
|
feat(core): update card_details for an existing mandate (#3452)
| false
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 57c66dc5a7b..8c27f498d7a 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -617,10 +617,18 @@ pub enum MandateReferenceId {
NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns
}
-#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)]
pub struct ConnectorMandateReferenceId {
pub connector_mandate_id: Option<String>,
pub payment_method_id: Option<String>,
+ pub update_history: Option<Vec<UpdateHistory>>,
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)]
+pub struct UpdateHistory {
+ pub connector_mandate_id: Option<String>,
+ pub payment_method_id: String,
+ pub original_payment_id: Option<String>,
}
impl MandateIds {
@@ -637,6 +645,8 @@ impl MandateIds {
#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct MandateData {
+ /// A way to update the mandate's payment method details
+ pub update_mandate_id: Option<String>,
/// A concent from the customer to store the payment method
pub customer_acceptance: Option<CustomerAcceptance>,
/// A way to select the type of mandate used
diff --git a/crates/data_models/src/mandates.rs b/crates/data_models/src/mandates.rs
index afdcda3a40e..319a78cf661 100644
--- a/crates/data_models/src/mandates.rs
+++ b/crates/data_models/src/mandates.rs
@@ -9,6 +9,13 @@ use error_stack::{IntoReport, ResultExt};
use masking::{PeekInterface, Secret};
use time::PrimitiveDateTime;
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub struct MandateDetails {
+ pub update_mandate_id: Option<String>,
+ pub mandate_type: Option<MandateDataType>,
+}
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum MandateDataType {
@@ -16,6 +23,13 @@ pub enum MandateDataType {
MultiUse(Option<MandateAmountData>),
}
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+#[serde(untagged)]
+pub enum MandateTypeDetails {
+ MandateType(MandateDataType),
+ MandateDetails(MandateDetails),
+}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct MandateAmountData {
pub amount: i64,
@@ -29,6 +43,8 @@ pub struct MandateAmountData {
// information about creating mandates
#[derive(Default, Eq, PartialEq, Debug, Clone)]
pub struct MandateData {
+ /// A way to update the mandate's payment method details
+ pub update_mandate_id: Option<String>,
/// A concent from the customer to store the payment method
pub customer_acceptance: Option<CustomerAcceptance>,
/// A way to select the type of mandate used
@@ -90,6 +106,7 @@ impl From<ApiMandateData> for MandateData {
Self {
customer_acceptance: value.customer_acceptance.map(|d| d.into()),
mandate_type: value.mandate_type.map(|d| d.into()),
+ update_mandate_id: value.update_mandate_id,
}
}
}
diff --git a/crates/data_models/src/payments/payment_attempt.rs b/crates/data_models/src/payments/payment_attempt.rs
index 3e6ba9e37f8..e6b9950b459 100644
--- a/crates/data_models/src/payments/payment_attempt.rs
+++ b/crates/data_models/src/payments/payment_attempt.rs
@@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use super::PaymentIntent;
-use crate::{errors, mandates::MandateDataType, ForeignIDRef};
+use crate::{errors, mandates::MandateTypeDetails, ForeignIDRef};
#[async_trait::async_trait]
pub trait PaymentAttemptInterface {
@@ -143,7 +143,7 @@ pub struct PaymentAttempt {
pub straight_through_algorithm: Option<serde_json::Value>,
pub preprocessing_step_id: Option<String>,
// providing a location to store mandate details intermediately for transaction
- pub mandate_details: Option<MandateDataType>,
+ pub mandate_details: Option<MandateTypeDetails>,
pub error_reason: Option<String>,
pub multiple_capture_count: Option<i16>,
// reference to the payment at connector side
@@ -184,7 +184,7 @@ pub struct PaymentAttemptNew {
pub attempt_id: String,
pub status: storage_enums::AttemptStatus,
pub amount: i64,
- /// amount + surcharge_amount + tax_amount
+ /// amount + surcharge_amount + tax_amount
/// This field will always be derived before updating in the Database
pub net_amount: i64,
pub currency: Option<storage_enums::Currency>,
@@ -221,7 +221,7 @@ pub struct PaymentAttemptNew {
pub business_sub_label: Option<String>,
pub straight_through_algorithm: Option<serde_json::Value>,
pub preprocessing_step_id: Option<String>,
- pub mandate_details: Option<MandateDataType>,
+ pub mandate_details: Option<MandateTypeDetails>,
pub error_reason: Option<String>,
pub connector_response_reference_id: Option<String>,
pub multiple_capture_count: Option<i16>,
diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs
index a06937c99a6..babffdbc4a8 100644
--- a/crates/diesel_models/src/enums.rs
+++ b/crates/diesel_models/src/enums.rs
@@ -166,6 +166,17 @@ use diesel::{
expression::AsExpression,
sql_types::Jsonb,
};
+
+#[derive(
+ serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression,
+)]
+#[diesel(sql_type = Jsonb)]
+#[serde(rename_all = "snake_case")]
+pub struct MandateDetails {
+ pub update_mandate_id: Option<String>,
+ pub mandate_type: Option<MandateDataType>,
+}
+
#[derive(
serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression,
)]
@@ -185,6 +196,7 @@ where
Ok(serde_json::from_value(value)?)
}
}
+
impl ToSql<Jsonb, diesel::pg::Pg> for MandateDataType
where
serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>,
@@ -199,6 +211,40 @@ where
}
}
+#[derive(
+ serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression,
+)]
+#[diesel(sql_type = Jsonb)]
+#[serde(untagged)]
+#[serde(rename_all = "snake_case")]
+pub enum MandateTypeDetails {
+ MandateType(MandateDataType),
+ MandateDetails(MandateDetails),
+}
+
+impl<DB: Backend> FromSql<Jsonb, DB> for MandateTypeDetails
+where
+ serde_json::Value: FromSql<Jsonb, DB>,
+{
+ fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
+ let value = <serde_json::Value as FromSql<Jsonb, DB>>::from_sql(bytes)?;
+ Ok(serde_json::from_value(value)?)
+ }
+}
+impl ToSql<Jsonb, diesel::pg::Pg> for MandateTypeDetails
+where
+ serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>,
+{
+ fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, diesel::pg::Pg>) -> diesel::serialize::Result {
+ let value = serde_json::to_value(self)?;
+
+ // the function `reborrow` only works in case of `Pg` backend. But, in case of other backends
+ // please refer to the diesel migration blog:
+ // https://github.com/Diesel-rs/Diesel/blob/master/guide_drafts/migration_guide.md#changed-tosql-implementations
+ <serde_json::Value as ToSql<Jsonb, diesel::pg::Pg>>::to_sql(&value, &mut out.reborrow())
+ }
+}
+
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct MandateAmountData {
pub amount: i64,
diff --git a/crates/diesel_models/src/mandate.rs b/crates/diesel_models/src/mandate.rs
index cc3474914c0..31c6ef62f2b 100644
--- a/crates/diesel_models/src/mandate.rs
+++ b/crates/diesel_models/src/mandate.rs
@@ -75,6 +75,12 @@ pub enum MandateUpdate {
ConnectorReferenceUpdate {
connector_mandate_ids: Option<pii::SecretSerdeValue>,
},
+ ConnectorMandateIdUpdate {
+ connector_mandate_id: Option<String>,
+ connector_mandate_ids: Option<pii::SecretSerdeValue>,
+ payment_method_id: String,
+ original_payment_id: Option<String>,
+ },
}
#[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)]
@@ -89,6 +95,9 @@ pub struct MandateUpdateInternal {
mandate_status: Option<storage_enums::MandateStatus>,
amount_captured: Option<i64>,
connector_mandate_ids: Option<pii::SecretSerdeValue>,
+ connector_mandate_id: Option<String>,
+ payment_method_id: Option<String>,
+ original_payment_id: Option<String>,
}
impl From<MandateUpdate> for MandateUpdateInternal {
@@ -98,16 +107,34 @@ impl From<MandateUpdate> for MandateUpdateInternal {
mandate_status: Some(mandate_status),
connector_mandate_ids: None,
amount_captured: None,
+ connector_mandate_id: None,
+ payment_method_id: None,
+ original_payment_id: None,
},
MandateUpdate::CaptureAmountUpdate { amount_captured } => Self {
mandate_status: None,
amount_captured,
connector_mandate_ids: None,
+ connector_mandate_id: None,
+ payment_method_id: None,
+ original_payment_id: None,
},
MandateUpdate::ConnectorReferenceUpdate {
- connector_mandate_ids: connector_mandate_id,
+ connector_mandate_ids,
+ } => Self {
+ connector_mandate_ids,
+ ..Default::default()
+ },
+ MandateUpdate::ConnectorMandateIdUpdate {
+ connector_mandate_id,
+ connector_mandate_ids,
+ payment_method_id,
+ original_payment_id,
} => Self {
- connector_mandate_ids: connector_mandate_id,
+ connector_mandate_id,
+ connector_mandate_ids,
+ payment_method_id: Some(payment_method_id),
+ original_payment_id,
..Default::default()
},
}
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index d08c146b0b8..4a7603384c5 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -51,7 +51,7 @@ pub struct PaymentAttempt {
pub straight_through_algorithm: Option<serde_json::Value>,
pub preprocessing_step_id: Option<String>,
// providing a location to store mandate details intermediately for transaction
- pub mandate_details: Option<storage_enums::MandateDataType>,
+ pub mandate_details: Option<storage_enums::MandateTypeDetails>,
pub error_reason: Option<String>,
pub multiple_capture_count: Option<i16>,
// reference to the payment at connector side
@@ -126,7 +126,7 @@ pub struct PaymentAttemptNew {
pub business_sub_label: Option<String>,
pub straight_through_algorithm: Option<serde_json::Value>,
pub preprocessing_step_id: Option<String>,
- pub mandate_details: Option<storage_enums::MandateDataType>,
+ pub mandate_details: Option<storage_enums::MandateTypeDetails>,
pub error_reason: Option<String>,
pub connector_response_reference_id: Option<String>,
pub multiple_capture_count: Option<i16>,
diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs
index 5a1ea696c56..5a2226f0676 100644
--- a/crates/diesel_models/src/user/sample_data.rs
+++ b/crates/diesel_models/src/user/sample_data.rs
@@ -5,7 +5,7 @@ use common_enums::{
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
-use crate::{enums::MandateDataType, schema::payment_attempt, PaymentAttemptNew};
+use crate::{enums::MandateTypeDetails, schema::payment_attempt, PaymentAttemptNew};
#[derive(
Clone, Debug, Default, diesel::Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize,
@@ -50,7 +50,7 @@ pub struct PaymentAttemptBatchNew {
pub business_sub_label: Option<String>,
pub straight_through_algorithm: Option<serde_json::Value>,
pub preprocessing_step_id: Option<String>,
- pub mandate_details: Option<MandateDataType>,
+ pub mandate_details: Option<MandateTypeDetails>,
pub error_reason: Option<String>,
pub connector_response_reference_id: Option<String>,
pub connector_transaction_id: Option<String>,
diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs
index 810e0ed1d28..aac150b5079 100644
--- a/crates/router/src/compatibility/stripe/payment_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs
@@ -753,6 +753,7 @@ impl ForeignTryFrom<(Option<MandateData>, Option<String>)> for Option<payments::
user_agent: online.user_agent,
}),
}),
+ update_mandate_id: None,
});
Ok(mandate_data)
}
diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs
index b6837d14f82..7299ef624d8 100644
--- a/crates/router/src/core/mandate.rs
+++ b/crates/router/src/core/mandate.rs
@@ -1,13 +1,13 @@
+pub mod helpers;
pub mod utils;
-
use api_models::payments;
use common_utils::{ext_traits::Encode, pii};
-use diesel_models::enums as storage_enums;
+use diesel_models::{enums as storage_enums, Mandate};
use error_stack::{report, IntoReport, ResultExt};
use futures::future;
use router_env::{instrument, logger, tracing};
-use super::payments::helpers;
+use super::payments::helpers as payment_helper;
use crate::{
core::{
errors::{self, RouterResponse, StorageErrorExt},
@@ -64,34 +64,17 @@ pub async fn revoke_mandate(
common_enums::MandateStatus::Active
| common_enums::MandateStatus::Inactive
| common_enums::MandateStatus::Pending => {
- let profile_id = if let Some(ref payment_id) = mandate.original_payment_id {
- let pi = db
- .find_payment_intent_by_payment_id_merchant_id(
- payment_id,
- &merchant_account.merchant_id,
- merchant_account.storage_scheme,
- )
- .await
- .change_context(errors::ApiErrorResponse::PaymentNotFound)?;
- let profile_id = pi.profile_id.clone().ok_or(
- errors::ApiErrorResponse::BusinessProfileNotFound {
- id: pi
- .profile_id
- .unwrap_or_else(|| "Profile id is Null".to_string()),
- },
- )?;
- Ok(profile_id)
- } else {
- Err(errors::ApiErrorResponse::PaymentNotFound)
- }?;
+ let profile_id =
+ helpers::get_profile_id_for_mandate(&state, &merchant_account, mandate.clone())
+ .await?;
- let merchant_connector_account = helpers::get_merchant_connector_account(
+ let merchant_connector_account = payment_helper::get_merchant_connector_account(
&state,
&merchant_account.merchant_id,
None,
&key_store,
&profile_id,
- &mandate.connector,
+ &mandate.connector.clone(),
mandate.merchant_connector_id.as_ref(),
)
.await?;
@@ -243,7 +226,72 @@ where
_ => Some(router_data.request.get_payment_method_data()),
}
}
+pub async fn update_mandate_procedure<F, FData>(
+ state: &AppState,
+ resp: types::RouterData<F, FData, types::PaymentsResponseData>,
+ mandate: Mandate,
+ merchant_id: &str,
+ pm_id: Option<String>,
+) -> errors::RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>>
+where
+ FData: MandateBehaviour,
+{
+ let mandate_details = match &resp.response {
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ mandate_reference, ..
+ }) => mandate_reference,
+ Ok(_) => Err(errors::ApiErrorResponse::InternalServerError)
+ .into_report()
+ .attach_printable("Unexpected response received")?,
+ Err(_) => return Ok(resp),
+ };
+ let old_record = payments::UpdateHistory {
+ connector_mandate_id: mandate.connector_mandate_id,
+ payment_method_id: mandate.payment_method_id,
+ original_payment_id: mandate.original_payment_id,
+ };
+
+ let mandate_ref = mandate
+ .connector_mandate_ids
+ .parse_value::<payments::ConnectorMandateReferenceId>("Connector Reference Id")
+ .change_context(errors::ApiErrorResponse::MandateDeserializationFailed)?;
+
+ let mut update_history = mandate_ref.update_history.unwrap_or_default();
+ update_history.push(old_record);
+
+ let updated_mandate_ref = payments::ConnectorMandateReferenceId {
+ connector_mandate_id: mandate_details
+ .as_ref()
+ .and_then(|mandate_ref| mandate_ref.connector_mandate_id.clone()),
+ payment_method_id: pm_id.clone(),
+ update_history: Some(update_history),
+ };
+
+ let connector_mandate_ids =
+ Encode::<types::MandateReference>::encode_to_value(&updated_mandate_ref)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .map(masking::Secret::new)?;
+
+ let _update_mandate_details = state
+ .store
+ .update_mandate_by_merchant_id_mandate_id(
+ merchant_id,
+ &mandate.mandate_id,
+ diesel_models::MandateUpdate::ConnectorMandateIdUpdate {
+ connector_mandate_id: mandate_details
+ .as_ref()
+ .and_then(|man_ref| man_ref.connector_mandate_id.clone()),
+ connector_mandate_ids: Some(connector_mandate_ids),
+ payment_method_id: pm_id
+ .unwrap_or("Error retrieving the payment_method_id".to_string()),
+ original_payment_id: Some(resp.payment_id.clone()),
+ },
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::MandateUpdateFailed)?;
+ Ok(resp)
+}
pub async fn mandate_procedure<F, FData>(
state: &AppState,
mut resp: types::RouterData<F, FData, types::PaymentsResponseData>,
@@ -324,7 +372,7 @@ where
})
.transpose()?;
- if let Some(new_mandate_data) = helpers::generate_mandate(
+ if let Some(new_mandate_data) = payment_helper::generate_mandate(
resp.merchant_id.clone(),
resp.payment_id.clone(),
resp.connector.clone(),
@@ -363,6 +411,8 @@ where
api_models::payments::ConnectorMandateReferenceId {
connector_mandate_id: connector_id.connector_mandate_id,
payment_method_id: connector_id.payment_method_id,
+ update_history:None,
+
}
)))
}));
diff --git a/crates/router/src/core/mandate/helpers.rs b/crates/router/src/core/mandate/helpers.rs
new file mode 100644
index 00000000000..150130ed9e5
--- /dev/null
+++ b/crates/router/src/core/mandate/helpers.rs
@@ -0,0 +1,35 @@
+use common_utils::errors::CustomResult;
+use diesel_models::Mandate;
+use error_stack::ResultExt;
+
+use crate::{core::errors, routes::AppState, types::domain};
+
+pub async fn get_profile_id_for_mandate(
+ state: &AppState,
+ merchant_account: &domain::MerchantAccount,
+ mandate: Mandate,
+) -> CustomResult<String, errors::ApiErrorResponse> {
+ let profile_id = if let Some(ref payment_id) = mandate.original_payment_id {
+ let pi = state
+ .store
+ .find_payment_intent_by_payment_id_merchant_id(
+ payment_id,
+ &merchant_account.merchant_id,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::PaymentNotFound)?;
+ let profile_id =
+ pi.profile_id
+ .clone()
+ .ok_or(errors::ApiErrorResponse::BusinessProfileNotFound {
+ id: pi
+ .profile_id
+ .unwrap_or_else(|| "Profile id is Null".to_string()),
+ })?;
+ Ok(profile_id)
+ } else {
+ Err(errors::ApiErrorResponse::PaymentNotFound)
+ }?;
+ Ok(profile_id)
+}
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 3dbd6fcb215..e08dbc61f5e 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -1823,14 +1823,24 @@ pub async fn list_payment_methods(
} else {
api_surcharge_decision_configs::MerchantSurchargeConfigs::default()
};
+ print!("PAMT{:?}", payment_attempt);
Ok(services::ApplicationResponse::Json(
api::PaymentMethodListResponse {
redirect_url: merchant_account.return_url,
merchant_name: merchant_account.merchant_name,
payment_type,
payment_methods: payment_method_responses,
- mandate_payment: payment_attempt.and_then(|inner| inner.mandate_details).map(
- |d| match d {
+ mandate_payment: payment_attempt
+ .and_then(|inner| inner.mandate_details)
+ .and_then(|man_type_details| match man_type_details {
+ data_models::mandates::MandateTypeDetails::MandateType(mandate_type) => {
+ Some(mandate_type)
+ }
+ data_models::mandates::MandateTypeDetails::MandateDetails(mandate_details) => {
+ mandate_details.mandate_type
+ }
+ })
+ .map(|d| match d {
data_models::mandates::MandateDataType::SingleUse(i) => {
api::MandateType::SingleUse(api::MandateAmountData {
amount: i.amount,
@@ -1852,8 +1862,7 @@ pub async fn list_payment_methods(
data_models::mandates::MandateDataType::MultiUse(None) => {
api::MandateType::MultiUse(None)
}
- },
- ),
+ }),
show_surcharge_breakup_screen: merchant_surcharge_configs
.show_surcharge_breakup_screen
.unwrap_or_default(),
diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
index d6343ed871b..8b0b54158fd 100644
--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs
+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
@@ -1,9 +1,10 @@
use async_trait::async_trait;
+use error_stack::{IntoReport, ResultExt};
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
- errors::{self, ConnectorErrorExt, RouterResult},
+ errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt},
mandate,
payments::{
self, access_token, customers, helpers, tokenization, transformers, PaymentData,
@@ -65,16 +66,16 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup
types::SetupMandateRequestData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
+
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
- call_connector_action,
+ call_connector_action.clone(),
connector_request,
)
.await
.to_setup_mandate_failed_response()?;
-
let pm_id = Box::pin(tokenization::save_payment_method(
state,
connector,
@@ -86,14 +87,84 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup
))
.await?;
- mandate::mandate_procedure(
- state,
- resp,
- maybe_customer,
- pm_id,
- connector.merchant_connector_id.clone(),
- )
- .await
+ if let Some(mandate_id) = self
+ .request
+ .setup_mandate_details
+ .as_ref()
+ .and_then(|mandate_data| mandate_data.update_mandate_id.clone())
+ {
+ let mandate = state
+ .store
+ .find_mandate_by_merchant_id_mandate_id(&merchant_account.merchant_id, &mandate_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
+
+ let profile_id = mandate::helpers::get_profile_id_for_mandate(
+ state,
+ merchant_account,
+ mandate.clone(),
+ )
+ .await?;
+ match resp.response {
+ Ok(types::PaymentsResponseData::TransactionResponse { .. }) => {
+ let connector_integration: services::BoxedConnectorIntegration<
+ '_,
+ types::api::MandateRevoke,
+ types::MandateRevokeRequestData,
+ types::MandateRevokeResponseData,
+ > = connector.connector.get_connector_integration();
+ let merchant_connector_account = helpers::get_merchant_connector_account(
+ state,
+ &merchant_account.merchant_id,
+ None,
+ key_store,
+ &profile_id,
+ &mandate.connector,
+ mandate.merchant_connector_id.as_ref(),
+ )
+ .await?;
+
+ let router_data = mandate::utils::construct_mandate_revoke_router_data(
+ merchant_connector_account,
+ merchant_account,
+ mandate.clone(),
+ )
+ .await?;
+
+ let _response = services::execute_connector_processing_step(
+ state,
+ connector_integration,
+ &router_data,
+ call_connector_action,
+ None,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ // TODO:Add the revoke mandate task to process tracker
+ mandate::update_mandate_procedure(
+ state,
+ resp,
+ mandate,
+ &merchant_account.merchant_id,
+ pm_id,
+ )
+ .await
+ }
+ Ok(_) => Err(errors::ApiErrorResponse::InternalServerError)
+ .into_report()
+ .attach_printable("Unexpected response received")?,
+ Err(_) => Ok(resp),
+ }
+ } else {
+ mandate::mandate_procedure(
+ state,
+ resp,
+ maybe_customer,
+ pm_id,
+ connector.merchant_connector_id.clone(),
+ )
+ .await
+ }
}
async fn add_access_token<'a>(
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 0cbed255348..520582eb22f 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -840,7 +840,7 @@ fn validate_new_mandate_request(
let mandate_details = match mandate_data.mandate_type {
Some(api_models::payments::MandateType::SingleUse(details)) => Some(details),
Some(api_models::payments::MandateType::MultiUse(details)) => details,
- None => None,
+ _ => None,
};
mandate_details.and_then(|md| md.start_date.zip(md.end_date)).map(|(start_date, end_date)|
utils::when (start_date >= end_date, || {
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index c81145c5de7..14fc28d6723 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -431,7 +431,29 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
// The operation merges mandate data from both request and payment_attempt
setup_mandate = setup_mandate.map(|mut sm| {
- sm.mandate_type = payment_attempt.mandate_details.clone().or(sm.mandate_type);
+ sm.mandate_type = payment_attempt
+ .mandate_details
+ .clone()
+ .and_then(|mandate| match mandate {
+ data_models::mandates::MandateTypeDetails::MandateType(mandate_type) => {
+ Some(mandate_type)
+ }
+ data_models::mandates::MandateTypeDetails::MandateDetails(mandate_details) => {
+ mandate_details.mandate_type
+ }
+ })
+ .or(sm.mandate_type);
+ sm.update_mandate_id = payment_attempt
+ .mandate_details
+ .clone()
+ .and_then(|mandate| match mandate {
+ data_models::mandates::MandateTypeDetails::MandateType(_) => None,
+ data_models::mandates::MandateTypeDetails::MandateDetails(update_id) => {
+ Some(update_id.update_mandate_id)
+ }
+ })
+ .flatten()
+ .or(sm.update_mandate_id);
sm
});
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 2b25a74deb1..d02ad15fbd6 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -3,7 +3,10 @@ use std::marker::PhantomData;
use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
use common_utils::ext_traits::{AsyncExt, Encode, ValueExt};
-use data_models::{mandates::MandateData, payments::payment_attempt::PaymentAttempt};
+use data_models::{
+ mandates::{MandateData, MandateDetails, MandateTypeDetails},
+ payments::payment_attempt::PaymentAttempt,
+};
use diesel_models::ephemeral_key;
use error_stack::{self, ResultExt};
use masking::PeekInterface;
@@ -255,7 +258,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment {
payment_id: payment_id.clone(),
})?;
-
+ // connector mandate reference update history
let mandate_id = request
.mandate_id
.as_ref()
@@ -284,10 +287,11 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
api_models::payments::MandateIds {
mandate_id: mandate_obj.mandate_id,
mandate_reference_id: Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
- api_models::payments::ConnectorMandateReferenceId {
- connector_mandate_id: connector_id.connector_mandate_id,
- payment_method_id: connector_id.payment_method_id,
- },
+ api_models::payments::ConnectorMandateReferenceId{
+ connector_mandate_id: connector_id.connector_mandate_id,
+ payment_method_id: connector_id.payment_method_id,
+ update_history: None
+ }
))
}
}),
@@ -701,6 +705,35 @@ impl PaymentCreate {
.surcharge_details
.and_then(|surcharge_details| surcharge_details.tax_amount);
+ if request.mandate_data.as_ref().map_or(false, |mandate_data| {
+ mandate_data.update_mandate_id.is_some() && mandate_data.mandate_type.is_some()
+ }) {
+ Err(errors::ApiErrorResponse::InvalidRequestData {message:"Only one field out of 'mandate_type' and 'update_mandate_id' was expected, found both".to_string()})?
+ }
+
+ let mandate_dets = if let Some(update_id) = request
+ .mandate_data
+ .as_ref()
+ .and_then(|inner| inner.update_mandate_id.clone())
+ {
+ let mandate_data = MandateDetails {
+ update_mandate_id: Some(update_id),
+ mandate_type: None,
+ };
+ Some(MandateTypeDetails::MandateDetails(mandate_data))
+ } else {
+ // let mandate_type: data_models::mandates::MandateDataType =
+
+ let mandate_data = MandateDetails {
+ update_mandate_id: None,
+ mandate_type: request
+ .mandate_data
+ .as_ref()
+ .and_then(|inner| inner.mandate_type.clone().map(Into::into)),
+ };
+ Some(MandateTypeDetails::MandateDetails(mandate_data))
+ };
+
Ok((
storage::PaymentAttemptNew {
payment_id: payment_id.to_string(),
@@ -727,10 +760,7 @@ impl PaymentCreate {
business_sub_label: request.business_sub_label.clone(),
surcharge_amount,
tax_amount,
- mandate_details: request
- .mandate_data
- .as_ref()
- .and_then(|inner| inner.mandate_type.clone().map(Into::into)),
+ mandate_details: mandate_dets,
..storage::PaymentAttemptNew::default()
},
additional_pm_data,
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index e002b92d181..015ef5cea6e 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -255,10 +255,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
api_models::payments::MandateIds {
mandate_id: mandate_obj.mandate_id,
mandate_reference_id: Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
- api_models::payments::ConnectorMandateReferenceId {
- connector_mandate_id: connector_id.connector_mandate_id,
- payment_method_id: connector_id.payment_method_id,
- },
+ api_models::payments::ConnectorMandateReferenceId {connector_mandate_id:connector_id.connector_mandate_id,payment_method_id:connector_id.payment_method_id, update_history: None },
))
}
}),
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 5f0c702a29d..61917fdcd2e 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -636,6 +636,7 @@ where
api::MandateType::MultiUse(None)
}
}),
+ update_mandate_id: d.update_mandate_id,
}),
auth_flow == services::AuthFlow::Merchant,
)
diff --git a/crates/router/src/db/mandate.rs b/crates/router/src/db/mandate.rs
index fcd71719657..0cf5cabf2e4 100644
--- a/crates/router/src/db/mandate.rs
+++ b/crates/router/src/db/mandate.rs
@@ -202,6 +202,18 @@ impl MandateInterface for MockDb {
} => {
mandate.connector_mandate_ids = connector_mandate_ids;
}
+
+ diesel_models::MandateUpdate::ConnectorMandateIdUpdate {
+ connector_mandate_id,
+ connector_mandate_ids,
+ payment_method_id,
+ original_payment_id,
+ } => {
+ mandate.connector_mandate_ids = connector_mandate_ids;
+ mandate.connector_mandate_id = connector_mandate_id;
+ mandate.payment_method_id = payment_method_id;
+ mandate.original_payment_id = original_payment_id
+ }
}
Ok(mandate.clone())
}
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 307dff55071..bc8ab2e05e7 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -1674,7 +1674,7 @@ pub fn build_redirection_form(
// Initialize the ThreeDSService
const threeDS = gateway.get3DSecure();
-
+
const options = {{
customerVaultId: '{customer_vault_id}',
currency: '{currency}',
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 786a8c55182..41aefc9026d 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -323,6 +323,7 @@ impl ForeignFrom<api_models::payments::MandateData> for data_models::mandates::M
data_models::mandates::MandateDataType::MultiUse(None)
}
}),
+ update_mandate_id: d.update_mandate_id,
}
}
}
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index f8f752c6bc8..b8d71cb32b7 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -2,7 +2,7 @@ use api_models::enums::{AuthenticationType, Connector, PaymentMethod, PaymentMet
use common_utils::{errors::CustomResult, fallback_reverse_lookup_not_found};
use data_models::{
errors,
- mandates::{MandateAmountData, MandateDataType},
+ mandates::{MandateAmountData, MandateDataType, MandateDetails, MandateTypeDetails},
payments::{
payment_attempt::{
PaymentAttempt, PaymentAttemptInterface, PaymentAttemptNew, PaymentAttemptUpdate,
@@ -14,6 +14,7 @@ use data_models::{
use diesel_models::{
enums::{
MandateAmountData as DieselMandateAmountData, MandateDataType as DieselMandateType,
+ MandateDetails as DieselMandateDetails, MandateTypeDetails as DieselMandateTypeOrDetails,
MerchantStorageScheme,
},
kv,
@@ -999,6 +1000,50 @@ impl DataModelExt for MandateAmountData {
}
}
}
+impl DataModelExt for MandateDetails {
+ type StorageModel = DieselMandateDetails;
+ fn to_storage_model(self) -> Self::StorageModel {
+ DieselMandateDetails {
+ update_mandate_id: self.update_mandate_id,
+ mandate_type: self
+ .mandate_type
+ .map(|mand_type| mand_type.to_storage_model()),
+ }
+ }
+ fn from_storage_model(storage_model: Self::StorageModel) -> Self {
+ Self {
+ update_mandate_id: storage_model.update_mandate_id,
+ mandate_type: storage_model
+ .mandate_type
+ .map(MandateDataType::from_storage_model),
+ }
+ }
+}
+impl DataModelExt for MandateTypeDetails {
+ type StorageModel = DieselMandateTypeOrDetails;
+
+ fn to_storage_model(self) -> Self::StorageModel {
+ match self {
+ Self::MandateType(mandate_type) => {
+ DieselMandateTypeOrDetails::MandateType(mandate_type.to_storage_model())
+ }
+ Self::MandateDetails(mandate_details) => {
+ DieselMandateTypeOrDetails::MandateDetails(mandate_details.to_storage_model())
+ }
+ }
+ }
+
+ fn from_storage_model(storage_model: Self::StorageModel) -> Self {
+ match storage_model {
+ DieselMandateTypeOrDetails::MandateType(data) => {
+ Self::MandateType(MandateDataType::from_storage_model(data))
+ }
+ DieselMandateTypeOrDetails::MandateDetails(data) => {
+ Self::MandateDetails(MandateDetails::from_storage_model(data))
+ }
+ }
+ }
+}
impl DataModelExt for MandateDataType {
type StorageModel = DieselMandateType;
@@ -1123,7 +1168,7 @@ impl DataModelExt for PaymentAttempt {
preprocessing_step_id: storage_model.preprocessing_step_id,
mandate_details: storage_model
.mandate_details
- .map(MandateDataType::from_storage_model),
+ .map(MandateTypeDetails::from_storage_model),
error_reason: storage_model.error_reason,
multiple_capture_count: storage_model.multiple_capture_count,
connector_response_reference_id: storage_model.connector_response_reference_id,
@@ -1231,7 +1276,7 @@ impl DataModelExt for PaymentAttemptNew {
preprocessing_step_id: storage_model.preprocessing_step_id,
mandate_details: storage_model
.mandate_details
- .map(MandateDataType::from_storage_model),
+ .map(MandateTypeDetails::from_storage_model),
error_reason: storage_model.error_reason,
connector_response_reference_id: storage_model.connector_response_reference_id,
multiple_capture_count: storage_model.multiple_capture_count,
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 7858029961a..09cb5fe1404 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -9026,6 +9026,11 @@
"MandateData": {
"type": "object",
"properties": {
+ "update_mandate_id": {
+ "type": "string",
+ "description": "A way to update the mandate's payment method details",
+ "nullable": true
+ },
"customer_acceptance": {
"allOf": [
{
|
feat
|
update card_details for an existing mandate (#3452)
|
28b102de2496c0880b6b232ddc82b1ef227af4da
|
2023-09-11 12:10:48
|
Nishant Joshi
|
feat(confirm): reduce the database calls to 2 stages in case of non-retry (#2113)
| false
|
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 701ccb5df85..83f33fb3e87 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -2772,7 +2772,7 @@ impl AttemptType {
}
}
- pub async fn get_connector_response(
+ pub async fn get_or_insert_connector_response(
&self,
payment_attempt: &PaymentAttempt,
db: &dyn StorageInterface,
@@ -2799,6 +2799,30 @@ impl AttemptType {
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound),
}
}
+
+ pub async fn get_connector_response(
+ &self,
+ db: &dyn StorageInterface,
+ payment_id: &str,
+ merchant_id: &str,
+ attempt_id: &str,
+ storage_scheme: storage_enums::MerchantStorageScheme,
+ ) -> RouterResult<storage::ConnectorResponse> {
+ match self {
+ Self::New => Err(errors::ApiErrorResponse::InternalServerError)
+ .into_report()
+ .attach_printable("Precondition failed, the attempt type should not be `New`"),
+ Self::SameOld => db
+ .find_connector_response_by_payment_id_merchant_id_attempt_id(
+ payment_id,
+ merchant_id,
+ attempt_id,
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound),
+ }
+ }
}
#[inline(always)]
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index e75e43fefb7..ef67315201c 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -33,7 +33,6 @@ use crate::{
pub struct PaymentConfirm;
#[async_trait]
impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentConfirm {
- #[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a AppState,
@@ -130,11 +129,89 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
key_store,
);
- let (mut payment_attempt, shipping_address, billing_address) = futures::try_join!(
- payment_attempt_fut,
- shipping_address_fut,
- billing_address_fut
- )?;
+ let config_update_fut = request
+ .merchant_connector_details
+ .to_owned()
+ .async_map(|mcd| async {
+ helpers::insert_merchant_connector_creds_to_config(
+ db,
+ merchant_account.merchant_id.as_str(),
+ mcd,
+ )
+ .await
+ })
+ .map(|x| x.transpose());
+
+ let (mut payment_attempt, shipping_address, billing_address, connector_response) =
+ match payment_intent.status {
+ api_models::enums::IntentStatus::RequiresCustomerAction
+ | api_models::enums::IntentStatus::RequiresMerchantAction
+ | api_models::enums::IntentStatus::RequiresPaymentMethod
+ | api_models::enums::IntentStatus::RequiresConfirmation => {
+ let attempt_type = helpers::AttemptType::SameOld;
+
+ let connector_response_fut = attempt_type.get_connector_response(
+ db,
+ &payment_intent.payment_id,
+ &payment_intent.merchant_id,
+ &payment_intent.active_attempt_id,
+ storage_scheme,
+ );
+
+ let (payment_attempt, shipping_address, billing_address, connector_response, _) =
+ futures::try_join!(
+ payment_attempt_fut,
+ shipping_address_fut,
+ billing_address_fut,
+ connector_response_fut,
+ config_update_fut
+ )?;
+
+ (
+ payment_attempt,
+ shipping_address,
+ billing_address,
+ connector_response,
+ )
+ }
+ _ => {
+ let (mut payment_attempt, shipping_address, billing_address, _) = futures::try_join!(
+ payment_attempt_fut,
+ shipping_address_fut,
+ billing_address_fut,
+ config_update_fut
+ )?;
+
+ let attempt_type = helpers::get_attempt_type(
+ &payment_intent,
+ &payment_attempt,
+ request,
+ "confirm",
+ )?;
+
+ (payment_intent, payment_attempt) = attempt_type
+ .modify_payment_intent_and_payment_attempt(
+ // 3
+ request,
+ payment_intent,
+ payment_attempt,
+ db,
+ storage_scheme,
+ )
+ .await?;
+
+ let connector_response = attempt_type
+ .get_or_insert_connector_response(&payment_attempt, db, storage_scheme)
+ .await?;
+
+ (
+ payment_attempt,
+ shipping_address,
+ billing_address,
+ connector_response,
+ )
+ }
+ };
payment_intent.order_details = request
.get_order_details_as_value()
@@ -142,20 +219,6 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
.attach_printable("Failed to convert order details to value")?
.or(payment_intent.order_details);
- let attempt_type =
- helpers::get_attempt_type(&payment_intent, &payment_attempt, request, "confirm")?;
-
- (payment_intent, payment_attempt) = attempt_type
- .modify_payment_intent_and_payment_attempt(
- // 3
- request,
- payment_intent,
- payment_attempt,
- db,
- storage_scheme,
- )
- .await?;
-
payment_intent.setup_future_usage = request
.setup_future_usage
.or(payment_intent.setup_future_usage);
@@ -220,25 +283,6 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
.as_ref()
.map(|mcd| mcd.creds_identifier.to_owned());
- let config_update_fut = request
- .merchant_connector_details
- .to_owned()
- .async_map(|mcd| async {
- helpers::insert_merchant_connector_creds_to_config(
- db,
- merchant_account.merchant_id.as_str(),
- mcd,
- )
- .await
- })
- .map(|x| x.transpose());
-
- let connector_response_fut =
- attempt_type.get_connector_response(&payment_attempt, db, storage_scheme);
-
- let (connector_response, _) =
- futures::try_join!(connector_response_fut, config_update_fut)?;
-
payment_intent.shipping_address_id = shipping_address.clone().map(|i| i.address_id);
payment_intent.billing_address_id = billing_address.clone().map(|i| i.address_id);
payment_intent.return_url = request
|
feat
|
reduce the database calls to 2 stages in case of non-retry (#2113)
|
96b790cb4b44cd4867be62e2889cb4aa23622161
|
2023-10-26 00:28:40
|
Mohammed Shakeel
|
feat(connector): [OpenNode] Use connector_request_reference_id as referemce to connector (#2596)
| false
|
diff --git a/crates/router/src/connector/opennode/transformers.rs b/crates/router/src/connector/opennode/transformers.rs
index aa3fae3a516..b367012ca75 100644
--- a/crates/router/src/connector/opennode/transformers.rs
+++ b/crates/router/src/connector/opennode/transformers.rs
@@ -19,6 +19,7 @@ pub struct OpennodePaymentsRequest {
auto_settle: bool,
success_url: String,
callback_url: String,
+ order_id: String,
}
impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpennodePaymentsRequest {
@@ -237,6 +238,7 @@ fn get_crypto_specific_payment_data(
auto_settle,
success_url,
callback_url,
+ order_id: item.connector_request_reference_id.clone(),
})
}
|
feat
|
[OpenNode] Use connector_request_reference_id as referemce to connector (#2596)
|
ae1edb061d38effeb12fd122b94e45fb768dd508
|
2024-06-19 00:28:19
|
Sandeep Kumar
|
fix(opensearch): handle index not present errors in search api (#4965)
| false
|
diff --git a/crates/analytics/docs/README.md b/crates/analytics/docs/README.md
index b822edd810e..da9a3c79f1f 100644
--- a/crates/analytics/docs/README.md
+++ b/crates/analytics/docs/README.md
@@ -101,4 +101,18 @@ Here's an example of how to do this:
[default.features]
audit_trail=true
system_metrics=true
-```
\ No newline at end of file
+global_search=true
+```
+
+## Viewing the data on OpenSearch Dashboard
+
+To view the data on the OpenSearch dashboard perform the following steps:
+
+- Go to the OpenSearch Dashboard home and click on `Stack Management` under the Management tab
+- Select `Index Patterns`
+- Click on `Create index pattern`
+- Define an index pattern with the same name that matches your indices and click on `Next Step`
+- Select a time field that will be used for time-based queries
+- Save the index pattern
+
+Now, head on to the `Discover` tab, to select the newly created index pattern and query the data
\ No newline at end of file
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs
index 7b19ba0ed06..e8f87aaef2e 100644
--- a/crates/analytics/src/opensearch.rs
+++ b/crates/analytics/src/opensearch.rs
@@ -76,6 +76,8 @@ pub enum OpenSearchError {
ResponseError,
#[error("Opensearch query building error")]
QueryBuildingError,
+ #[error("Opensearch deserialisation error")]
+ DeserialisationError,
}
impl ErrorSwitch<OpenSearchError> for QueryBuildingError {
@@ -111,6 +113,12 @@ impl ErrorSwitch<ApiErrorResponse> for OpenSearchError {
"Query building error",
None,
)),
+ Self::DeserialisationError => ApiErrorResponse::InternalServerError(ApiError::new(
+ "IR",
+ 0,
+ "Deserialisation error",
+ None,
+ )),
}
}
}
diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs
index dc802ff6948..8810dc1e3a1 100644
--- a/crates/analytics/src/search.rs
+++ b/crates/analytics/src/search.rs
@@ -4,7 +4,7 @@ use api_models::analytics::search::{
};
use common_utils::errors::{CustomResult, ReportSwitchExt};
use error_stack::ResultExt;
-use serde_json::Value;
+use router_env::tracing;
use strum::IntoEnumIterator;
use crate::opensearch::{
@@ -22,27 +22,59 @@ pub async fn msearch_results(
.add_filter_clause("merchant_id".to_string(), merchant_id.to_string())
.switch()?;
- let response_body = client
+ let response_text: OpenMsearchOutput = client
.execute(query_builder)
.await
.change_context(OpenSearchError::ConnectionError)?
- .json::<OpenMsearchOutput<Value>>()
+ .text()
.await
- .change_context(OpenSearchError::ResponseError)?;
+ .change_context(OpenSearchError::ResponseError)
+ .and_then(|body: String| {
+ serde_json::from_str::<OpenMsearchOutput>(&body)
+ .change_context(OpenSearchError::DeserialisationError)
+ .attach_printable(body.clone())
+ })?;
+
+ let response_body: OpenMsearchOutput = response_text;
Ok(response_body
.responses
.into_iter()
.zip(SearchIndex::iter())
- .map(|(index_hit, index)| GetSearchResponse {
- count: index_hit.hits.total.value,
- index,
- hits: index_hit
- .hits
- .hits
- .into_iter()
- .map(|hit| hit._source)
- .collect(),
+ .map(|(index_hit, index)| match index_hit {
+ OpensearchOutput::Success(success) => {
+ if success.status == 200 {
+ GetSearchResponse {
+ count: success.hits.total.value,
+ index,
+ hits: success
+ .hits
+ .hits
+ .into_iter()
+ .map(|hit| hit.source)
+ .collect(),
+ }
+ } else {
+ tracing::error!("Unexpected status code: {}", success.status,);
+ GetSearchResponse {
+ count: 0,
+ index,
+ hits: Vec::new(),
+ }
+ }
+ }
+ OpensearchOutput::Error(error) => {
+ tracing::error!(
+ index = ?index,
+ error_response = ?error,
+ "Search error"
+ );
+ GetSearchResponse {
+ count: 0,
+ index,
+ hits: Vec::new(),
+ }
+ }
})
.collect())
}
@@ -65,22 +97,54 @@ pub async fn search_results(
.set_offset_n_count(search_req.offset, search_req.count)
.switch()?;
- let response_body = client
+ let response_text: OpensearchOutput = client
.execute(query_builder)
.await
.change_context(OpenSearchError::ConnectionError)?
- .json::<OpensearchOutput<Value>>()
+ .text()
.await
- .change_context(OpenSearchError::ResponseError)?;
+ .change_context(OpenSearchError::ResponseError)
+ .and_then(|body: String| {
+ serde_json::from_str::<OpensearchOutput>(&body)
+ .change_context(OpenSearchError::DeserialisationError)
+ .attach_printable(body.clone())
+ })?;
+
+ let response_body: OpensearchOutput = response_text;
- Ok(GetSearchResponse {
- count: response_body.hits.total.value,
- index: req.index,
- hits: response_body
- .hits
- .hits
- .into_iter()
- .map(|hit| hit._source)
- .collect(),
- })
+ match response_body {
+ OpensearchOutput::Success(success) => {
+ if success.status == 200 {
+ Ok(GetSearchResponse {
+ count: success.hits.total.value,
+ index: req.index,
+ hits: success
+ .hits
+ .hits
+ .into_iter()
+ .map(|hit| hit.source)
+ .collect(),
+ })
+ } else {
+ tracing::error!("Unexpected status code: {}", success.status);
+ Ok(GetSearchResponse {
+ count: 0,
+ index: req.index,
+ hits: Vec::new(),
+ })
+ }
+ }
+ OpensearchOutput::Error(error) => {
+ tracing::error!(
+ index = ?req.index,
+ error_response = ?error,
+ "Search error"
+ );
+ Ok(GetSearchResponse {
+ count: 0,
+ index: req.index,
+ hits: Vec::new(),
+ })
+ }
+ }
}
diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs
index 6f6a3f22812..c29bb0e9f71 100644
--- a/crates/api_models/src/analytics/search.rs
+++ b/crates/api_models/src/analytics/search.rs
@@ -48,19 +48,40 @@ pub struct GetSearchResponse {
}
#[derive(Debug, serde::Deserialize)]
-pub struct OpenMsearchOutput<T> {
- pub responses: Vec<OpensearchOutput<T>>,
+pub struct OpenMsearchOutput {
+ pub responses: Vec<OpensearchOutput>,
}
#[derive(Debug, serde::Deserialize)]
-pub struct OpensearchOutput<T> {
- pub hits: OpensearchResults<T>,
+#[serde(untagged)]
+pub enum OpensearchOutput {
+ Success(OpensearchSuccess),
+ Error(OpensearchError),
}
#[derive(Debug, serde::Deserialize)]
-pub struct OpensearchResults<T> {
+pub struct OpensearchError {
+ pub error: OpensearchErrorDetails,
+ pub status: u16,
+}
+
+#[derive(Debug, serde::Deserialize)]
+pub struct OpensearchErrorDetails {
+ #[serde(rename = "type")]
+ pub error_type: String,
+ pub reason: String,
+}
+
+#[derive(Debug, serde::Deserialize)]
+pub struct OpensearchSuccess {
+ pub status: u16,
+ pub hits: OpensearchHits,
+}
+
+#[derive(Debug, serde::Deserialize)]
+pub struct OpensearchHits {
pub total: OpensearchResultsTotal,
- pub hits: Vec<OpensearchHits<T>>,
+ pub hits: Vec<OpensearchHit>,
}
#[derive(Debug, serde::Deserialize)]
@@ -69,6 +90,7 @@ pub struct OpensearchResultsTotal {
}
#[derive(Debug, serde::Deserialize)]
-pub struct OpensearchHits<T> {
- pub _source: T,
+pub struct OpensearchHit {
+ #[serde(rename = "_source")]
+ pub source: Value,
}
|
fix
|
handle index not present errors in search api (#4965)
|
603215db05b69ff6f525733afbf61b26dedd00ce
|
2023-11-03 17:36:13
|
github-actions
|
chore(version): v1.70.1
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a6f88af7c8b..a5cf72d1908 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,17 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 1.70.1 (2023-11-03)
+
+### Revert
+
+- Fix(analytics): feat(analytics): analytics APIs ([#2777](https://github.com/juspay/hyperswitch/pull/2777)) ([`169d33b`](https://github.com/juspay/hyperswitch/commit/169d33bf8157b1a9910c841c8c55eddc4d2ad168))
+
+**Full Changelog:** [`v1.70.0...v1.70.1`](https://github.com/juspay/hyperswitch/compare/v1.70.0...v1.70.1)
+
+- - -
+
+
## 1.70.0 (2023-11-03)
### Features
|
chore
|
v1.70.1
|
f0464bc4f584b52c4983df62a28befd60f67cca4
|
2023-05-04 19:22:28
|
Prasunna Soppa
|
feat(connector): add authorize, capture, void, psync, refund, rsync for Forte connector (#955)
| false
|
diff --git a/config/development.toml b/config/development.toml
index 00c5a1228de..e5b4ca00907 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -217,6 +217,10 @@ apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,D
bucket_name = ""
region = ""
+[pm_filters.forte]
+credit = {currency = "USD"}
+debit = {currency = "USD"}
+
[tokenization]
stripe = { long_lived_token = false, payment_method = "wallet" }
checkout = { long_lived_token = false, payment_method = "wallet" }
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 5ab3ac128cf..fbee4ea058e 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -596,7 +596,7 @@ pub enum Connector {
Bambora,
Dlocal,
Fiserv,
- //Forte,
+ Forte,
Globalpay,
Klarna,
Mollie,
@@ -661,7 +661,7 @@ pub enum RoutableConnectors {
Cybersource,
Dlocal,
Fiserv,
- //Forte,
+ Forte,
Globalpay,
Klarna,
Mollie,
diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs
index 7ac9e430311..6ecd6974c02 100644
--- a/crates/router/src/connector/aci/transformers.rs
+++ b/crates/router/src/connector/aci/transformers.rs
@@ -186,7 +186,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest {
}
api::PaymentMethodData::Crypto(_) | api::PaymentMethodData::BankDebit(_) => {
Err(errors::ConnectorError::NotSupported {
- payment_method: format!("{:?}", item.payment_method),
+ message: format!("{:?}", item.payment_method),
connector: "Aci",
payment_experience: api_models::enums::PaymentExperience::RedirectToUrl
.to_string(),
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 72ae3d0e5d1..ed8f5fadf8d 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -348,7 +348,7 @@ impl TryFrom<&api_enums::BankNames> for OnlineBankingCzechRepublicBanks {
api::enums::BankNames::CeskaSporitelna => Ok(Self::CS),
api::enums::BankNames::PlatnoscOnlineKartaPlatnicza => Ok(Self::C),
_ => Err(errors::ConnectorError::NotSupported {
- payment_method: String::from("BankRedirect"),
+ message: String::from("BankRedirect"),
connector: "Adyen",
payment_experience: api_enums::PaymentExperience::RedirectToUrl.to_string(),
})?,
@@ -429,7 +429,7 @@ impl TryFrom<&api_enums::BankNames> for OnlineBankingPolandBanks {
api_models::enums::BankNames::VeloBank => Ok(Self::VeloBank),
api_models::enums::BankNames::ETransferPocztowy24 => Ok(Self::ETransferPocztowy24),
_ => Err(errors::ConnectorError::NotSupported {
- payment_method: String::from("BankRedirect"),
+ message: String::from("BankRedirect"),
connector: "Adyen",
payment_experience: api_enums::PaymentExperience::RedirectToUrl.to_string(),
})?,
@@ -465,7 +465,7 @@ impl TryFrom<&api_enums::BankNames> for OnlineBankingSlovakiaBanks {
api::enums::BankNames::TatraPay => Ok(Self::Tatra),
api::enums::BankNames::Viamo => Ok(Self::Viamo),
_ => Err(errors::ConnectorError::NotSupported {
- payment_method: String::from("BankRedirect"),
+ message: String::from("BankRedirect"),
connector: "Adyen",
payment_experience: api_enums::PaymentExperience::RedirectToUrl.to_string(),
})?,
@@ -697,7 +697,7 @@ impl<'a> TryFrom<&api_enums::BankNames> for AdyenTestBankNames<'a> {
Self("4a0a975b-0594-4b40-9068-39f77b3a91f9")
}
_ => Err(errors::ConnectorError::NotSupported {
- payment_method: String::from("BankRedirect"),
+ message: String::from("BankRedirect"),
connector: "Adyen",
payment_experience: api_enums::PaymentExperience::RedirectToUrl.to_string(),
})?,
@@ -743,7 +743,7 @@ impl<'a> TryFrom<&types::PaymentsAuthorizeRouterData> for AdyenPaymentRequest<'a
AdyenPaymentRequest::try_from((item, bank_redirect))
}
_ => Err(errors::ConnectorError::NotSupported {
- payment_method: format!("{:?}", item.request.payment_method_type),
+ message: format!("{:?}", item.request.payment_method_type),
connector: "Adyen",
payment_experience: api_models::enums::PaymentExperience::RedirectToUrl
.to_string(),
@@ -1130,7 +1130,7 @@ impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, MandateReferenceId)>
Ok(AdyenPaymentMethod::AdyenCard(Box::new(adyen_card)))
}
_ => Err(errors::ConnectorError::NotSupported {
- payment_method: format!("mandate_{:?}", item.payment_method),
+ message: format!("mandate_{:?}", item.payment_method),
connector: "Adyen",
payment_experience: api_models::enums::PaymentExperience::RedirectToUrl
.to_string(),
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index 8f26534058c..55500b281ac 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -104,7 +104,7 @@ fn get_pm_and_subsequent_auth_detail(
Ok((payment_details, processing_options, subseuent_auth_info))
}
_ => Err(errors::ConnectorError::NotSupported {
- payment_method: format!("{:?}", item.request.payment_method_data),
+ message: format!("{:?}", item.request.payment_method_data),
connector: "AuthorizeDotNet",
payment_experience: api_models::enums::PaymentExperience::RedirectToUrl
.to_string(),
@@ -131,7 +131,7 @@ fn get_pm_and_subsequent_auth_detail(
}
api::PaymentMethodData::Crypto(_) | api::PaymentMethodData::BankDebit(_) => {
Err(errors::ConnectorError::NotSupported {
- payment_method: format!("{:?}", item.request.payment_method_data),
+ message: format!("{:?}", item.request.payment_method_data),
connector: "AuthorizeDotNet",
payment_experience: api_models::enums::PaymentExperience::RedirectToUrl
.to_string(),
diff --git a/crates/router/src/connector/forte.rs b/crates/router/src/connector/forte.rs
index 3e834c2ed71..c42044d5436 100644
--- a/crates/router/src/connector/forte.rs
+++ b/crates/router/src/connector/forte.rs
@@ -2,11 +2,14 @@ mod transformers;
use std::fmt::Debug;
+use base64::Engine;
use error_stack::{IntoReport, ResultExt};
use transformers as forte;
use crate::{
configs::settings,
+ connector::utils::{PaymentsSyncRequestData, RefundsRequestData},
+ consts,
core::errors::{self, CustomResult},
headers,
services::{self, ConnectorIntegration},
@@ -42,6 +45,7 @@ impl
> for Forte
{
}
+pub const AUTH_ORG_ID_HEADER: &str = "X-Forte-Auth-Organization-Id";
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Forte
where
@@ -52,13 +56,10 @@ where
req: &types::RouterData<Flow, Request, Response>,
_connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
- let mut header = vec![(
- headers::CONTENT_TYPE.to_string(),
- types::PaymentsAuthorizeType::get_content_type(self).to_string(),
- )];
- let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
- header.append(&mut api_key);
- Ok(header)
+ let content_type = ConnectorCommon::common_get_content_type(self);
+ let mut common_headers = self.get_auth_header(&req.connector_auth_type)?;
+ common_headers.push((headers::CONTENT_TYPE.to_string(), content_type.to_string()));
+ Ok(common_headers)
}
}
@@ -79,25 +80,34 @@ impl ConnectorCommon for Forte {
&self,
auth_type: &types::ConnectorAuthType,
) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
- let auth = forte::ForteAuthType::try_from(auth_type)
+ let auth: forte::ForteAuthType = auth_type
+ .try_into()
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
- Ok(vec![(headers::AUTHORIZATION.to_string(), auth.api_key)])
+ let raw_basic_token = format!("{}:{}", auth.api_access_id, auth.api_secret_key);
+ let basic_token = format!("Basic {}", consts::BASE64_ENGINE.encode(raw_basic_token));
+ Ok(vec![
+ (headers::AUTHORIZATION.to_string(), basic_token),
+ (AUTH_ORG_ID_HEADER.to_string(), auth.organization_id),
+ ])
}
-
fn build_error_response(
&self,
res: Response,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- let response: forte::ForteErrorResponse =
- res.response
- .parse_struct("ForteErrorResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
-
+ let response: forte::ForteErrorResponse = res
+ .response
+ .parse_struct("Forte ErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ let message = response.response.response_desc;
+ let code = response
+ .response
+ .response_code
+ .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string());
Ok(ErrorResponse {
status_code: res.status_code,
- code: response.code,
- message: response.message,
- reason: response.reason,
+ code,
+ message,
+ reason: None,
})
}
}
@@ -134,19 +144,25 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
+ Ok(format!(
+ "{}/organizations/{}/locations/{}/transactions",
+ self.base_url(connectors),
+ auth.organization_id,
+ auth.location_id
+ ))
}
fn get_request_body(
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<String>, errors::ConnectorError> {
- let req_obj = forte::FortePaymentsRequest::try_from(req)?;
+ let connector_req = forte::FortePaymentsRequest::try_from(req)?;
let forte_req =
- utils::Encode::<forte::FortePaymentsRequest>::encode_to_string_of_json(&req_obj)
+ utils::Encode::<forte::FortePaymentsRequest>::encode_to_string_of_json(&connector_req)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Some(forte_req))
}
@@ -178,14 +194,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: forte::FortePaymentsResponse = res
.response
- .parse_struct("Forte PaymentsAuthorizeResponse")
+ .parse_struct("Forte AuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
- .change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
@@ -213,10 +228,19 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- _req: &types::PaymentsSyncRouterData,
- _connectors: &settings::Connectors,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
+ let txn_id = PaymentsSyncRequestData::get_connector_transaction_id(&req.request)
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
+ Ok(format!(
+ "{}/organizations/{}/locations/{}/transactions/{}",
+ self.base_url(connectors),
+ auth.organization_id,
+ auth.location_id,
+ txn_id
+ ))
}
fn build_request(
@@ -233,13 +257,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.build(),
))
}
-
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
- let response: forte::FortePaymentsResponse = res
+ let response: forte::FortePaymentsSyncResponse = res
.response
.parse_struct("forte PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -248,7 +271,6 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
data: data.clone(),
http_code: res.status_code,
})
- .change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
@@ -276,17 +298,27 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
- _req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
+ Ok(format!(
+ "{}/organizations/{}/locations/{}/transactions",
+ self.base_url(connectors),
+ auth.organization_id,
+ auth.location_id
+ ))
}
fn get_request_body(
&self,
- _req: &types::PaymentsCaptureRouterData,
+ req: &types::PaymentsCaptureRouterData,
) -> CustomResult<Option<String>, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ let connector_req = forte::ForteCaptureRequest::try_from(req)?;
+ let forte_req =
+ utils::Encode::<forte::ForteCaptureRequest>::encode_to_string_of_json(&connector_req)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(forte_req))
}
fn build_request(
@@ -296,12 +328,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
- .method(services::Method::Post)
+ .method(services::Method::Put)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
+ .body(types::PaymentsCaptureType::get_request_body(self, req)?)
.build(),
))
}
@@ -311,7 +344,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
data: &types::PaymentsCaptureRouterData,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
- let response: forte::FortePaymentsResponse = res
+ let response: forte::ForteCaptureResponse = res
.response
.parse_struct("Forte PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -320,7 +353,6 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
data: data.clone(),
http_code: res.status_code,
})
- .change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
@@ -330,10 +362,84 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
self.build_error_response(res)
}
}
-
impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
for Forte
{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsCancelRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ req: &types::PaymentsCancelRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
+ Ok(format!(
+ "{}/organizations/{}/locations/{}/transactions/{}",
+ self.base_url(connectors),
+ auth.organization_id,
+ auth.location_id,
+ req.request.connector_transaction_id
+ ))
+ }
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsCancelRouterData,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let connector_req = forte::ForteCancelRequest::try_from(req)?;
+ let forte_req =
+ utils::Encode::<forte::ForteCancelRequest>::encode_to_string_of_json(&connector_req)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(forte_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsCancelRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Put)
+ .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
+ .body(types::PaymentsVoidType::get_request_body(self, req)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsCancelRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ let response: forte::ForteCancelResponse = res
+ .response
+ .parse_struct("forte CancelResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
}
impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Forte {
@@ -351,19 +457,25 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
+ Ok(format!(
+ "{}/organizations/{}/locations/{}/transactions",
+ self.base_url(connectors),
+ auth.organization_id,
+ auth.location_id
+ ))
}
fn get_request_body(
&self,
req: &types::RefundsRouterData<api::Execute>,
) -> CustomResult<Option<String>, errors::ConnectorError> {
- let req_obj = forte::ForteRefundRequest::try_from(req)?;
+ let connector_req = forte::ForteRefundRequest::try_from(req)?;
let forte_req =
- utils::Encode::<forte::ForteRefundRequest>::encode_to_string_of_json(&req_obj)
+ utils::Encode::<forte::ForteRefundRequest>::encode_to_string_of_json(&connector_req)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Some(forte_req))
}
@@ -399,7 +511,6 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
data: data.clone(),
http_code: res.status_code,
})
- .change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
@@ -425,10 +536,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
- _req: &types::RefundSyncRouterData,
- _connectors: &settings::Connectors,
+ req: &types::RefundSyncRouterData,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
+ Ok(format!(
+ "{}/organizations/{}/locations/{}/transactions/{}",
+ self.base_url(connectors),
+ auth.organization_id,
+ auth.location_id,
+ req.request.get_connector_refund_id()?
+ ))
}
fn build_request(
@@ -442,7 +560,6 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
- .body(types::RefundSyncType::get_request_body(self, req)?)
.build(),
))
}
@@ -452,7 +569,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
data: &types::RefundSyncRouterData,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
- let response: forte::RefundResponse = res
+ let response: forte::RefundSyncResponse = res
.response
.parse_struct("forte RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -461,7 +578,6 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
data: data.clone(),
http_code: res.status_code,
})
- .change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs
index 46dcb527ea7..a806d2af94c 100644
--- a/crates/router/src/connector/forte/transformers.rs
+++ b/crates/router/src/connector/forte/transformers.rs
@@ -2,90 +2,242 @@ use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::PaymentsAuthorizeRequestData,
+ connector::utils::{
+ self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, RouterData,
+ },
core::errors,
- types::{self, api, storage::enums},
+ pii::{self},
+ types::{self, api, storage::enums, transformers::ForeignFrom},
};
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+#[derive(Debug, Serialize)]
pub struct FortePaymentsRequest {
- amount: i64,
- card: ForteCard,
+ action: ForteAction,
+ authorization_amount: f64,
+ billing_address: BillingAddress,
+ card: Card,
+}
+#[derive(Debug, Serialize, Deserialize)]
+pub struct BillingAddress {
+ first_name: Secret<String>,
+ last_name: Secret<String>,
+}
+
+#[derive(Debug, Serialize)]
+pub struct Card {
+ card_type: ForteCardType,
+ name_on_card: Secret<String>,
+ account_number: Secret<String, pii::CardNumber>,
+ expire_month: Secret<String>,
+ expire_year: Secret<String>,
+ card_verification_value: Secret<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ForteCardType {
+ Visa,
+ MasterCard,
+ Amex,
+ Discover,
+ DinersClub,
+ Jcb,
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct ForteCard {
- name: Secret<String>,
- number: Secret<String, common_utils::pii::CardNumber>,
- expiry_month: Secret<String>,
- expiry_year: Secret<String>,
- cvc: Secret<String>,
- complete: bool,
+impl TryFrom<utils::CardIssuer> for ForteCardType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(issuer: utils::CardIssuer) -> Result<Self, Self::Error> {
+ match issuer {
+ utils::CardIssuer::AmericanExpress => Ok(Self::Amex),
+ utils::CardIssuer::Master => Ok(Self::MasterCard),
+ utils::CardIssuer::Discover => Ok(Self::Discover),
+ utils::CardIssuer::Visa => Ok(Self::Visa),
+ utils::CardIssuer::DinersClub => Ok(Self::DinersClub),
+ utils::CardIssuer::JCB => Ok(Self::Jcb),
+ _ => Err(errors::ConnectorError::NotSupported {
+ message: issuer.to_string(),
+ connector: "Forte",
+ payment_experience: api::enums::PaymentExperience::RedirectToUrl.to_string(),
+ }
+ .into()),
+ }
+ }
}
impl TryFrom<&types::PaymentsAuthorizeRouterData> for FortePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
- match item.request.payment_method_data.clone() {
- api::PaymentMethodData::Card(req_card) => {
- let card = ForteCard {
- name: req_card.card_holder_name,
- number: req_card.card_number,
- expiry_month: req_card.card_exp_month,
- expiry_year: req_card.card_exp_year,
- cvc: req_card.card_cvc,
- complete: item.request.is_auto_capture()?,
+ if item.request.currency != enums::Currency::USD {
+ Err(errors::ConnectorError::NotSupported {
+ message: item.request.currency.to_string(),
+ connector: "Forte",
+ payment_experience: api::enums::PaymentExperience::RedirectToUrl.to_string(),
+ })?
+ }
+ match item.request.payment_method_data {
+ api_models::payments::PaymentMethodData::Card(ref ccard) => {
+ let action = match item.request.is_auto_capture()? {
+ true => ForteAction::Sale,
+ false => ForteAction::Authorize,
+ };
+ let card_type = ForteCardType::try_from(ccard.get_card_issuer()?)?;
+ let address = item.get_billing_address()?;
+ let card = Card {
+ card_type,
+ name_on_card: ccard.card_holder_name.clone(),
+ account_number: ccard.card_number.clone(),
+ expire_month: ccard.card_exp_month.clone(),
+ expire_year: ccard.card_exp_year.clone(),
+ card_verification_value: ccard.card_cvc.clone(),
+ };
+ let billing_address = BillingAddress {
+ first_name: address.get_first_name()?.to_owned(),
+ last_name: address.get_last_name()?.to_owned(),
};
+ let authorization_amount =
+ utils::to_currency_base_unit_asf64(item.request.amount, item.request.currency)?;
Ok(Self {
- amount: item.request.amount,
+ action,
+ authorization_amount,
+ billing_address,
card,
})
}
- _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ _ => Err(errors::ConnectorError::NotImplemented(
+ "Payment Method".to_string(),
+ ))?,
}
}
}
// Auth Struct
pub struct ForteAuthType {
- pub(super) api_key: String,
+ pub(super) api_access_id: String,
+ pub(super) organization_id: String,
+ pub(super) location_id: String,
+ pub(super) api_secret_key: String,
}
impl TryFrom<&types::ConnectorAuthType> for ForteAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
- api_key: api_key.to_string(),
+ types::ConnectorAuthType::MultiAuthKey {
+ api_key,
+ key1,
+ api_secret,
+ key2,
+ } => Ok(Self {
+ api_access_id: api_key.to_string(),
+ organization_id: format!("org_{}", key1),
+ location_id: format!("loc_{}", key2),
+ api_secret_key: api_secret.to_string(),
}),
- _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
+ _ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
}
// PaymentsResponse
-#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FortePaymentStatus {
- Succeeded,
+ Complete,
Failed,
- #[default]
- Processing,
+ Authorized,
+ Ready,
+ Voided,
+ Settled,
}
impl From<FortePaymentStatus> for enums::AttemptStatus {
fn from(item: FortePaymentStatus) -> Self {
match item {
- FortePaymentStatus::Succeeded => Self::Charged,
+ FortePaymentStatus::Complete | FortePaymentStatus::Settled => Self::Charged,
FortePaymentStatus::Failed => Self::Failure,
- FortePaymentStatus::Processing => Self::Authorizing,
+ FortePaymentStatus::Ready => Self::Pending,
+ FortePaymentStatus::Authorized => Self::Authorized,
+ FortePaymentStatus::Voided => Self::Voided,
+ }
+ }
+}
+
+impl ForeignFrom<(ForteResponseCode, ForteAction)> for enums::AttemptStatus {
+ fn foreign_from((response_code, action): (ForteResponseCode, ForteAction)) -> Self {
+ match response_code {
+ ForteResponseCode::A01 => match action {
+ ForteAction::Authorize => Self::Authorized,
+ ForteAction::Sale => Self::Pending,
+ },
+ ForteResponseCode::A05 | ForteResponseCode::A06 => Self::Authorizing,
+ _ => Self::Failure,
}
}
}
-#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[derive(Debug, Deserialize)]
+pub struct CardResponse {
+ pub name_on_card: Secret<String>,
+ pub last_4_account_number: String,
+ pub masked_account_number: String,
+ pub card_type: String,
+}
+
+#[derive(Debug, Deserialize)]
+pub enum ForteResponseCode {
+ A01,
+ A05,
+ A06,
+ U13,
+ U14,
+ U18,
+ U20,
+}
+
+impl From<ForteResponseCode> for enums::AttemptStatus {
+ fn from(item: ForteResponseCode) -> Self {
+ match item {
+ ForteResponseCode::A01 | ForteResponseCode::A05 | ForteResponseCode::A06 => {
+ Self::Pending
+ }
+ _ => Self::Failure,
+ }
+ }
+}
+
+#[derive(Debug, Deserialize)]
+pub struct ResponseStatus {
+ pub environment: String,
+ pub response_type: String,
+ pub response_code: ForteResponseCode,
+ pub response_desc: String,
+ pub authorization_code: String,
+ pub avs_result: Option<String>,
+ pub cvv_result: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum ForteAction {
+ Sale,
+ Authorize,
+}
+
+#[derive(Debug, Deserialize)]
pub struct FortePaymentsResponse {
- status: FortePaymentStatus,
- id: String,
+ pub transaction_id: String,
+ pub location_id: String,
+ pub action: ForteAction,
+ pub authorization_amount: Option<f64>,
+ pub authorization_code: String,
+ pub entered_by: String,
+ pub billing_address: Option<BillingAddress>,
+ pub card: Option<CardResponse>,
+ pub response: ResponseStatus,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct ForteMeta {
+ pub auth_id: String,
}
impl<F, T>
@@ -96,13 +248,197 @@ impl<F, T>
fn try_from(
item: types::ResponseRouterData<F, FortePaymentsResponse, T, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
+ let response_code = item.response.response.response_code;
+ let action = item.response.action;
+ let transaction_id = &item.response.transaction_id;
+ Ok(Self {
+ status: enums::AttemptStatus::foreign_from((response_code, action)),
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(transaction_id.to_string()),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: Some(serde_json::json!(ForteMeta {
+ auth_id: item.response.authorization_code,
+ })),
+ network_txn_id: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+//PsyncResponse
+
+#[derive(Debug, Deserialize)]
+pub struct FortePaymentsSyncResponse {
+ pub transaction_id: String,
+ pub location_id: String,
+ pub status: FortePaymentStatus,
+ pub action: ForteAction,
+ pub authorization_amount: Option<f64>,
+ pub authorization_code: String,
+ pub entered_by: String,
+ pub billing_address: Option<BillingAddress>,
+ pub card: Option<CardResponse>,
+ pub response: ResponseStatus,
+}
+
+impl<F, T>
+ TryFrom<types::ResponseRouterData<F, FortePaymentsSyncResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<
+ F,
+ FortePaymentsSyncResponse,
+ T,
+ types::PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let transaction_id = &item.response.transaction_id;
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ resource_id: types::ResponseId::ConnectorTransactionId(transaction_id.to_string()),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: Some(serde_json::json!(ForteMeta {
+ auth_id: item.response.authorization_code,
+ })),
+ network_txn_id: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+// Capture
+
+#[derive(Debug, Serialize)]
+pub struct ForteCaptureRequest {
+ action: String,
+ transaction_id: String,
+ authorization_code: String,
+}
+
+impl TryFrom<&types::PaymentsCaptureRouterData> for ForteCaptureRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
+ let trn_id = item.request.connector_transaction_id.clone();
+ let connector_auth_id: ForteMeta =
+ utils::to_connector_meta(item.request.connector_meta.clone())?;
+ let auth_code = connector_auth_id.auth_id;
+ Ok(Self {
+ action: "capture".to_string(),
+ transaction_id: trn_id,
+ authorization_code: auth_code,
+ })
+ }
+}
+
+#[derive(Debug, Deserialize)]
+pub struct CaptureResponseStatus {
+ pub environment: String,
+ pub response_type: String,
+ pub response_code: ForteResponseCode,
+ pub response_desc: String,
+ pub authorization_code: String,
+}
+// Capture Response
+#[derive(Debug, Deserialize)]
+pub struct ForteCaptureResponse {
+ pub transaction_id: String,
+ pub original_transaction_id: String,
+ pub entered_by: String,
+ pub authorization_code: String,
+ pub response: CaptureResponseStatus,
+}
+
+impl TryFrom<types::PaymentsCaptureResponseRouterData<ForteCaptureResponse>>
+ for types::PaymentsCaptureRouterData
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::PaymentsCaptureResponseRouterData<ForteCaptureResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ status: enums::AttemptStatus::from(item.response.response.response_code),
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.transaction_id,
+ ),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: Some(serde_json::json!(ForteMeta {
+ auth_id: item.response.authorization_code,
+ })),
+ network_txn_id: None,
+ }),
+ amount_captured: None,
+ ..item.data
+ })
+ }
+}
+
+//Cancel
+
+#[derive(Debug, Serialize)]
+pub struct ForteCancelRequest {
+ action: String,
+ authorization_code: String,
+}
+
+impl TryFrom<&types::PaymentsCancelRouterData> for ForteCancelRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
+ let action = "void".to_string();
+ let connector_auth_id: ForteMeta =
+ utils::to_connector_meta(item.request.connector_meta.clone())?;
+ let authorization_code = connector_auth_id.auth_id;
+ Ok(Self {
+ action,
+ authorization_code,
+ })
+ }
+}
+
+#[derive(Debug, Deserialize)]
+pub struct CancelResponseStatus {
+ pub response_type: String,
+ pub response_code: ForteResponseCode,
+ pub response_desc: String,
+ pub authorization_code: String,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct ForteCancelResponse {
+ pub transaction_id: String,
+ pub location_id: String,
+ pub action: String,
+ pub authorization_code: String,
+ pub entered_by: String,
+ pub response: CancelResponseStatus,
+}
+
+impl<F, T>
+ TryFrom<types::ResponseRouterData<F, ForteCancelResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<F, ForteCancelResponse, T, types::PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ let transaction_id = &item.response.transaction_id;
+ Ok(Self {
+ status: enums::AttemptStatus::from(item.response.response.response_code),
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(transaction_id.to_string()),
redirection_data: None,
mandate_reference: None,
- connector_metadata: None,
+ connector_metadata: Some(serde_json::json!(ForteMeta {
+ auth_id: item.response.authorization_code,
+ })),
network_txn_id: None,
}),
..item.data
@@ -111,46 +447,68 @@ impl<F, T>
}
// REFUND :
-// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct ForteRefundRequest {
- pub amount: i64,
+ action: String,
+ authorization_amount: f64,
+ original_transaction_id: String,
+ authorization_code: String,
}
impl<F> TryFrom<&types::RefundsRouterData<F>> for ForteRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ let trn_id = item.request.connector_transaction_id.clone();
+ let connector_auth_id: ForteMeta =
+ utils::to_connector_meta(item.request.connector_metadata.clone())?;
+ let auth_code = connector_auth_id.auth_id;
+ let authorization_amount =
+ utils::to_currency_base_unit_asf64(item.request.amount, item.request.currency)?;
Ok(Self {
- amount: item.request.amount,
+ action: "reverse".to_string(),
+ authorization_amount,
+ original_transaction_id: trn_id,
+ authorization_code: auth_code,
})
}
}
-// Type definition for Refund Response
-
-#[allow(dead_code)]
-#[derive(Debug, Serialize, Default, Deserialize, Clone)]
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "lowercase")]
pub enum RefundStatus {
- Succeeded,
+ Complete,
+ Ready,
Failed,
- #[default]
- Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
- RefundStatus::Succeeded => Self::Success,
+ RefundStatus::Complete => Self::Success,
+ RefundStatus::Ready => Self::Pending,
RefundStatus::Failed => Self::Failure,
- RefundStatus::Processing => Self::Pending,
+ }
+ }
+}
+impl From<ForteResponseCode> for enums::RefundStatus {
+ fn from(item: ForteResponseCode) -> Self {
+ match item {
+ ForteResponseCode::A01 | ForteResponseCode::A05 | ForteResponseCode::A06 => {
+ Self::Pending
+ }
+ _ => Self::Failure,
}
}
}
-#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+#[derive(Debug, Deserialize)]
pub struct RefundResponse {
- id: String,
- status: RefundStatus,
+ pub transaction_id: String,
+ pub original_transaction_id: String,
+ pub action: String,
+ pub authorization_amount: Option<f64>,
+ pub authorization_code: String,
+ pub response: ResponseStatus,
}
impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
@@ -162,24 +520,30 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(types::RefundsResponseData {
- connector_refund_id: item.response.id.to_string(),
- refund_status: enums::RefundStatus::from(item.response.status),
+ connector_refund_id: item.response.transaction_id,
+ refund_status: enums::RefundStatus::from(item.response.response.response_code),
}),
..item.data
})
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
+#[derive(Debug, Deserialize)]
+pub struct RefundSyncResponse {
+ status: RefundStatus,
+ transaction_id: String,
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>>
for types::RefundsRouterData<api::RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ item: types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(types::RefundsResponseData {
- connector_refund_id: item.response.id.to_string(),
+ connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
@@ -187,10 +551,15 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
}
}
-#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+#[derive(Debug, Deserialize)]
+pub struct ErrorResponseStatus {
+ pub environment: String,
+ pub response_type: Option<String>,
+ pub response_code: Option<String>,
+ pub response_desc: String,
+}
+
+#[derive(Debug, Deserialize)]
pub struct ForteErrorResponse {
- pub status_code: u16,
- pub code: String,
- pub message: String,
- pub reason: Option<String>,
+ pub response: ErrorResponseStatus,
}
diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs
index f2be4b2afbe..4ed92d73d03 100644
--- a/crates/router/src/connector/klarna.rs
+++ b/crates/router/src/connector/klarna.rs
@@ -261,7 +261,7 @@ impl
token
)),
_ => Err(error_stack::report!(errors::ConnectorError::NotSupported {
- payment_method: payment_method_type.to_string(),
+ message: payment_method_type.to_string(),
connector: "klarna",
payment_experience: payment_experience.to_string()
})),
diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs
index 34663924739..afc05858c63 100644
--- a/crates/router/src/connector/multisafepay/transformers.rs
+++ b/crates/router/src/connector/multisafepay/transformers.rs
@@ -194,14 +194,21 @@ pub struct MultisafepayPaymentsRequest {
pub var3: Option<String>,
}
-impl From<utils::CardIssuer> for Gateway {
- fn from(issuer: utils::CardIssuer) -> Self {
+impl TryFrom<utils::CardIssuer> for Gateway {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(issuer: utils::CardIssuer) -> Result<Self, Self::Error> {
match issuer {
- utils::CardIssuer::AmericanExpress => Self::Amex,
- utils::CardIssuer::Master => Self::MasterCard,
- utils::CardIssuer::Maestro => Self::Maestro,
- utils::CardIssuer::Visa => Self::Visa,
- utils::CardIssuer::Discover => Self::Discover,
+ utils::CardIssuer::AmericanExpress => Ok(Self::Amex),
+ utils::CardIssuer::Master => Ok(Self::MasterCard),
+ utils::CardIssuer::Maestro => Ok(Self::Maestro),
+ utils::CardIssuer::Discover => Ok(Self::Discover),
+ utils::CardIssuer::Visa => Ok(Self::Visa),
+ _ => Err(errors::ConnectorError::NotSupported {
+ message: issuer.to_string(),
+ connector: "Multisafe pay",
+ payment_experience: api::enums::PaymentExperience::RedirectToUrl.to_string(),
+ }
+ .into()),
}
}
}
@@ -216,7 +223,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques
};
let gateway = match item.request.payment_method_data {
- api::PaymentMethodData::Card(ref ccard) => Gateway::from(ccard.get_card_issuer()?),
+ api::PaymentMethodData::Card(ref ccard) => Gateway::try_from(ccard.get_card_issuer()?)?,
api::PaymentMethodData::PayLater(
api_models::payments::PayLaterData::KlarnaRedirect {
billing_email: _,
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index b80c599db21..15e15d5035e 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -539,7 +539,7 @@ impl<F>
)
}
_ => Err(errors::ConnectorError::NotSupported {
- payment_method: "Bank Redirect".to_string(),
+ message: "Bank Redirect".to_string(),
connector: "Nuvei",
payment_experience: "Redirection".to_string(),
})?,
@@ -583,7 +583,7 @@ impl<F>
item,
)),
_ => Err(errors::ConnectorError::NotSupported {
- payment_method: "Wallet".to_string(),
+ message: "Wallet".to_string(),
connector: "Nuvei",
payment_experience: "RedirectToUrl".to_string(),
}
@@ -611,7 +611,7 @@ impl<F>
item,
)),
_ => Err(errors::ConnectorError::NotSupported {
- payment_method: "Bank Redirect".to_string(),
+ message: "Bank Redirect".to_string(),
connector: "Nuvei",
payment_experience: "RedirectToUrl".to_string(),
}
diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs
index 428cc12bba4..b0cd6beaca2 100644
--- a/crates/router/src/connector/payeezy/transformers.rs
+++ b/crates/router/src/connector/payeezy/transformers.rs
@@ -38,7 +38,7 @@ impl TryFrom<utils::CardIssuer> for PayeezyCardType {
utils::CardIssuer::Discover => Ok(Self::Discover),
utils::CardIssuer::Visa => Ok(Self::Visa),
_ => Err(errors::ConnectorError::NotSupported {
- payment_method: api::enums::PaymentMethod::Card.to_string(),
+ message: issuer.to_string(),
connector: "Payeezy",
payment_experience: api::enums::PaymentExperience::RedirectToUrl.to_string(),
}
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 6d203610ac8..d0bfd1d4a45 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -454,7 +454,7 @@ impl TryFrom<&api_models::enums::BankNames> for StripeBankNames {
api_models::enums::BankNames::VolkskreditbankAg => Self::VolkskreditbankAg,
api_models::enums::BankNames::VrBankBraunau => Self::VrBankBraunau,
_ => Err(errors::ConnectorError::NotSupported {
- payment_method: api_enums::PaymentMethod::BankRedirect.to_string(),
+ message: api_enums::PaymentMethod::BankRedirect.to_string(),
connector: "Stripe",
payment_experience: api_enums::PaymentExperience::RedirectToUrl.to_string(),
})?,
@@ -497,14 +497,14 @@ fn infer_stripe_pay_later_type(
Ok(StripePaymentMethodType::AfterpayClearpay)
}
_ => Err(errors::ConnectorError::NotSupported {
- payment_method: pm_type.to_string(),
+ message: pm_type.to_string(),
connector: "stripe",
payment_experience: experience.to_string(),
}),
}
} else {
Err(errors::ConnectorError::NotSupported {
- payment_method: pm_type.to_string(),
+ message: pm_type.to_string(),
connector: "stripe",
payment_experience: experience.to_string(),
})
@@ -1865,7 +1865,7 @@ impl
}))
}
api::PaymentMethodData::Crypto(_) => Err(errors::ConnectorError::NotSupported {
- payment_method: format!("{pm_type:?}"),
+ message: format!("{pm_type:?}"),
connector: "Stripe",
payment_experience: api_models::enums::PaymentExperience::RedirectToUrl.to_string(),
})?,
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index c2c05df8b7a..d9ced8e1e07 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -325,6 +325,14 @@ static CARD_REGEX: Lazy<HashMap<CardIssuer, Result<Regex, regex::Error>>> = Lazy
CardIssuer::Maestro,
Regex::new(r"^(5018|5020|5038|5893|6304|6759|6761|6762|6763)[0-9]{8,15}$"),
);
+ map.insert(
+ CardIssuer::DinersClub,
+ Regex::new(r"^3(?:0[0-5]|[68][0-9])[0-9]{11}$"),
+ );
+ map.insert(
+ CardIssuer::JCB,
+ Regex::new(r"^(3(?:088|096|112|158|337|5(?:2[89]|[3-8][0-9]))\d{12})$"),
+ );
map
});
@@ -335,6 +343,8 @@ pub enum CardIssuer {
Maestro,
Visa,
Discover,
+ DinersClub,
+ JCB,
}
pub trait CardData {
@@ -630,6 +640,14 @@ pub fn to_currency_base_unit(
amount: i64,
currency: storage_models::enums::Currency,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
+ let amount_f64 = to_currency_base_unit_asf64(amount, currency)?;
+ Ok(format!("{amount_f64:.2}"))
+}
+
+pub fn to_currency_base_unit_asf64(
+ amount: i64,
+ currency: storage_models::enums::Currency,
+) -> Result<f64, error_stack::Report<errors::ConnectorError>> {
let amount_u32 = u32::try_from(amount)
.into_report()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
@@ -642,7 +660,7 @@ pub fn to_currency_base_unit(
| storage_models::enums::Currency::OMR => amount_f64 / 1000.00,
_ => amount_f64 / 100.00,
};
- Ok(format!("{amount:.2}"))
+ Ok(amount)
}
pub fn str_to_f32<S>(value: &str, serializer: S) -> Result<S::Ok, S::Error>
diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs
index 4b34d054315..c0676e4d55b 100644
--- a/crates/router/src/connector/worldline/transformers.rs
+++ b/crates/router/src/connector/worldline/transformers.rs
@@ -130,7 +130,7 @@ impl TryFrom<utils::CardIssuer> for Gateway {
utils::CardIssuer::Discover => Ok(Self::Discover),
utils::CardIssuer::Visa => Ok(Self::Visa),
_ => Err(errors::ConnectorError::NotSupported {
- payment_method: api_enums::PaymentMethod::Card.to_string(),
+ message: issuer.to_string(),
connector: "worldline",
payment_experience: api_enums::PaymentExperience::RedirectToUrl.to_string(),
}
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index b6c653f95ab..ce71849c097 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -253,9 +253,9 @@ pub enum ConnectorError {
FailedToObtainCertificateKey,
#[error("This step has not been implemented for: {0}")]
NotImplemented(String),
- #[error("{payment_method} is not supported by {connector}")]
+ #[error("{message} is not supported by {connector}")]
NotSupported {
- payment_method: String,
+ message: String,
connector: &'static str,
payment_experience: String,
},
diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs
index 62f77ae2d3b..0df489edf26 100644
--- a/crates/router/src/core/errors/utils.rs
+++ b/crates/router/src/core/errors/utils.rs
@@ -107,8 +107,8 @@ impl ConnectorErrorExt for error_stack::Report<errors::ConnectorError> {
"payment_method_data, payment_method_type and payment_experience does not match",
}
},
- errors::ConnectorError::NotSupported { payment_method, connector, payment_experience } => {
- errors::ApiErrorResponse::NotSupported { message: format!("Payment method type {payment_method} is not supported by {connector} through payment experience {payment_experience}") }
+ errors::ConnectorError::NotSupported { message, connector, payment_experience } => {
+ errors::ApiErrorResponse::NotSupported { message: format!("{message} is not supported by {connector} through payment experience {payment_experience}") }
},
errors::ConnectorError::FlowNotSupported{ flow, connector } => {
errors::ApiErrorResponse::FlowNotSupported { flow: flow.to_owned(), connector: connector.to_owned() }
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index a799c9245b6..8bcbf2d580b 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -537,6 +537,12 @@ pub enum ConnectorAuthType {
key1: String,
api_secret: String,
},
+ MultiAuthKey {
+ api_key: String,
+ key1: String,
+ api_secret: String,
+ key2: String,
+ },
#[default]
NoKey,
}
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 1a60dd3756a..f84436112d2 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -204,7 +204,7 @@ impl ConnectorData {
"cybersource" => Ok(Box::new(&connector::Cybersource)),
"dlocal" => Ok(Box::new(&connector::Dlocal)),
"fiserv" => Ok(Box::new(&connector::Fiserv)),
- // "forte" => Ok(Box::new(&connector::Forte)),
+ "forte" => Ok(Box::new(&connector::Forte)),
"globalpay" => Ok(Box::new(&connector::Globalpay)),
"klarna" => Ok(Box::new(&connector::Klarna)),
"mollie" => Ok(Box::new(&connector::Mollie)),
diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs
index d178c00a0d9..3e83c00b9cb 100644
--- a/crates/router/tests/connectors/connector_auth.rs
+++ b/crates/router/tests/connectors/connector_auth.rs
@@ -16,7 +16,7 @@ pub(crate) struct ConnectorAuthentication {
pub cybersource: Option<SignatureKey>,
pub dlocal: Option<SignatureKey>,
pub fiserv: Option<SignatureKey>,
- pub forte: Option<HeaderKey>,
+ pub forte: Option<MultiAuthKey>,
pub globalpay: Option<HeaderKey>,
pub mollie: Option<HeaderKey>,
pub multisafepay: Option<HeaderKey>,
@@ -91,3 +91,22 @@ impl From<SignatureKey> for ConnectorAuthType {
}
}
}
+
+#[derive(Debug, Deserialize, Clone)]
+pub(crate) struct MultiAuthKey {
+ pub api_key: String,
+ pub key1: String,
+ pub api_secret: String,
+ pub key2: String,
+}
+
+impl From<MultiAuthKey> for ConnectorAuthType {
+ fn from(key: MultiAuthKey) -> Self {
+ Self::MultiAuthKey {
+ api_key: key.api_key,
+ key1: key.key1,
+ api_secret: key.api_secret,
+ key2: key.key2,
+ }
+ }
+}
diff --git a/crates/router/tests/connectors/forte.rs b/crates/router/tests/connectors/forte.rs
index 5b5976acc63..57fa0175000 100644
--- a/crates/router/tests/connectors/forte.rs
+++ b/crates/router/tests/connectors/forte.rs
@@ -1,3 +1,5 @@
+use std::time::Duration;
+
use masking::Secret;
use router::types::{self, api, storage::enums};
@@ -14,7 +16,7 @@ impl utils::Connector for ForteTest {
use router::connector::Forte;
types::api::ConnectorData {
connector: Box::new(&Forte),
- connector_name: types::Connector::Dummy,
+ connector_name: types::Connector::Forte,
get_token: types::api::GetToken::Connector,
}
}
@@ -34,12 +36,39 @@ impl utils::Connector for ForteTest {
static CONNECTOR: ForteTest = ForteTest {};
-fn get_default_payment_info() -> Option<utils::PaymentInfo> {
- None
+fn get_payment_data() -> Option<types::PaymentsAuthorizeData> {
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethodData::Card(api::Card {
+ card_number: Secret::new(String::from("4111111111111111")),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ })
}
-fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
- None
+fn get_default_payment_info() -> Option<utils::PaymentInfo> {
+ Some(utils::PaymentInfo {
+ address: Some(types::PaymentAddress {
+ billing: Some(api::Address {
+ address: Some(api::AddressDetails {
+ first_name: Some(Secret::new("first".to_string())),
+ last_name: Some(Secret::new("last".to_string())),
+ line1: Some(Secret::new("line1".to_string())),
+ line2: Some(Secret::new("line2".to_string())),
+ city: Some("city".to_string()),
+ zip: Some(Secret::new("zip".to_string())),
+ country: Some(api_models::enums::CountryAlpha2::IN),
+ ..Default::default()
+ }),
+ phone: Some(api::PhoneDetails {
+ number: Some(Secret::new("1234567890".to_string())),
+ country_code: Some("+91".to_string()),
+ }),
+ }),
+ ..Default::default()
+ }),
+ ..Default::default()
+ })
}
// Cards Positive Tests
@@ -47,7 +76,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
- .authorize_payment(payment_method_details(), get_default_payment_info())
+ .authorize_payment(get_payment_data(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
@@ -56,20 +85,41 @@ async fn should_only_authorize_payment() {
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
+ let authorize_response = CONNECTOR
+ .authorize_payment(get_payment_data(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
+ let connector_meta = utils::get_connector_metadata(authorize_response.response);
let response = CONNECTOR
- .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
+ .capture_payment(
+ txn_id,
+ Some(types::PaymentsCaptureData {
+ connector_meta,
+ ..utils::PaymentCaptureType::default().0
+ }),
+ get_default_payment_info(),
+ )
.await
.expect("Capture payment response");
- assert_eq!(response.status, enums::AttemptStatus::Charged);
+ //Status of the Payments is always in Pending State, Forte has to settle the sandbox transaction manually
+ assert_eq!(response.status, enums::AttemptStatus::Pending);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
+ let authorize_response = CONNECTOR
+ .authorize_payment(get_payment_data(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
+ let connector_meta = utils::get_connector_metadata(authorize_response.response);
let response = CONNECTOR
- .authorize_and_capture_payment(
- payment_method_details(),
+ .capture_payment(
+ txn_id,
Some(types::PaymentsCaptureData {
+ connector_meta,
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
@@ -77,14 +127,15 @@ async fn should_partially_capture_authorized_payment() {
)
.await
.expect("Capture payment response");
- assert_eq!(response.status, enums::AttemptStatus::Charged);
+ //Status of the Payments is always in Pending State, Forte has to settle the sandbox transactions manually
+ assert_eq!(response.status, enums::AttemptStatus::Pending);
}
// 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())
+ .authorize_payment(get_payment_data(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
@@ -95,7 +146,9 @@ async fn should_sync_authorized_payment() {
connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
- ..Default::default()
+ encoded_data: None,
+ capture_method: None,
+ connector_meta: None,
}),
get_default_payment_info(),
)
@@ -107,30 +160,59 @@ async fn should_sync_authorized_payment() {
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
+ let authorize_response = CONNECTOR
+ .authorize_payment(get_payment_data(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
+ let connector_meta = utils::get_connector_metadata(authorize_response.response);
let response = CONNECTOR
- .authorize_and_void_payment(
- payment_method_details(),
+ .void_payment(
+ txn_id,
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
+ connector_meta,
..Default::default()
}),
- get_default_payment_info(),
+ None,
)
.await
.expect("Void payment response");
- assert_eq!(response.status, enums::AttemptStatus::Voided);
+ //Forte doesnot send status in response, so setting it to pending so later it will be synced
+ assert_eq!(response.status, enums::AttemptStatus::Pending);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
+#[ignore = "Since Payment status is always in pending, cannot refund"]
async fn should_refund_manually_captured_payment() {
- let response = CONNECTOR
- .capture_payment_and_refund(
- payment_method_details(),
+ let authorize_response = CONNECTOR
+ .authorize_payment(get_payment_data(), None)
+ .await
+ .expect("Authorize payment response");
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
+ let capture_connector_meta = utils::get_connector_metadata(authorize_response.response);
+ let capture_response = CONNECTOR
+ .capture_payment(
+ txn_id.clone(),
+ Some(types::PaymentsCaptureData {
+ connector_meta: capture_connector_meta,
+ ..utils::PaymentCaptureType::default().0
+ }),
None,
+ )
+ .await
+ .expect("Capture payment response");
+ let refund_connector_metadata = utils::get_connector_metadata(capture_response.response);
+ let response = CONNECTOR
+ .refund_payment(
+ txn_id,
+ Some(types::RefundsData {
+ connector_metadata: refund_connector_metadata,
+ ..utils::PaymentRefundType::default().0
+ }),
None,
- get_default_payment_info(),
)
.await
.unwrap();
@@ -142,16 +224,35 @@ async fn should_refund_manually_captured_payment() {
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
+#[ignore = "Since Payment status is always in pending, cannot refund"]
async fn should_partially_refund_manually_captured_payment() {
- let response = CONNECTOR
- .capture_payment_and_refund(
- payment_method_details(),
+ let authorize_response = CONNECTOR
+ .authorize_payment(get_payment_data(), None)
+ .await
+ .expect("Authorize payment response");
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
+ let capture_connector_meta = utils::get_connector_metadata(authorize_response.response);
+ let capture_response = CONNECTOR
+ .capture_payment(
+ txn_id.clone(),
+ Some(types::PaymentsCaptureData {
+ connector_meta: capture_connector_meta,
+ ..utils::PaymentCaptureType::default().0
+ }),
None,
+ )
+ .await
+ .expect("Capture payment response");
+ let refund_connector_metadata = utils::get_connector_metadata(capture_response.response);
+ let response = CONNECTOR
+ .refund_payment(
+ txn_id,
Some(types::RefundsData {
+ connector_metadata: refund_connector_metadata,
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
- get_default_payment_info(),
+ None,
)
.await
.unwrap();
@@ -163,14 +264,10 @@ async fn should_partially_refund_manually_captured_payment() {
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
+#[ignore = "Since Payment status is always in pending, cannot refund"]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
- .capture_payment_and_refund(
- payment_method_details(),
- None,
- None,
- get_default_payment_info(),
- )
+ .capture_payment_and_refund(None, None, None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
@@ -191,21 +288,22 @@ async fn should_sync_manually_captured_refund() {
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
- let authorize_response = CONNECTOR
- .make_payment(payment_method_details(), get_default_payment_info())
+ let response = CONNECTOR
+ .make_payment(get_payment_data(), get_default_payment_info())
.await
.unwrap();
- assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ //Status of the Payments is always in Pending State, Forte has to settle the sandbox transaction manually
+ assert_eq!(response.status, enums::AttemptStatus::Pending);
}
// 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())
+ .make_payment(get_payment_data(), get_default_payment_info())
.await
.unwrap();
- assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Pending);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
@@ -215,37 +313,63 @@ async fn should_sync_auto_captured_payment() {
connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
- capture_method: Some(enums::CaptureMethod::Automatic),
+ encoded_data: None,
+ capture_method: None,
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
- assert_eq!(response.status, enums::AttemptStatus::Charged,);
+ //Status of the Payments is always in Pending State, Forte has to settle the sandbox transaction manually
+ assert_eq!(response.status, enums::AttemptStatus::Pending,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
+#[ignore = "Since Payment status is always in pending, cannot refund"]
async fn should_refund_auto_captured_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(get_payment_data(), get_default_payment_info())
+ .await
+ .unwrap();
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
+ tokio::time::sleep(Duration::from_secs(10)).await;
+ let refund_connector_metadata = utils::get_connector_metadata(authorize_response.response);
let response = CONNECTOR
- .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .refund_payment(
+ txn_id,
+ Some(types::RefundsData {
+ connector_metadata: refund_connector_metadata,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
- enums::RefundStatus::Success,
+ enums::RefundStatus::Pending,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
+#[ignore = "Since Payment status is always in pending, cannot refund"]
async fn should_partially_refund_succeeded_payment() {
- let refund_response = CONNECTOR
- .make_payment_and_refund(
- payment_method_details(),
+ let authorize_response = CONNECTOR
+ .make_payment(get_payment_data(), get_default_payment_info())
+ .await
+ .unwrap();
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
+ tokio::time::sleep(Duration::from_secs(10)).await;
+ let refund_connector_metadata = utils::get_connector_metadata(authorize_response.response);
+ let response = CONNECTOR
+ .refund_payment(
+ txn_id,
Some(types::RefundsData {
refund_amount: 50,
+ connector_metadata: refund_connector_metadata,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
@@ -253,31 +377,63 @@ async fn should_partially_refund_succeeded_payment() {
.await
.unwrap();
assert_eq!(
- refund_response.response.unwrap().refund_status,
- enums::RefundStatus::Success,
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Pending,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
+#[ignore = "Since Payment status is always in pending, cannot refund"]
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;
+ let authorize_response = CONNECTOR
+ .make_payment(get_payment_data(), get_default_payment_info())
+ .await
+ .unwrap();
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
+ tokio::time::sleep(Duration::from_secs(10)).await;
+
+ let refund_connector_metadata = utils::get_connector_metadata(authorize_response.response);
+ for _x in 0..2 {
+ let refund_response = CONNECTOR
+ .refund_payment(
+ txn_id.clone(),
+ Some(types::RefundsData {
+ connector_metadata: refund_connector_metadata.clone(),
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ refund_response.response.unwrap().refund_status,
+ enums::RefundStatus::Pending,
+ );
+ }
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
+#[ignore = "Since Payment status is always in pending, cannot refund"]
async fn should_sync_refund() {
+ let authorize_response = CONNECTOR
+ .make_payment(get_payment_data(), get_default_payment_info())
+ .await
+ .unwrap();
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
+ tokio::time::sleep(Duration::from_secs(10)).await;
+ let refund_connector_metadata = utils::get_connector_metadata(authorize_response.response);
let refund_response = CONNECTOR
- .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .refund_payment(
+ txn_id,
+ Some(types::RefundsData {
+ connector_metadata: refund_connector_metadata,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
.await
.unwrap();
let response = CONNECTOR
@@ -291,7 +447,7 @@ async fn should_sync_refund() {
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
- enums::RefundStatus::Success,
+ enums::RefundStatus::Pending,
);
}
@@ -303,7 +459,7 @@ async fn should_fail_payment_for_incorrect_card_number() {
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: types::api::PaymentMethodData::Card(api::Card {
- card_number: Secret::new("1234567891011".to_string()),
+ card_number: Secret::new("4111111111111100".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
@@ -314,7 +470,7 @@ async fn should_fail_payment_for_incorrect_card_number() {
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
- "Your card number is incorrect.".to_string(),
+ "INVALID CREDIT CARD NUMBER".to_string(),
);
}
@@ -332,13 +488,11 @@ async fn should_fail_payment_for_empty_card_number() {
}),
get_default_payment_info(),
)
- .await
- .unwrap();
- let x = response.response.unwrap_err();
+ .await;
assert_eq!(
- x.message,
- "You passed an empty string for 'payment_method_data[card][number]'.",
- );
+ *response.unwrap_err().current_context(),
+ router::core::errors::ConnectorError::NotImplemented("Card Type".into())
+ )
}
// Creates a payment with incorrect CVC.
@@ -359,7 +513,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
- "Your card's security code is invalid.".to_string(),
+ "INVALID CVV DATA".to_string(),
);
}
@@ -381,12 +535,13 @@ async fn should_fail_payment_for_invalid_exp_month() {
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
- "Your card's expiration month is invalid.".to_string(),
+ "INVALID EXPIRATION DATE".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
+#[ignore]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
@@ -397,7 +552,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
}),
..utils::PaymentAuthorizeType::default().0
}),
- get_default_payment_info(),
+ None,
)
.await
.unwrap();
@@ -411,46 +566,85 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
#[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())
+ .authorize_payment(get_payment_data(), get_default_payment_info())
.await
- .unwrap();
- assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
- let txn_id = utils::get_connector_transaction_id(authorize_response.response);
- assert_ne!(txn_id, None, "Empty connector transaction id");
+ .expect("Authorize payment response");
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
+ let capture_connector_meta = utils::get_connector_metadata(authorize_response.response);
+ let capture_response = CONNECTOR
+ .capture_payment(
+ txn_id,
+ Some(types::PaymentsCaptureData {
+ connector_meta: capture_connector_meta,
+ ..utils::PaymentCaptureType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Capture payment response");
+ let txn_id = utils::get_connector_transaction_id(capture_response.clone().response).unwrap();
+ let connector_meta = utils::get_connector_metadata(capture_response.response);
let void_response = CONNECTOR
- .void_payment(txn_id.unwrap(), None, get_default_payment_info())
+ .void_payment(
+ txn_id,
+ Some(types::PaymentsCancelData {
+ cancellation_reason: Some("requested_by_customer".to_string()),
+ connector_meta,
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
.await
- .unwrap();
+ .expect("Void payment response");
assert_eq!(
void_response.response.unwrap_err().message,
- "You cannot cancel this PaymentIntent because it has a status of succeeded."
+ "ORIG TRANS NOT FOUND"
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
+ let connector_meta = Some(serde_json::json!({
+ "auth_id": "56YH8TZ",
+ }));
let capture_response = CONNECTOR
- .capture_payment("123456789".to_string(), None, get_default_payment_info())
+ .capture_payment(
+ "123456789".to_string(),
+ Some(types::PaymentsCaptureData {
+ connector_meta,
+ ..utils::PaymentCaptureType::default().0
+ }),
+ None,
+ )
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
- String::from("No such payment_intent: '123456789'")
+ "Error[1]: The value for field transaction_id is invalid. Check for possible formatting issues. Error[2]: The value for field transaction_id is invalid. Check for possible formatting issues.",
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
+#[ignore]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
+ let authorize_response = CONNECTOR
+ .make_payment(get_payment_data(), None)
+ .await
+ .unwrap();
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
+ tokio::time::sleep(Duration::from_secs(10)).await;
+ let refund_connector_metadata = utils::get_connector_metadata(authorize_response.response);
let response = CONNECTOR
- .make_payment_and_refund(
- payment_method_details(),
+ .refund_payment(
+ txn_id,
Some(types::RefundsData {
- refund_amount: 150,
+ refund_amount: 1500,
+ connector_metadata: refund_connector_metadata,
..utils::PaymentRefundType::default().0
}),
- get_default_payment_info(),
+ None,
)
.await
.unwrap();
@@ -463,3 +657,27 @@ async fn should_fail_for_refund_amount_higher_than_payment_amount() {
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
+
+// Cards Negative scenerios
+// Creates a payment with incorrect card issuer.
+
+#[actix_web::test]
+async fn should_throw_not_implemented_for_unsupported_issuer() {
+ let authorize_data = Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethodData::Card(api::Card {
+ card_number: Secret::new(String::from("6759649826438453")),
+ ..utils::CCardType::default().0
+ }),
+ capture_method: Some(enums::CaptureMethod::Automatic),
+ ..utils::PaymentAuthorizeType::default().0
+ });
+ let response = CONNECTOR.make_payment(authorize_data, None).await;
+ assert_eq!(
+ *response.unwrap_err().current_context(),
+ router::core::errors::ConnectorError::NotSupported {
+ message: "Maestro".to_string(),
+ connector: "Forte",
+ payment_experience: api::enums::PaymentExperience::RedirectToUrl.to_string(),
+ }
+ )
+}
diff --git a/crates/router/tests/connectors/payeezy.rs b/crates/router/tests/connectors/payeezy.rs
index 0f2ff7bb234..166457fe3c3 100644
--- a/crates/router/tests/connectors/payeezy.rs
+++ b/crates/router/tests/connectors/payeezy.rs
@@ -376,7 +376,7 @@ async fn should_throw_not_implemented_for_unsupported_issuer() {
assert_eq!(
*response.unwrap_err().current_context(),
errors::ConnectorError::NotSupported {
- payment_method: "card".to_string(),
+ message: "card".to_string(),
connector: "Payeezy",
payment_experience: "RedirectToUrl".to_string(),
}
diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml
index 5892e409c54..73311e860c3 100644
--- a/crates/router/tests/connectors/sample_auth.toml
+++ b/crates/router/tests/connectors/sample_auth.toml
@@ -76,7 +76,10 @@ key1 = "key1"
api_key = "API Key"
[forte]
-api_key="API Key"
+api_key = "api_key"
+key1 = "key1"
+key2 = "key2"
+api_secret = "api_secret"
[coinbase]
diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs
index a9c28b4502f..305e17c40ec 100644
--- a/crates/router/tests/connectors/worldline.rs
+++ b/crates/router/tests/connectors/worldline.rs
@@ -141,7 +141,7 @@ async fn should_throw_not_implemented_for_unsupported_issuer() {
assert_eq!(
*response.unwrap_err().current_context(),
errors::ConnectorError::NotSupported {
- payment_method: "card".to_string(),
+ message: "card".to_string(),
connector: "worldline",
payment_experience: "RedirectToUrl".to_string(),
}
|
feat
|
add authorize, capture, void, psync, refund, rsync for Forte connector (#955)
|
e5b7bc62fbfee7c1e6631b4d38fef5859dd736c1
|
2024-03-14 22:56:50
|
Swangi Kumari
|
fix(connector): [Iatapay] remove unused fields from auth response (#4091)
| false
|
diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs
index b2507661395..0a5f592c765 100644
--- a/crates/router/src/connector/iatapay/transformers.rs
+++ b/crates/router/src/connector/iatapay/transformers.rs
@@ -63,10 +63,7 @@ impl<T>
#[derive(Debug, Deserialize, Serialize)]
pub struct IatapayAuthUpdateResponse {
pub access_token: Secret<String>,
- pub token_type: String,
pub expires_in: i64,
- pub scope: String,
- pub jti: String,
}
impl<F, T> TryFrom<types::ResponseRouterData<F, IatapayAuthUpdateResponse, T, types::AccessToken>>
|
fix
|
[Iatapay] remove unused fields from auth response (#4091)
|
a9613111a7ce44fd19a73c8cb26dd62a937ee7e6
|
2023-01-19 18:10:02
|
Shan MS
|
docs: improve README (#414)
| false
|
diff --git a/README.md b/README.md
index f05e5fe8f33..9b9a2763c09 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# hyperswitch
+# HyperSwitch
[![Build Status][actions-badge]][actions-url]
[![Apache 2.0 license][license-badge]][license-url]
@@ -8,29 +8,36 @@
[license-badge]: https://img.shields.io/github/license/juspay/hyperswitch
[license-url]: https://github.com/juspay/hyperswitch/blob/main/LICENSE
-hyperswitch is a **_Payment Switch_** that lets you connect with **multiple payment processors with a single API integration**.
-Once integrated, you can add new payment processors and route traffic effortlessly.
-Using hyperswitch, you can:
-
-- Reduce dependency on a single processor like Stripe
-- Control & customize your payment flow with 100% visibility
-- Reduce processing fees through smart routing
-- Improve conversion rate with dynamic routing
-- Expand your business reach with new payment methods
-- Reduce development & testing efforts of adding new processors
-
-_hyperswitch is wire-compatible with top processors like Stripe making it easy to integrate._
+HyperSwitch is an **Open Source Financial Switch** to make payments Fast,
+Reliable and Affordable.
+It lets you connect with **multiple payment processors with a single API
+integration**.
+Once integrated, you can add new payment processors and route traffic
+effortlessly.
+Using HyperSwitch, you can:
+
+- **Reduce dependency** on a single processor like Stripe or Braintree
+- **Reduce Dev efforts** by 90% in adding & maintaining integrations
+- **Improve success rates** with auto-retries
+- **Reduce processing fees** through smart routing
+- **Customize your payment** flow with 100% visibility and control
+- **Increase business reach** with local payment methods
+- **Embrace diversity** in payments
+
+_HyperSwitch is wire-compatible with top processors like Stripe making it easy
+to integrate._
<p align="center">
-<img src= "./docs/imgs/hyperswitch-product.png" alt="hyperswitch-product" width="40%" />
+<img src= "./docs/imgs/hyperswitch-product.png" alt="HyperSwitch-Product" width="40%" />
</p>
## Table of Contents
- [Quick Start Guide](#quick-start-guide)
+- [Fast Integration for Stripe Users](#fast-integration-for-stripe-users)
- [Supported Features](#supported-features)
- [What's Included](#whats-included)
-- [Join us in building hyperswitch](#join-us-in-building-hyperswitch)
+- [Join us in building HyperSwitch](#join-us-in-building-hyperswitch)
- [Community](#community)
- [Bugs and feature requests](#bugs-and-feature-requests)
- [Versioning](#versioning)
@@ -38,55 +45,72 @@ _hyperswitch is wire-compatible with top processors like Stripe making it easy t
## Quick Start Guide
-### Try It Out
+You have two options to try out HyperSwitch:
-You have two options to try out hyperswitch:
+1. [Try it in our Sandbox Environment](/docs/try_sandbox.md): Fast and easy to
+ start.
+ No code or setup required in your system.
+2. [Install in your local system](/docs/try_local_system.md): Configurations and
+ setup required in your system.
+ Suitable if you like to customize the core offering.
-1. [Try out our sandbox environment](/docs/try_sandbox.md): Requires the least
- effort and does not involve setting up anything on your system.
-2. [Try out hyperswitch on your local system](/docs/try_local_system.md):
- Requires comparatively more effort as it involves setting up dependencies on
- your system.
+## Fast Integration for Stripe Users
-### Fast Integration for Stripe Users
-
-If you are already using Stripe, integrating with hyperswitch is fun, fast & easy.
+If you are already using Stripe, integrating with HyperSwitch is fun, fast &
+easy.
Try the steps below to get a feel for how quick the setup is:
-1. Get API keys from our [dashboard](https://dashboard-hyperswitch.netlify.app).
-2. Follow the instructions detailed on our [documentation page](https://hyperswitch.io/docs).
+1. Get API keys from our [dashboard].
+2. Follow the instructions detailed on our
+ [documentation page][migrate-from-stripe].
+
+[dashboard]: https://dashboard-hyperswitch.netlify.app
+[migrate-from-stripe]: https://hyperswitch.io/docs/migrateFromStripe
## Supported Features
-| Features | Stripe | Adyen | Checkout | Authorize.net | ACI |
-| ------------------------ | ------------------ | ------------------ | ------------------ | ------------------ | ------------------ |
-| Payments - CRUD, Confirm | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: |
-| Customers - CRUD | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: |
-| Refunds | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | WIP |
-| Mandates | :white_check_mark: | WIP | WIP | WIP | WIP |
-| PCI Compliance | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: |
+### Supported Payment Processors and Methods
+
+As of Jan 2023, we support 14 payment processors and multiple payment methods.
+In addition, we are continuously integrating new processors based on their reach
+and community requests.
+Our target is to support 100+ processors by H2 2023.
+You can find the latest list of payment processors, supported methods, and
+features
+[here][supported-connectors-and-features].
+
+[supported-connectors-and-features]: https://docs.google.com/spreadsheets/d/e/2PACX-1vQWHLza9m5iO4Ol-tEBx22_Nnq8Mb3ISCWI53nrinIGLK8eHYmHGnvXFXUXEut8AFyGyI9DipsYaBLG/pubhtml?gid=0&single=true
+
+### Hosted Version
-The **hosted version** provides the following additional features:
+In addition to all the features of the open-source product, our hosted version
+provides features and support to manage your payment infrastructure, compliance,
+analytics, and operations end-to-end:
- **System Performance & Reliability**
- Scalable to support 50000 tps
- - System uptime of upto 99.99%
- - Low latency service
- - Hosting option with AWS, GCP
+ - System uptime of up to 99.99%
+ - Deployment with very low latency
+ - Hosting option with AWS or GCP
- **Value Added Services**
- - Compliance Support incl. PCI, GDPR etc
- - Support for processors / gateways not currently available as part of OSS (E.g. Chase Payments)
+ - Compliance Support incl. PCI, GDPR, Card Vault etc
+ - Customize the integration or payment experience
+ - Control Center with elaborate analytics and reporting
- Integration with Risk Management Solutions
- - Support for Subscription
+ - Integration with other platforms like Subscription, E-commerce, Accounting,
+ etc.
-- **Payment Operations Support**
+- **Enterprise Support**
- - 24x7 Support
- - Dashboards with deep analytics
- - Experts team to consult and improve business metrics
+ - 24x7 Email / On-call Support
+ - Dedicated Relationship Manager
+ - Custom dashboards with deep analytics, alerts, and reporting
+ - Expert team to consult and improve business metrics
+
+You can [try the hosted version in our sandbox][dashboard].
<!--
## Documentation
@@ -102,11 +126,14 @@ Please refer to the following documentation pages:
## What's Included
-Within the repositories you'll find the following directories and files, logically grouping common assets and providing both compiled and minified variations.
+Within the repositories you'll find the following directories and files,
+logically grouping common assets and providing both compiled and minified
+variations.
### Repositories
-The current setup contains a single repo, which contains the core payment router and the various connector integrations under the `src/connector` sub-directory.
+The current setup contains a single repo, which contains the core payment router
+and the various connector integrations under the `src/connector` sub-directory.
<!-- ### Sub-Crates -->
@@ -119,7 +146,8 @@ The current setup contains a single repo, which contains the core payment router
### Files Tree Layout
-<!-- FIXME: this table should either be generated by a script or smoke test should be introduced checking it agrees with actual structure -->
+<!-- FIXME: this table should either be generated by a script or smoke test
+should be introduced checking it agrees with actual structure -->
```text
├── config : config files for router. This stores the initial startup config and separate configs can be provided for debug/release builds.
@@ -136,42 +164,87 @@ The current setup contains a single repo, which contains the core payment router
└── target : generated files
```
-## Join us in building hyperswitch
+## Join us in building HyperSwitch
### Our Belief
-**We believe payments should be open, fast and cheap.**
-
-hyperswitch would allow everyone to quickly customize and set up an open payment switch, while giving a unified experience to your users, abstracting away the ever shifting payments landscape.
+_We believe payments should be open, fast, reliable and affordable to serve
+billions of people at scale._
-The hyperswitch journey starts with a payment orchestrator.
-It was born from our struggle to understand and integrate various payment options/payment processors/networks and banks, with varying degrees of documentation and inconsistent API semantics.
+<!--
+HyperSwitch would allow everyone to quickly customize and set up an open payment
+switch, while giving a unified experience to your users, abstracting away the
+ever shifting payments landscape.
+
+The HyperSwitch journey starts with a payment orchestrator.
+It was born from our struggle to understand and integrate various payment
+options/payment processors/networks and banks, with varying degrees of
+documentation and inconsistent API semantics. -->
+
+Globally payment diversity has been growing exponentially.
+There are hundreds of payment processors and new payment methods.
+So, businesses embrace diversity by onboarding multiple payment processors to
+increase conversion, reduce cost and improve control.
+But integrating and maintaining multiple processors needs a lot of dev efforts.
+So, why should devs across companies repeat this same work?
+Why can't it be unified and reused? Hence, HyperSwitch was born to create that
+reusable core and let companies build or customize on top of it.
+
+### Our Values
+
+1. Embrace Diversity of Payments: It leads to a better experience, efficiency &
+ resilience.
+2. Future is Open Source: It enables Innovation, code reuse & affordability.
+3. Be part of the Community: It helps in collaboration, learning & contribution.
+4. Build it like a System Software: It makes the product reliable, secure &
+ performant.
+5. Maximize Value Creation: For developers, customers & partners.
### Contributing
-This project is created and currently maintained by [Juspay](https://juspay.io/juspay-router).
-
-We welcome contributions from the open source community.
-Please read through our [contributing guidelines](/docs/CONTRIBUTING.md).
-Included are directions for opening issues, coding standards, and notes on development.
-
-Important note for Rust developers: We aim for contributions from the community across a broad range of tracks.
-Hence, we have prioritized simplicity and code readability over purely idiomatic code.
-For example, some of the code in core functions (e.g. `payments_core`) is written to be more readable rather than being pure-idiomatic.
+This project is being created and maintained by [Juspay](https://juspay.in),
+South Asia's largest payments orchestrator/switch, processing more than 50
+Million transactions per day. The solution has 1Mn+ lines of Haskell code built
+over 10 years.
+HyperSwitch leverages our experience in building large-scale, enterprise-grade &
+frictionless payment solutions.
+It is built afresh for the global markets as an open-source product in Rust.
+We are long-term committed to building and making it useful for the community.
+
+The product roadmap is open for the community's feedback.
+We shall evolve a prioritization process that is open and community-driven.
+We welcome contributions from the community. Please read through our
+[contributing guidelines](/docs/CONTRIBUTING.md).
+Included are directions for opening issues, coding standards, and notes on
+development.
+
+Important note for Rust developers: We aim for contributions from the community
+across a broad range of tracks. Hence, we have prioritized simplicity and code
+readability over purely idiomatic code. For example, some of the code in core
+functions (e.g., `payments_core`) is written to be more readable than
+pure-idiomatic.
## Community
-Get updates on hyperswitch development and chat with the community:
+Get updates on HyperSwitch development and chat with the community:
+
+- Read and subscribe to [the official HyperSwitch blog][blog].
+- Join our [Discord server][discord].
+- Join our [Slack workspace][slack].
+- Ask and explore our [GitHub Discussions][github-discussions].
-- Read and subscribe to [the official hyperswitch blog](https://blog.hyperswitch.io)
-- Join our [Discord server](https://discord.gg/wJZ7DVW8mm)
-- Join our [Slack workspace](https://join.slack.com/t/hyperswitch-io/shared_invite/zt-1k6cz4lee-SAJzhz6bjmpp4jZCDOtOIg)
-- Ask and explore our [GitHub Discussions](https://github.com/juspay/hyperswitch/discussions)
+[blog]: https://blog.hyperswitch.io
+[discord]: https://discord.gg/wJZ7DVW8mm
+[slack]: https://join.slack.com/t/hyperswitch-io/shared_invite/zt-1k6cz4lee-SAJzhz6bjmpp4jZCDOtOIg
+[github-discussions]: https://github.com/juspay/hyperswitch/discussions
## Bugs and feature requests
-Please read the issue guidelines and search for [existing and closed issues](https://github.com/juspay/hyperswitch/issues).
-If your problem or idea is not addressed yet, please [open a new issue](https://github.com/juspay/hyperswitch/issues/new/choose).
+Please read the issue guidelines and search for [existing and closed issues].
+If your problem or idea is not addressed yet, please [open a new issue].
+
+[existing and closed issues]: https://github.com/juspay/hyperswitch/issues
+[open a new issue]: https://github.com/juspay/hyperswitch/issues/new/choose
## Versioning
diff --git a/docs/try_local_system.md b/docs/try_local_system.md
index 7d88c5c3dd6..2394eaae781 100644
--- a/docs/try_local_system.md
+++ b/docs/try_local_system.md
@@ -347,6 +347,8 @@ Once you're done with configuring the application, proceed with
- Pay special attention to the `connector_name` and
`connector_account_details` fields and update them.
+ You can find connector-specific details to be included in this
+ [spreadsheet][connector-specific-details].
Click on the "Send" button to create a payment connector account.
You should obtain a response containing most of the data included in the
@@ -407,3 +409,4 @@ To explore more of our APIs, please check the remaining folders in the
[payments-retrieve]: https://www.postman.com/hyperswitch/workspace/hyperswitch/request/25176183-11995c9b-8a34-4afd-a6ce-e8645693929b
[refunds-create]: https://www.postman.com/hyperswitch/workspace/hyperswitch/request/25176183-5b15d068-db9e-48a5-9ee9-3a70c0aac944
[refunds-retrieve]: https://www.postman.com/hyperswitch/workspace/hyperswitch/request/25176183-c50c32af-5ceb-4ab6-aca7-85f6b32df9d3
+[connector-specific-details]: https://docs.google.com/spreadsheets/d/e/2PACX-1vQWHLza9m5iO4Ol-tEBx22_Nnq8Mb3ISCWI53nrinIGLK8eHYmHGnvXFXUXEut8AFyGyI9DipsYaBLG/pubhtml?gid=748960791&single=true
diff --git a/supported_connectors.md b/supported_connectors.md
deleted file mode 100644
index e11c08c1e82..00000000000
--- a/supported_connectors.md
+++ /dev/null
@@ -1,16 +0,0 @@
-
-# Supported connectors
-
-| Connector | Card | 3DS Auth | Mandates |
-| :------------:| :---: | :------: | :------: |
-| Stripe | Y | N | N |
-| Adyen | Y | N | N |
-| Checkout | Y | N | N |
-| ACI | Y | N | N |
-| Authorize.net | Y | N | N |
-
-In addition to the connectors listed above, below payment methods and connectors will be made available very soon.
-* d-local
-* PPRO
-* Paypal
-* Braintree
\ No newline at end of file
|
docs
|
improve README (#414)
|
979539702190363c67045d509be04498efd9a1fa
|
2024-07-26 13:12:18
|
Vrishab Srivatsa
|
fix: added created at and modified at keys in PaymentAttemptResponse (#5412)
| false
|
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json
index c4e01dcca10..30c23c83a50 100644
--- a/api-reference/openapi_spec.json
+++ b/api-reference/openapi_spec.json
@@ -13477,7 +13477,9 @@
"required": [
"attempt_id",
"status",
- "amount"
+ "amount",
+ "created_at",
+ "modified_at"
],
"properties": {
"attempt_id": {
@@ -13541,6 +13543,18 @@
"default": "three_ds",
"nullable": true
},
+ "created_at": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Time at which the payment attempt was created",
+ "example": "2022-09-10T10:11:12Z"
+ },
+ "modified_at": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Time at which the payment attempt was last modified",
+ "example": "2022-09-10T10:11:12Z"
+ },
"cancellation_reason": {
"type": "string",
"description": "If the payment was cancelled the reason will be provided here",
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index a466288b416..8433ac43d0c 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -761,9 +761,7 @@ impl HeaderPayload {
}
}
-#[derive(
- Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema,
-)]
+#[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)]
pub struct PaymentAttemptResponse {
/// Unique identifier for the attempt
pub attempt_id: String,
@@ -791,6 +789,14 @@ pub struct PaymentAttemptResponse {
/// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS
#[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")]
pub authentication_type: Option<enums::AuthenticationType>,
+ /// Time at which the payment attempt was created
+ #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")]
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub created_at: PrimitiveDateTime,
+ /// Time at which the payment attempt was last modified
+ #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")]
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub modified_at: PrimitiveDateTime,
/// If the payment was cancelled the reason will be provided here
pub cancellation_reason: Option<String>,
/// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 8a29ac7e79a..a9c8e8bcbe8 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -1053,6 +1053,8 @@ impl ForeignFrom<storage::PaymentAttempt> for payments::PaymentAttemptResponse {
connector_transaction_id: payment_attempt.connector_transaction_id,
capture_method: payment_attempt.capture_method,
authentication_type: payment_attempt.authentication_type,
+ created_at: payment_attempt.created_at,
+ modified_at: payment_attempt.modified_at,
cancellation_reason: payment_attempt.cancellation_reason,
mandate_id: payment_attempt.mandate_id,
error_code: payment_attempt.error_code,
|
fix
|
added created at and modified at keys in PaymentAttemptResponse (#5412)
|
0dd62e86fd0a118b2122d252ce7fbee43bf2eaea
|
2025-02-27 17:12:01
|
Debarati Ghatak
|
feat(payments): [Payment links] add configs for payment link (#7340)
| false
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 90cc3d4b6a9..2e0d57d977e 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -13953,6 +13953,21 @@
"type": "string",
"description": "Custom background colour for payment link's handle confirm button",
"nullable": true
+ },
+ "skip_status_screen": {
+ "type": "boolean",
+ "description": "Skip the status screen after payment completion",
+ "nullable": true
+ },
+ "payment_button_text_colour": {
+ "type": "string",
+ "description": "Custom text colour for payment link's handle confirm button",
+ "nullable": true
+ },
+ "background_colour": {
+ "type": "string",
+ "description": "Custom background colour for the payment link",
+ "nullable": true
}
}
},
@@ -14053,6 +14068,21 @@
"type": "string",
"description": "Custom background colour for payment link's handle confirm button",
"nullable": true
+ },
+ "skip_status_screen": {
+ "type": "boolean",
+ "description": "Skip the status screen after payment completion",
+ "nullable": true
+ },
+ "payment_button_text_colour": {
+ "type": "string",
+ "description": "Custom text colour for payment link's handle confirm button",
+ "nullable": true
+ },
+ "background_colour": {
+ "type": "string",
+ "description": "Custom background colour for the payment link",
+ "nullable": true
}
}
},
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json
index a16adf76c54..0473fec243c 100644
--- a/api-reference/openapi_spec.json
+++ b/api-reference/openapi_spec.json
@@ -16505,6 +16505,21 @@
"type": "string",
"description": "Custom background colour for payment link's handle confirm button",
"nullable": true
+ },
+ "skip_status_screen": {
+ "type": "boolean",
+ "description": "Skip the status screen after payment completion",
+ "nullable": true
+ },
+ "payment_button_text_colour": {
+ "type": "string",
+ "description": "Custom text colour for payment link's handle confirm button",
+ "nullable": true
+ },
+ "background_colour": {
+ "type": "string",
+ "description": "Custom background colour for the payment link",
+ "nullable": true
}
}
},
@@ -16605,6 +16620,21 @@
"type": "string",
"description": "Custom background colour for payment link's handle confirm button",
"nullable": true
+ },
+ "skip_status_screen": {
+ "type": "boolean",
+ "description": "Skip the status screen after payment completion",
+ "nullable": true
+ },
+ "payment_button_text_colour": {
+ "type": "string",
+ "description": "Custom text colour for payment link's handle confirm button",
+ "nullable": true
+ },
+ "background_colour": {
+ "type": "string",
+ "description": "Custom background colour for the payment link",
+ "nullable": true
}
}
},
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index ec69d7c8fda..d9ae29d4b30 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -2786,6 +2786,12 @@ pub struct PaymentLinkConfigRequest {
pub custom_message_for_card_terms: Option<String>,
/// Custom background colour for payment link's handle confirm button
pub payment_button_colour: Option<String>,
+ /// Skip the status screen after payment completion
+ pub skip_status_screen: Option<bool>,
+ /// Custom text colour for payment link's handle confirm button
+ pub payment_button_text_colour: Option<String>,
+ /// Custom background colour for the payment link
+ pub background_colour: Option<String>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)]
@@ -2861,6 +2867,12 @@ pub struct PaymentLinkConfig {
pub custom_message_for_card_terms: Option<String>,
/// Custom background colour for payment link's handle confirm button
pub payment_button_colour: Option<String>,
+ /// Skip the status screen after payment completion
+ pub skip_status_screen: Option<bool>,
+ /// Custom text colour for payment link's handle confirm button
+ pub payment_button_text_colour: Option<String>,
+ /// Custom background colour for the payment link
+ pub background_colour: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 8f14dc8d860..c94193831ff 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -7818,8 +7818,11 @@ pub struct PaymentLinkDetails {
pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>,
pub branding_visibility: Option<bool>,
pub payment_button_text: Option<String>,
+ pub skip_status_screen: Option<bool>,
pub custom_message_for_card_terms: Option<String>,
pub payment_button_colour: Option<String>,
+ pub payment_button_text_colour: Option<String>,
+ pub background_colour: Option<String>,
}
#[derive(Debug, serde::Serialize, Clone)]
@@ -7830,8 +7833,11 @@ pub struct SecurePaymentLinkDetails {
#[serde(flatten)]
pub payment_link_details: PaymentLinkDetails,
pub payment_button_text: Option<String>,
+ pub skip_status_screen: Option<bool>,
pub custom_message_for_card_terms: Option<String>,
pub payment_button_colour: Option<String>,
+ pub payment_button_text_colour: Option<String>,
+ pub background_colour: Option<String>,
}
#[derive(Debug, serde::Serialize)]
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index d0ee9e8926f..c5507d78002 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -629,6 +629,9 @@ pub struct PaymentLinkConfigRequest {
pub payment_button_text: Option<String>,
pub custom_message_for_card_terms: Option<String>,
pub payment_button_colour: Option<String>,
+ pub skip_status_screen: Option<bool>,
+ pub payment_button_text_colour: Option<String>,
+ pub background_colour: Option<String>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)]
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index 77cd5db77ba..a2b3c406a2a 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -177,10 +177,16 @@ pub struct PaymentLinkConfigRequestForPayments {
pub details_layout: Option<common_enums::PaymentLinkDetailsLayout>,
/// Text for payment link's handle confirm button
pub payment_button_text: Option<String>,
+ /// Skip the status screen after payment completion
+ pub skip_status_screen: Option<bool>,
/// Text for customizing message for card terms
pub custom_message_for_card_terms: Option<String>,
/// Custom background colour for payment link's handle confirm button
pub payment_button_colour: Option<String>,
+ /// Custom text colour for payment link's handle confirm button
+ pub payment_button_text_colour: Option<String>,
+ /// Custom background colour for the payment link
+ pub background_colour: Option<String>,
}
common_utils::impl_to_sql_from_sql_json!(PaymentLinkConfigRequestForPayments);
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index 011f9619cdd..c97753a6dc0 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -409,6 +409,9 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest>
payment_button_text: item.payment_button_text,
custom_message_for_card_terms: item.custom_message_for_card_terms,
payment_button_colour: item.payment_button_colour,
+ skip_status_screen: item.skip_status_screen,
+ background_colour: item.background_colour,
+ payment_button_text_colour: item.payment_button_text_colour,
}
}
fn convert_back(self) -> api_models::admin::PaymentLinkConfigRequest {
@@ -427,6 +430,9 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest>
payment_button_text,
custom_message_for_card_terms,
payment_button_colour,
+ skip_status_screen,
+ background_colour,
+ payment_button_text_colour,
} = self;
api_models::admin::PaymentLinkConfigRequest {
theme,
@@ -449,6 +455,9 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest>
payment_button_text,
custom_message_for_card_terms,
payment_button_colour,
+ skip_status_screen,
+ background_colour,
+ payment_button_text_colour,
}
}
}
diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs
index ba63319aabb..e62d9946416 100644
--- a/crates/router/src/core/payment_link.rs
+++ b/crates/router/src/core/payment_link.rs
@@ -132,6 +132,9 @@ pub async fn form_payment_link_data(
payment_button_text: None,
custom_message_for_card_terms: None,
payment_button_colour: None,
+ skip_status_screen: None,
+ background_colour: None,
+ payment_button_text_colour: None,
}
};
@@ -280,6 +283,9 @@ pub async fn form_payment_link_data(
payment_button_text: payment_link_config.payment_button_text.clone(),
custom_message_for_card_terms: payment_link_config.custom_message_for_card_terms.clone(),
payment_button_colour: payment_link_config.payment_button_colour.clone(),
+ skip_status_screen: payment_link_config.skip_status_screen,
+ background_colour: payment_link_config.background_colour.clone(),
+ payment_button_text_colour: payment_link_config.payment_button_text_colour.clone(),
};
Ok((
@@ -333,6 +339,9 @@ pub async fn initiate_secure_payment_link_flow(
payment_button_text: payment_link_config.payment_button_text,
custom_message_for_card_terms: payment_link_config.custom_message_for_card_terms,
payment_button_colour: payment_link_config.payment_button_colour,
+ skip_status_screen: payment_link_config.skip_status_screen,
+ background_colour: payment_link_config.background_colour,
+ payment_button_text_colour: payment_link_config.payment_button_text_colour,
};
let js_script = format!(
"window.__PAYMENT_DETAILS = {}",
@@ -444,7 +453,10 @@ fn get_js_script(payment_details: &PaymentLinkData) -> RouterResult<String> {
}
fn get_color_scheme_css(payment_link_config: &PaymentLinkConfig) -> String {
- let background_primary_color = payment_link_config.theme.clone();
+ let background_primary_color = payment_link_config
+ .background_colour
+ .clone()
+ .unwrap_or(payment_link_config.theme.clone());
format!(
":root {{
--primary-color: {background_primary_color};
@@ -638,6 +650,9 @@ pub fn get_payment_link_config_based_on_priority(
payment_button_text,
custom_message_for_card_terms,
payment_button_colour,
+ skip_status_screen,
+ background_colour,
+ payment_button_text_colour,
) = get_payment_link_config_value!(
payment_create_link_config,
business_theme_configs,
@@ -647,6 +662,9 @@ pub fn get_payment_link_config_based_on_priority(
(payment_button_text),
(custom_message_for_card_terms),
(payment_button_colour),
+ (skip_status_screen),
+ (background_colour),
+ (payment_button_text_colour)
);
let payment_link_config =
@@ -661,6 +679,7 @@ pub fn get_payment_link_config_based_on_priority(
show_card_form_by_default,
allowed_domains,
branding_visibility,
+ skip_status_screen,
transaction_details: payment_create_link_config.as_ref().and_then(
|payment_link_config| payment_link_config.theme_config.transaction_details.clone(),
),
@@ -669,6 +688,8 @@ pub fn get_payment_link_config_based_on_priority(
payment_button_text,
custom_message_for_card_terms,
payment_button_colour,
+ background_colour,
+ payment_button_text_colour,
};
Ok((payment_link_config, domain_name))
@@ -774,6 +795,9 @@ pub async fn get_payment_link_status(
payment_button_text: None,
custom_message_for_card_terms: None,
payment_button_colour: None,
+ skip_status_screen: None,
+ background_colour: None,
+ payment_button_text_colour: None,
}
};
diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js
index a73067a5bce..811ae799d0f 100644
--- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js
+++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js
@@ -307,8 +307,9 @@ function initializeEventListeners(paymentDetails) {
}
if (submitButtonNode instanceof HTMLButtonElement) {
- submitButtonNode.style.color = contrastBWColor;
- submitButtonNode.style.backgroundColor = paymentDetails.payment_button_colour || primaryColor;
+ var chosenColor = paymentDetails.payment_button_colour || primaryColor;
+ submitButtonNode.style.color = paymentDetails.payment_button_text_colour || invert(chosenColor, true);
+ submitButtonNode.style.backgroundColor = chosenColor;
}
if (hyperCheckoutCartImageNode instanceof HTMLDivElement) {
@@ -442,9 +443,25 @@ function handleSubmit(e) {
} else {
showMessage(translations.unexpectedError);
}
+ } else if (paymentDetails.skip_status_screen) {
+ // Form query params
+ var queryParams = {
+ payment_id: paymentDetails.payment_id,
+ status: result.status
+ };
+ var url = new URL(paymentDetails.return_url);
+ var params = new URLSearchParams(url.search);
+ // Attach query params to return_url
+ for (var key in queryParams) {
+ if (queryParams.hasOwnProperty(key)) {
+ params.set(key, queryParams[key]);
+ }
+ }
+ url.search = params.toString();
+ window.top.location.href = url.toString();
} else {
redirectToStatus();
- }
+ }
})
.catch(function (error) {
console.error("Error confirming payment_intent", error);
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index ff4e6fe56a5..ad56394c5f8 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -4410,6 +4410,9 @@ impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest>
payment_button_text: config.payment_button_text,
custom_message_for_card_terms: config.custom_message_for_card_terms,
payment_button_colour: config.payment_button_colour,
+ skip_status_screen: config.skip_status_screen,
+ background_colour: config.background_colour,
+ payment_button_text_colour: config.payment_button_text_colour,
}
}
}
@@ -4475,6 +4478,9 @@ impl ForeignFrom<diesel_models::PaymentLinkConfigRequestForPayments>
payment_button_text: config.payment_button_text,
custom_message_for_card_terms: config.custom_message_for_card_terms,
payment_button_colour: config.payment_button_colour,
+ skip_status_screen: config.skip_status_screen,
+ background_colour: config.background_colour,
+ payment_button_text_colour: config.payment_button_text_colour,
}
}
}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 4da26061e49..8938461eec4 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -2156,8 +2156,11 @@ impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest>
.background_image
.map(|background_image| background_image.foreign_into()),
payment_button_text: item.payment_button_text,
+ skip_status_screen: item.skip_status_screen,
custom_message_for_card_terms: item.custom_message_for_card_terms,
payment_button_colour: item.payment_button_colour,
+ background_colour: item.background_colour,
+ payment_button_text_colour: item.payment_button_text_colour,
}
}
}
@@ -2181,8 +2184,11 @@ impl ForeignFrom<diesel_models::business_profile::PaymentLinkConfigRequest>
.background_image
.map(|background_image| background_image.foreign_into()),
payment_button_text: item.payment_button_text,
+ skip_status_screen: item.skip_status_screen,
custom_message_for_card_terms: item.custom_message_for_card_terms,
payment_button_colour: item.payment_button_colour,
+ background_colour: item.background_colour,
+ payment_button_text_colour: item.payment_button_text_colour,
}
}
}
|
feat
|
[Payment links] add configs for payment link (#7340)
|
0796bb3b259c43f1105cf98e3d4407c46f4ca91d
|
2024-07-04 13:12:44
|
likhinbopanna
|
ci(cypress): Update card number for adyen and status for paypal (#5192)
| false
|
diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js b/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js
index 72090f91722..8513f596f4f 100644
--- a/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js
+++ b/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js
@@ -1,11 +1,11 @@
import { getCustomExchange } from "./Commons";
const successfulNo3DSCardDetails = {
- card_number: "371449635398431",
+ card_number: "4111111111111111",
card_exp_month: "03",
card_exp_year: "30",
card_holder_name: "John Doe",
- card_cvc: "7373",
+ card_cvc: "737",
};
const successfulThreeDSTestCardDetails = {
diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Paypal.js b/cypress-tests/cypress/e2e/PaymentUtils/Paypal.js
index 1aa4bc9c1a9..7c109b98160 100644
--- a/cypress-tests/cypress/e2e/PaymentUtils/Paypal.js
+++ b/cypress-tests/cypress/e2e/PaymentUtils/Paypal.js
@@ -62,7 +62,7 @@ export const connectorDetails = {
Response: {
status: 200,
body: {
- status: "processing",
+ status: "succeeded",
},
},
},
@@ -94,7 +94,7 @@ export const connectorDetails = {
Response: {
status: 200,
body: {
- status: "processing",
+ status: "succeeded",
},
},
},
@@ -109,10 +109,10 @@ export const connectorDetails = {
Response: {
status: 200,
body: {
- status: "processing",
+ status: "succeeded",
amount: 6500,
- amount_capturable: 6500,
- amount_received: 0,
+ amount_capturable: 0,
+ amount_received: 6500,
},
},
},
@@ -121,10 +121,10 @@ export const connectorDetails = {
Response: {
status: 200,
body: {
- status: "processing",
+ status: "partially_captured",
amount: 6500,
- amount_capturable: 6500,
- amount_received: 0,
+ amount_capturable: 0,
+ amount_received: 100,
},
},
},
@@ -146,14 +146,9 @@ export const connectorDetails = {
customer_acceptance: null,
},
Response: {
- status: 400,
+ status: 200,
body: {
- error: {
- type: "invalid_request",
- message:
- "This Payment could not be refund because it has a status of processing. The expected state is succeeded, partially_captured",
- code: "IR_14",
- },
+ status: "succeeded",
},
},
},
@@ -166,14 +161,9 @@ export const connectorDetails = {
customer_acceptance: null,
},
Response: {
- status: 400,
+ status: 200,
body: {
- error: {
- type: "invalid_request",
- message:
- "This Payment could not be refund because it has a status of processing. The expected state is succeeded, partially_captured",
- code: "IR_14",
- },
+ status: "succeeded",
},
},
},
@@ -186,14 +176,9 @@ export const connectorDetails = {
customer_acceptance: null,
},
Response: {
- status: 400,
+ status: 200,
body: {
- error: {
- type: "invalid_request",
- message:
- "This Payment could not be refund because it has a status of processing. The expected state is succeeded, partially_captured",
- code: "IR_14",
- },
+ status: "succeeded",
},
},
},
@@ -228,7 +213,7 @@ export const connectorDetails = {
Response: {
status: 200,
body: {
- status: "processing",
+ status: "succeeded",
},
},
},
@@ -338,7 +323,8 @@ export const connectorDetails = {
Response: {
status: 200,
body: {
- status: "requires_customer_action",
+ status: "failed",
+ error_code: "PERMISSION_DENIED",
},
},
},
|
ci
|
Update card number for adyen and status for paypal (#5192)
|
4e875d42209e07baa3391b3dfff2442fcfab397b
|
2024-09-27 18:50:05
|
Kartikeya Hegde
|
fix(config): dont read cert and url if keymanager is disabled (#6091)
| false
|
diff --git a/config/development.toml b/config/development.toml
index 29beed992f6..3cdb4f31112 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -13,7 +13,7 @@ use_xray_generator = false
bg_metrics_collection_interval_in_secs = 15
[key_manager]
-url = "http://localhost:5000"
+enabled = false
# TODO: Update database credentials before running application
[master_database]
diff --git a/crates/common_utils/src/types/keymanager.rs b/crates/common_utils/src/types/keymanager.rs
index abcb7aa87f7..078f1f3fcd8 100644
--- a/crates/common_utils/src/types/keymanager.rs
+++ b/crates/common_utils/src/types/keymanager.rs
@@ -25,7 +25,7 @@ use crate::{
#[derive(Debug, Clone)]
pub struct KeyManagerState {
- pub enabled: Option<bool>,
+ pub enabled: bool,
pub url: String,
pub client_idle_timeout: Option<u64>,
#[cfg(feature = "km_forward_x_request_id")]
diff --git a/crates/hyperswitch_domain_models/src/type_encryption.rs b/crates/hyperswitch_domain_models/src/type_encryption.rs
index 0ff37b0bc29..983528dee98 100644
--- a/crates/hyperswitch_domain_models/src/type_encryption.rs
+++ b/crates/hyperswitch_domain_models/src/type_encryption.rs
@@ -101,7 +101,7 @@ mod encrypt {
fn is_encryption_service_enabled(_state: &KeyManagerState) -> bool {
#[cfg(feature = "encryption_service")]
{
- _state.enabled.unwrap_or_default()
+ _state.enabled
}
#[cfg(not(feature = "encryption_service"))]
{
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index ead168b7d0f..88011529bbf 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -12495,16 +12495,3 @@ pub fn get_shipping_required_fields() -> HashMap<String, RequiredFieldInfo> {
),
])
}
-
-impl Default for super::settings::KeyManagerConfig {
- fn default() -> Self {
- Self {
- enabled: None,
- url: String::from("localhost:5000"),
- #[cfg(feature = "keymanager_mtls")]
- ca: String::default().into(),
- #[cfg(feature = "keymanager_mtls")]
- cert: String::default().into(),
- }
- }
-}
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index e1b68efc446..0f25477802c 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -232,14 +232,22 @@ impl SecretsHandler for settings::KeyManagerConfig {
let keyconfig = value.get_inner();
#[cfg(feature = "keymanager_mtls")]
- let ca = _secret_management_client
- .get_secret(keyconfig.ca.clone())
- .await?;
+ let ca = if keyconfig.enabled {
+ _secret_management_client
+ .get_secret(keyconfig.ca.clone())
+ .await?
+ } else {
+ keyconfig.ca.clone()
+ };
#[cfg(feature = "keymanager_mtls")]
- let cert = _secret_management_client
- .get_secret(keyconfig.cert.clone())
- .await?;
+ let cert = if keyconfig.enabled {
+ _secret_management_client
+ .get_secret(keyconfig.cert.clone())
+ .await?
+ } else {
+ keyconfig.ca.clone()
+ };
Ok(value.transition_state(|keyconfig| Self {
#[cfg(feature = "keymanager_mtls")]
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index e59dd73cd3b..1124423714b 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -215,9 +215,10 @@ pub struct KvConfig {
pub soft_kill: Option<bool>,
}
-#[derive(Debug, Deserialize, Clone)]
+#[derive(Debug, Deserialize, Clone, Default)]
+#[serde(default)]
pub struct KeyManagerConfig {
- pub enabled: Option<bool>,
+ pub enabled: bool,
pub url: String,
#[cfg(feature = "keymanager_mtls")]
pub cert: Secret<String>,
@@ -863,6 +864,8 @@ impl Settings<SecuredSecret> {
.map(|x| x.get_inner().validate())
.transpose()?;
+ self.key_manager.get_inner().validate()?;
+
Ok(())
}
}
diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs
index bfea4eee42d..f109fe3f773 100644
--- a/crates/router/src/configs/validations.rs
+++ b/crates/router/src/configs/validations.rs
@@ -235,3 +235,25 @@ impl super::settings::NetworkTokenizationService {
})
}
}
+
+impl super::settings::KeyManagerConfig {
+ pub fn validate(&self) -> Result<(), ApplicationError> {
+ use common_utils::fp_utils::when;
+
+ #[cfg(feature = "keymanager_mtls")]
+ when(
+ self.enabled && (self.ca.is_default_or_empty() || self.cert.is_default_or_empty()),
+ || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Invalid CA or Certificate for Keymanager.".into(),
+ ))
+ },
+ )?;
+
+ when(self.enabled && self.url.is_default_or_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Invalid URL for Keymanager".into(),
+ ))
+ })
+ }
+}
|
fix
|
dont read cert and url if keymanager is disabled (#6091)
|
b8be10de52e40d2327819d33c6c1ec40a459bdd5
|
2024-04-22 16:42:47
|
Sakil Mostak
|
feat(euclied_wasm): [NMI] Add configs for extended 3DS (#4422)
| false
|
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index ee5f3ba749f..849da0d9236 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -1325,6 +1325,10 @@ key1="Public Key"
[nmi.connector_webhook_details]
merchant_secret="Source verification key"
+[nmi.metadata]
+acquirer_bin = "Acquirer Bin"
+acquirer_merchant_id = "Acquirer Merchant ID"
+
[nmi.metadata.google_pay]
merchant_name="Google Pay Merchant Name"
gateway_merchant_id="Google Pay Merchant Key"
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index b643f5a2fda..912949a3152 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -1325,6 +1325,10 @@ key1="Public Key"
[nmi.connector_webhook_details]
merchant_secret="Source verification key"
+[nmi.metadata]
+acquirer_bin = "Acquirer Bin"
+acquirer_merchant_id = "Acquirer Merchant ID"
+
[nmi.metadata.google_pay]
merchant_name="Google Pay Merchant Name"
gateway_merchant_id="Google Pay Merchant Key"
|
feat
|
[NMI] Add configs for extended 3DS (#4422)
|
4bfabdfa24b24c4bc2dddfca4bd8dd7b34003863
|
2024-12-05 16:13:22
|
Sahkal Poddar
|
feat(core): add is_click_to_pay_enabled in business profile (#6736)
| false
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 1af9284596d..78d58c69719 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -17241,7 +17241,8 @@
"ProfileCreate": {
"type": "object",
"required": [
- "profile_name"
+ "profile_name",
+ "is_click_to_pay_enabled"
],
"properties": {
"profile_name": {
@@ -17399,6 +17400,12 @@
"is_network_tokenization_enabled": {
"type": "boolean",
"description": "Indicates if network tokenization is enabled or not."
+ },
+ "is_click_to_pay_enabled": {
+ "type": "boolean",
+ "description": "Indicates if click to pay is enabled or not.",
+ "default": false,
+ "example": false
}
},
"additionalProperties": false
@@ -17431,7 +17438,8 @@
"redirect_to_merchant_with_http_post",
"is_tax_connector_enabled",
"is_network_tokenization_enabled",
- "should_collect_cvv_during_payment"
+ "should_collect_cvv_during_payment",
+ "is_click_to_pay_enabled"
],
"properties": {
"merchant_id": {
@@ -17611,6 +17619,12 @@
"should_collect_cvv_during_payment": {
"type": "boolean",
"description": "Indicates if CVV should be collected during payment or not."
+ },
+ "is_click_to_pay_enabled": {
+ "type": "boolean",
+ "description": "Indicates if click to pay is enabled or not.",
+ "default": false,
+ "example": false
}
}
},
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json
index f2904dd4783..b391061c387 100644
--- a/api-reference/openapi_spec.json
+++ b/api-reference/openapi_spec.json
@@ -21668,6 +21668,10 @@
"description": "Maximum number of auto retries allowed for a payment",
"nullable": true,
"minimum": 0
+ },
+ "is_click_to_pay_enabled": {
+ "type": "boolean",
+ "description": "Indicates if click to pay is enabled or not."
}
},
"additionalProperties": false
@@ -21700,7 +21704,8 @@
"redirect_to_merchant_with_http_post",
"is_tax_connector_enabled",
"is_network_tokenization_enabled",
- "is_auto_retries_enabled"
+ "is_auto_retries_enabled",
+ "is_click_to_pay_enabled"
],
"properties": {
"merchant_id": {
@@ -21897,6 +21902,12 @@
"format": "int32",
"description": "Maximum number of auto retries allowed for a payment",
"nullable": true
+ },
+ "is_click_to_pay_enabled": {
+ "type": "boolean",
+ "description": "Indicates if click to pay is enabled or not.",
+ "default": false,
+ "example": false
}
}
},
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index f0a8c999438..53ce8678966 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -1966,6 +1966,10 @@ pub struct ProfileCreate {
/// Maximum number of auto retries allowed for a payment
pub max_auto_retries_enabled: Option<u8>,
+
+ /// Indicates if click to pay is enabled or not.
+ #[serde(default)]
+ pub is_click_to_pay_enabled: bool,
}
#[nutype::nutype(
@@ -2074,6 +2078,10 @@ pub struct ProfileCreate {
/// Indicates if network tokenization is enabled or not.
#[serde(default)]
pub is_network_tokenization_enabled: bool,
+
+ /// Indicates if click to pay is enabled or not.
+ #[schema(default = false, example = false)]
+ pub is_click_to_pay_enabled: bool,
}
#[cfg(feature = "v1")]
@@ -2202,6 +2210,10 @@ pub struct ProfileResponse {
/// Maximum number of auto retries allowed for a payment
pub max_auto_retries_enabled: Option<i16>,
+
+ /// Indicates if click to pay is enabled or not.
+ #[schema(default = false, example = false)]
+ pub is_click_to_pay_enabled: bool,
}
#[cfg(feature = "v2")]
@@ -2317,6 +2329,10 @@ pub struct ProfileResponse {
/// Indicates if CVV should be collected during payment or not.
pub should_collect_cvv_during_payment: bool,
+
+ /// Indicates if click to pay is enabled or not.
+ #[schema(default = false, example = false)]
+ pub is_click_to_pay_enabled: bool,
}
#[cfg(feature = "v1")]
@@ -2439,6 +2455,10 @@ pub struct ProfileUpdate {
/// Maximum number of auto retries allowed for a payment
pub max_auto_retries_enabled: Option<u8>,
+
+ /// Indicates if click to pay is enabled or not.
+ #[schema(default = false, example = false)]
+ pub is_click_to_pay_enabled: Option<bool>,
}
#[cfg(feature = "v2")]
@@ -2542,6 +2562,10 @@ pub struct ProfileUpdate {
/// Indicates if network tokenization is enabled or not.
pub is_network_tokenization_enabled: Option<bool>,
+
+ /// Indicates if click to pay is enabled or not.
+ #[schema(default = false, example = false)]
+ pub is_click_to_pay_enabled: Option<bool>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index 1f8209397ae..484a1c0c699 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -57,6 +57,7 @@ pub struct Profile {
pub is_network_tokenization_enabled: bool,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
+ pub is_click_to_pay_enabled: bool,
}
#[cfg(feature = "v1")]
@@ -100,6 +101,7 @@ pub struct ProfileNew {
pub is_network_tokenization_enabled: bool,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
+ pub is_click_to_pay_enabled: bool,
}
#[cfg(feature = "v1")]
@@ -140,6 +142,7 @@ pub struct ProfileUpdateInternal {
pub is_network_tokenization_enabled: Option<bool>,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
+ pub is_click_to_pay_enabled: Option<bool>,
}
#[cfg(feature = "v1")]
@@ -179,6 +182,7 @@ impl ProfileUpdateInternal {
is_network_tokenization_enabled,
is_auto_retries_enabled,
max_auto_retries_enabled,
+ is_click_to_pay_enabled,
} = self;
Profile {
profile_id: source.profile_id,
@@ -238,6 +242,8 @@ impl ProfileUpdateInternal {
.unwrap_or(source.is_network_tokenization_enabled),
is_auto_retries_enabled: is_auto_retries_enabled.or(source.is_auto_retries_enabled),
max_auto_retries_enabled: max_auto_retries_enabled.or(source.max_auto_retries_enabled),
+ is_click_to_pay_enabled: is_click_to_pay_enabled
+ .unwrap_or(source.is_click_to_pay_enabled),
}
}
}
@@ -292,6 +298,7 @@ pub struct Profile {
pub is_network_tokenization_enabled: bool,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
+ pub is_click_to_pay_enabled: bool,
}
impl Profile {
@@ -350,6 +357,7 @@ pub struct ProfileNew {
pub is_network_tokenization_enabled: bool,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
+ pub is_click_to_pay_enabled: bool,
}
#[cfg(feature = "v2")]
@@ -392,6 +400,7 @@ pub struct ProfileUpdateInternal {
pub is_network_tokenization_enabled: Option<bool>,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
+ pub is_click_to_pay_enabled: Option<bool>,
}
#[cfg(feature = "v2")]
@@ -433,6 +442,7 @@ impl ProfileUpdateInternal {
is_network_tokenization_enabled,
is_auto_retries_enabled,
max_auto_retries_enabled,
+ is_click_to_pay_enabled,
} = self;
Profile {
id: source.id,
@@ -497,6 +507,8 @@ impl ProfileUpdateInternal {
.unwrap_or(source.is_network_tokenization_enabled),
is_auto_retries_enabled: is_auto_retries_enabled.or(source.is_auto_retries_enabled),
max_auto_retries_enabled: max_auto_retries_enabled.or(source.max_auto_retries_enabled),
+ is_click_to_pay_enabled: is_click_to_pay_enabled
+ .unwrap_or(source.is_click_to_pay_enabled),
}
}
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index b6f1a4f8d05..936428bd46c 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -213,6 +213,7 @@ diesel::table! {
is_network_tokenization_enabled -> Bool,
is_auto_retries_enabled -> Nullable<Bool>,
max_auto_retries_enabled -> Nullable<Int2>,
+ is_click_to_pay_enabled -> Bool,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 470868ed82d..8a1733fc986 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -221,6 +221,7 @@ diesel::table! {
is_network_tokenization_enabled -> Bool,
is_auto_retries_enabled -> Nullable<Bool>,
max_auto_retries_enabled -> Nullable<Int2>,
+ is_click_to_pay_enabled -> Bool,
}
}
diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs
index 3e8213a3588..433353b2f81 100644
--- a/crates/hyperswitch_domain_models/src/business_profile.rs
+++ b/crates/hyperswitch_domain_models/src/business_profile.rs
@@ -58,6 +58,7 @@ pub struct Profile {
pub is_network_tokenization_enabled: bool,
pub is_auto_retries_enabled: bool,
pub max_auto_retries_enabled: Option<i16>,
+ pub is_click_to_pay_enabled: bool,
}
#[cfg(feature = "v1")]
@@ -98,6 +99,7 @@ pub struct ProfileSetter {
pub is_network_tokenization_enabled: bool,
pub is_auto_retries_enabled: bool,
pub max_auto_retries_enabled: Option<i16>,
+ pub is_click_to_pay_enabled: bool,
}
#[cfg(feature = "v1")]
@@ -145,6 +147,7 @@ impl From<ProfileSetter> for Profile {
is_network_tokenization_enabled: value.is_network_tokenization_enabled,
is_auto_retries_enabled: value.is_auto_retries_enabled,
max_auto_retries_enabled: value.max_auto_retries_enabled,
+ is_click_to_pay_enabled: value.is_click_to_pay_enabled,
}
}
}
@@ -194,6 +197,7 @@ pub struct ProfileGeneralUpdate {
pub is_network_tokenization_enabled: Option<bool>,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
+ pub is_click_to_pay_enabled: Option<bool>,
}
#[cfg(feature = "v1")]
@@ -256,6 +260,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_network_tokenization_enabled,
is_auto_retries_enabled,
max_auto_retries_enabled,
+ is_click_to_pay_enabled,
} = *update;
Self {
@@ -293,6 +298,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_network_tokenization_enabled,
is_auto_retries_enabled,
max_auto_retries_enabled,
+ is_click_to_pay_enabled,
}
}
ProfileUpdate::RoutingAlgorithmUpdate {
@@ -332,6 +338,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
+ is_click_to_pay_enabled: None,
},
ProfileUpdate::DynamicRoutingAlgorithmUpdate {
dynamic_routing_algorithm,
@@ -369,6 +376,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
+ is_click_to_pay_enabled: None,
},
ProfileUpdate::ExtendedCardInfoUpdate {
is_extended_card_info_enabled,
@@ -406,6 +414,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
+ is_click_to_pay_enabled: None,
},
ProfileUpdate::ConnectorAgnosticMitUpdate {
is_connector_agnostic_mit_enabled,
@@ -443,6 +452,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
+ is_click_to_pay_enabled: None,
},
ProfileUpdate::NetworkTokenizationUpdate {
is_network_tokenization_enabled,
@@ -480,6 +490,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_network_tokenization_enabled: Some(is_network_tokenization_enabled),
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
+ is_click_to_pay_enabled: None,
},
}
}
@@ -536,6 +547,7 @@ impl super::behaviour::Conversion for Profile {
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
is_auto_retries_enabled: Some(self.is_auto_retries_enabled),
max_auto_retries_enabled: self.max_auto_retries_enabled,
+ is_click_to_pay_enabled: self.is_click_to_pay_enabled,
})
}
@@ -604,6 +616,7 @@ impl super::behaviour::Conversion for Profile {
is_network_tokenization_enabled: item.is_network_tokenization_enabled,
is_auto_retries_enabled: item.is_auto_retries_enabled.unwrap_or(false),
max_auto_retries_enabled: item.max_auto_retries_enabled,
+ is_click_to_pay_enabled: item.is_click_to_pay_enabled,
})
}
.await
@@ -656,6 +669,7 @@ impl super::behaviour::Conversion for Profile {
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
is_auto_retries_enabled: Some(self.is_auto_retries_enabled),
max_auto_retries_enabled: self.max_auto_retries_enabled,
+ is_click_to_pay_enabled: self.is_click_to_pay_enabled,
})
}
}
@@ -700,6 +714,7 @@ pub struct Profile {
pub is_tax_connector_enabled: bool,
pub version: common_enums::ApiVersion,
pub is_network_tokenization_enabled: bool,
+ pub is_click_to_pay_enabled: bool,
}
#[cfg(feature = "v2")]
@@ -740,6 +755,7 @@ pub struct ProfileSetter {
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: bool,
pub is_network_tokenization_enabled: bool,
+ pub is_click_to_pay_enabled: bool,
}
#[cfg(feature = "v2")]
@@ -787,6 +803,7 @@ impl From<ProfileSetter> for Profile {
is_tax_connector_enabled: value.is_tax_connector_enabled,
version: consts::API_VERSION,
is_network_tokenization_enabled: value.is_network_tokenization_enabled,
+ is_click_to_pay_enabled: value.is_click_to_pay_enabled,
}
}
}
@@ -837,6 +854,7 @@ pub struct ProfileGeneralUpdate {
pub order_fulfillment_time: Option<i64>,
pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>,
pub is_network_tokenization_enabled: Option<bool>,
+ pub is_click_to_pay_enabled: Option<bool>,
}
#[cfg(feature = "v2")]
@@ -895,6 +913,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
order_fulfillment_time,
order_fulfillment_time_origin,
is_network_tokenization_enabled,
+ is_click_to_pay_enabled,
} = *update;
Self {
profile_name,
@@ -933,6 +952,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_network_tokenization_enabled,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
+ is_click_to_pay_enabled,
}
}
ProfileUpdate::RoutingAlgorithmUpdate {
@@ -974,6 +994,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
+ is_click_to_pay_enabled: None,
},
ProfileUpdate::ExtendedCardInfoUpdate {
is_extended_card_info_enabled,
@@ -1013,6 +1034,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
+ is_click_to_pay_enabled: None,
},
ProfileUpdate::ConnectorAgnosticMitUpdate {
is_connector_agnostic_mit_enabled,
@@ -1052,6 +1074,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
+ is_click_to_pay_enabled: None,
},
ProfileUpdate::DefaultRoutingFallbackUpdate {
default_fallback_routing,
@@ -1091,6 +1114,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
+ is_click_to_pay_enabled: None,
},
ProfileUpdate::NetworkTokenizationUpdate {
is_network_tokenization_enabled,
@@ -1130,6 +1154,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_network_tokenization_enabled: Some(is_network_tokenization_enabled),
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
+ is_click_to_pay_enabled: None,
},
ProfileUpdate::CollectCvvDuringPaymentUpdate {
should_collect_cvv_during_payment,
@@ -1169,6 +1194,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
+ is_click_to_pay_enabled: None,
},
}
}
@@ -1228,6 +1254,7 @@ impl super::behaviour::Conversion for Profile {
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
+ is_click_to_pay_enabled: self.is_click_to_pay_enabled,
})
}
@@ -1296,6 +1323,7 @@ impl super::behaviour::Conversion for Profile {
is_tax_connector_enabled: item.is_tax_connector_enabled.unwrap_or(false),
version: item.version,
is_network_tokenization_enabled: item.is_network_tokenization_enabled,
+ is_click_to_pay_enabled: item.is_click_to_pay_enabled,
})
}
.await
@@ -1351,6 +1379,7 @@ impl super::behaviour::Conversion for Profile {
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
+ is_click_to_pay_enabled: self.is_click_to_pay_enabled,
})
}
}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 055c428b1fb..6e2ed220721 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -3555,6 +3555,7 @@ impl ProfileCreateBridge for api::ProfileCreate {
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
is_auto_retries_enabled: self.is_auto_retries_enabled.unwrap_or_default(),
max_auto_retries_enabled: self.max_auto_retries_enabled.map(i16::from),
+ is_click_to_pay_enabled: self.is_click_to_pay_enabled,
}))
}
@@ -3662,6 +3663,7 @@ impl ProfileCreateBridge for api::ProfileCreate {
tax_connector_id: self.tax_connector_id,
is_tax_connector_enabled: self.is_tax_connector_enabled,
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
+ is_click_to_pay_enabled: self.is_click_to_pay_enabled,
}))
}
}
@@ -3911,6 +3913,7 @@ impl ProfileUpdateBridge for api::ProfileUpdate {
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
is_auto_retries_enabled: self.is_auto_retries_enabled,
max_auto_retries_enabled: self.max_auto_retries_enabled.map(i16::from),
+ is_click_to_pay_enabled: self.is_click_to_pay_enabled,
},
)))
}
@@ -4007,6 +4010,7 @@ impl ProfileUpdateBridge for api::ProfileUpdate {
always_collect_shipping_details_from_wallet_connector: self
.always_collect_shipping_details_from_wallet_connector,
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
+ is_click_to_pay_enabled: self.is_click_to_pay_enabled,
},
)))
}
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index 85275a768df..7207f63aa0f 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -174,6 +174,7 @@ impl ForeignTryFrom<domain::Profile> for ProfileResponse {
is_network_tokenization_enabled: item.is_network_tokenization_enabled,
is_auto_retries_enabled: item.is_auto_retries_enabled,
max_auto_retries_enabled: item.max_auto_retries_enabled,
+ is_click_to_pay_enabled: item.is_click_to_pay_enabled,
})
}
}
@@ -241,6 +242,7 @@ impl ForeignTryFrom<domain::Profile> for ProfileResponse {
tax_connector_id: item.tax_connector_id,
is_tax_connector_enabled: item.is_tax_connector_enabled,
is_network_tokenization_enabled: item.is_network_tokenization_enabled,
+ is_click_to_pay_enabled: item.is_click_to_pay_enabled,
})
}
}
@@ -367,5 +369,6 @@ pub async fn create_profile_from_merchant_account(
is_network_tokenization_enabled: request.is_network_tokenization_enabled,
is_auto_retries_enabled: request.is_auto_retries_enabled.unwrap_or_default(),
max_auto_retries_enabled: request.max_auto_retries_enabled.map(i16::from),
+ is_click_to_pay_enabled: request.is_click_to_pay_enabled,
}))
}
diff --git a/migrations/2024-12-04-072648_add_is_click_to_pay_enabled/down.sql b/migrations/2024-12-04-072648_add_is_click_to_pay_enabled/down.sql
new file mode 100644
index 00000000000..8ff46e69d6f
--- /dev/null
+++ b/migrations/2024-12-04-072648_add_is_click_to_pay_enabled/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE business_profile DROP COLUMN IF EXISTS is_click_to_pay_enabled;
\ No newline at end of file
diff --git a/migrations/2024-12-04-072648_add_is_click_to_pay_enabled/up.sql b/migrations/2024-12-04-072648_add_is_click_to_pay_enabled/up.sql
new file mode 100644
index 00000000000..3adb84258b7
--- /dev/null
+++ b/migrations/2024-12-04-072648_add_is_click_to_pay_enabled/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE business_profile ADD COLUMN IF NOT EXISTS is_click_to_pay_enabled BOOLEAN NOT NULL DEFAULT FALSE;
\ No newline at end of file
|
feat
|
add is_click_to_pay_enabled in business profile (#6736)
|
8c99db72adbd2b5f03c37fa5b1fa82b9c77ce2c5
|
2024-09-18 16:56:35
|
Narayan Bhat
|
fix(merchant_account_v2): remove compatible_connector field in metadata (#5935)
| false
|
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 1846ef0e45a..3b9a8e1c983 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -188,7 +188,7 @@ pub struct MerchantAccountCreate {
/// Metadata is useful for storing additional, unstructured information about the merchant account.
#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]
- pub metadata: Option<MerchantAccountMetadata>,
+ pub metadata: Option<pii::SecretSerdeValue>,
/// The id of the organization to which the merchant belongs to. Please use the organization endpoint to create an organization
#[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")]
@@ -210,15 +210,6 @@ impl MerchantAccountCreate {
.transpose()
}
- pub fn get_metadata_as_secret(
- &self,
- ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> {
- self.metadata
- .as_ref()
- .map(|metadata| metadata.encode_to_value().map(Secret::new))
- .transpose()
- }
-
pub fn get_primary_details_as_value(
&self,
) -> CustomResult<serde_json::Value, errors::ParsingError> {
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 690d16596b8..95b02f0cdb3 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -606,12 +606,6 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {
let publishable_key = create_merchant_publishable_key();
let db = &*state.store;
- let metadata = self.get_metadata_as_secret().change_context(
- errors::ApiErrorResponse::InvalidDataValue {
- field_name: "metadata",
- },
- )?;
-
let merchant_details = self.get_merchant_details_as_secret().change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "merchant_details",
@@ -659,7 +653,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {
})
.await?,
publishable_key,
- metadata,
+ metadata: self.metadata,
storage_scheme: MerchantStorageScheme::PostgresOnly,
created_at: date_time::now(),
modified_at: date_time::now(),
|
fix
|
remove compatible_connector field in metadata (#5935)
|
75ba3ff09f71d1dd295f9dad0060d2620d7b3764
|
2023-05-17 21:31:13
|
Sai Harsha Vardhan
|
feat(router): add mandates list api (#1143)
| false
|
diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs
index a5283b375e8..21733047440 100644
--- a/crates/api_models/src/mandates.rs
+++ b/crates/api_models/src/mandates.rs
@@ -1,5 +1,6 @@
use masking::Secret;
use serde::{Deserialize, Serialize};
+use time::PrimitiveDateTime;
use utoipa::ToSchema;
use crate::{enums as api_enums, payments};
@@ -60,3 +61,33 @@ pub struct MandateCardDetails {
/// A unique identifier alias to identify a particular card
pub card_fingerprint: Option<Secret<String>>,
}
+
+#[derive(Clone, Debug, Deserialize, ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct MandateListConstraints {
+ /// limit on the number of objects to return
+ pub limit: Option<i64>,
+ /// status of the mandate
+ pub mandate_status: Option<api_enums::MandateStatus>,
+ /// connector linked to mandate
+ pub connector: Option<String>,
+ /// The time at which mandate is created
+ #[schema(example = "2022-09-10T10:11:12Z")]
+ pub created_time: Option<PrimitiveDateTime>,
+ /// Time less than the mandate created time
+ #[schema(example = "2022-09-10T10:11:12Z")]
+ #[serde(rename = "created_time.lt")]
+ pub created_time_lt: Option<PrimitiveDateTime>,
+ /// Time greater than the mandate created time
+ #[schema(example = "2022-09-10T10:11:12Z")]
+ #[serde(rename = "created_time.gt")]
+ pub created_time_gt: Option<PrimitiveDateTime>,
+ /// Time less than or equals to the mandate created time
+ #[schema(example = "2022-09-10T10:11:12Z")]
+ #[serde(rename = "created_time.lte")]
+ pub created_time_lte: Option<PrimitiveDateTime>,
+ /// Time greater than or equals to the mandate created time
+ #[schema(example = "2022-09-10T10:11:12Z")]
+ #[serde(rename = "created_time.gte")]
+ pub created_time_gte: Option<PrimitiveDateTime>,
+}
diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs
index c07a6499349..3273c5a579e 100644
--- a/crates/router/src/core/mandate.rs
+++ b/crates/router/src/core/mandate.rs
@@ -1,5 +1,6 @@
use common_utils::{ext_traits::Encode, pii};
use error_stack::{report, ResultExt};
+use futures::future;
use router_env::{instrument, logger, tracing};
use storage_models::enums as storage_enums;
@@ -259,6 +260,25 @@ where
Ok(resp)
}
+#[instrument(skip(state))]
+pub async fn retrieve_mandates_list(
+ state: &AppState,
+ merchant_account: storage::MerchantAccount,
+ constraints: api_models::mandates::MandateListConstraints,
+) -> RouterResponse<Vec<api_models::mandates::MandateResponse>> {
+ let mandates = state
+ .store
+ .find_mandates_by_merchant_id(&merchant_account.merchant_id, constraints)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to retrieve mandates")?;
+ let mandates_list = future::try_join_all(mandates.into_iter().map(|mandate| {
+ mandates::MandateResponse::from_db_mandate(state, mandate, &merchant_account)
+ }))
+ .await?;
+ Ok(services::ApplicationResponse::Json(mandates_list))
+}
+
impl ForeignTryFrom<Result<types::PaymentsResponseData, types::ErrorResponse>>
for Option<pii::SecretSerdeValue>
{
diff --git a/crates/router/src/db/mandate.rs b/crates/router/src/db/mandate.rs
index b3cbbbd0788..2ac9595b776 100644
--- a/crates/router/src/db/mandate.rs
+++ b/crates/router/src/db/mandate.rs
@@ -4,7 +4,7 @@ use super::{MockDb, Store};
use crate::{
connection,
core::errors::{self, CustomResult},
- types::storage,
+ types::storage::{self, MandateDbExt},
};
#[async_trait::async_trait]
@@ -28,6 +28,12 @@ pub trait MandateInterface {
mandate: storage::MandateUpdate,
) -> CustomResult<storage::Mandate, errors::StorageError>;
+ async fn find_mandates_by_merchant_id(
+ &self,
+ merchant_id: &str,
+ mandate_constraints: api_models::mandates::MandateListConstraints,
+ ) -> CustomResult<Vec<storage::Mandate>, errors::StorageError>;
+
async fn insert_mandate(
&self,
mandate: storage::MandateNew,
@@ -73,6 +79,18 @@ impl MandateInterface for Store {
.into_report()
}
+ async fn find_mandates_by_merchant_id(
+ &self,
+ merchant_id: &str,
+ mandate_constraints: api_models::mandates::MandateListConstraints,
+ ) -> CustomResult<Vec<storage::Mandate>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::Mandate::filter_by_constraints(&conn, merchant_id, mandate_constraints)
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
+
async fn insert_mandate(
&self,
mandate: storage::MandateNew,
@@ -116,6 +134,15 @@ impl MandateInterface for MockDb {
Err(errors::StorageError::MockDbError)?
}
+ async fn find_mandates_by_merchant_id(
+ &self,
+ _merchant_id: &str,
+ _mandate_constraints: api_models::mandates::MandateListConstraints,
+ ) -> CustomResult<Vec<storage::Mandate>, errors::StorageError> {
+ // [#172]: Implement function for `MockDb`
+ Err(errors::StorageError::MockDbError)?
+ }
+
async fn insert_mandate(
&self,
_mandate: storage::MandateNew,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index dbfde139d24..d0062faf9ea 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -365,6 +365,8 @@ impl Mandates {
#[cfg(feature = "olap")]
{
+ route =
+ route.service(web::resource("/list").route(web::get().to(retrieve_mandates_list)));
route = route.service(web::resource("/{id}").route(web::get().to(get_mandate)));
}
#[cfg(feature = "oltp")]
diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs
index b980f082122..a0e211f2dc8 100644
--- a/crates/router/src/routes/mandates.rs
+++ b/crates/router/src/routes/mandates.rs
@@ -87,3 +87,44 @@ pub async fn revoke_mandate(
)
.await
}
+
+/// Mandates - List Mandates
+#[utoipa::path(
+ get,
+ path = "/mandates/list",
+ params(
+ ("limit" = Option<i64>, Query, description = "The maximum number of Mandate Objects to include in the response"),
+ ("mandate_status" = Option<MandateStatus>, Query, description = "The status of mandate"),
+ ("connector" = Option<String>, Query, description = "The connector linked to mandate"),
+ ("created_time" = Option<PrimitiveDateTime>, Query, description = "The time at which mandate is created"),
+ ("created_time.lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the mandate created time"),
+ ("created_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the mandate created time"),
+ ("created_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the mandate created time"),
+ ("created_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the mandate created time"),
+ ),
+ responses(
+ (status = 200, description = "The mandate list was retrieved successfully", body = Vec<MandateResponse>),
+ (status = 401, description = "Unauthorized request")
+ ),
+ tag = "Mandates",
+ operation_id = "List Mandates",
+ security(("api_key" = []))
+)]
+#[instrument(skip_all, fields(flow = ?Flow::MandatesList))]
+pub async fn retrieve_mandates_list(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ payload: web::Query<api_models::mandates::MandateListConstraints>,
+) -> HttpResponse {
+ let flow = Flow::MandatesList;
+ let payload = payload.into_inner();
+ api::server_wrap(
+ flow,
+ state.get_ref(),
+ &req,
+ payload,
+ mandate::retrieve_mandates_list,
+ auth::auth_type(&auth::ApiKeyAuth, &auth::JWTAuth, req.headers()),
+ )
+ .await
+}
diff --git a/crates/router/src/types/storage/mandate.rs b/crates/router/src/types/storage/mandate.rs
index bafecb42f25..0f1bdaae8fa 100644
--- a/crates/router/src/types/storage/mandate.rs
+++ b/crates/router/src/types/storage/mandate.rs
@@ -1,3 +1,71 @@
+use async_bb8_diesel::AsyncRunQueryDsl;
+use common_utils::errors::CustomResult;
+use diesel::{associations::HasTable, ExpressionMethods, QueryDsl};
+use error_stack::{IntoReport, ResultExt};
pub use storage_models::mandate::{
Mandate, MandateNew, MandateUpdate, MandateUpdateInternal, SingleUseMandate,
};
+use storage_models::{errors, schema::mandate::dsl};
+
+use crate::{connection::PgPooledConn, logger, types::transformers::ForeignInto};
+
+#[async_trait::async_trait]
+pub trait MandateDbExt: Sized {
+ async fn filter_by_constraints(
+ conn: &PgPooledConn,
+ merchant_id: &str,
+ mandate_list_constraints: api_models::mandates::MandateListConstraints,
+ ) -> CustomResult<Vec<Self>, errors::DatabaseError>;
+}
+
+#[async_trait::async_trait]
+impl MandateDbExt for Mandate {
+ async fn filter_by_constraints(
+ conn: &PgPooledConn,
+ merchant_id: &str,
+ mandate_list_constraints: api_models::mandates::MandateListConstraints,
+ ) -> CustomResult<Vec<Self>, errors::DatabaseError> {
+ let mut filter = <Self as HasTable>::table()
+ .filter(dsl::merchant_id.eq(merchant_id.to_owned()))
+ .order(dsl::created_at.desc())
+ .into_boxed();
+
+ if let Some(created_time) = mandate_list_constraints.created_time {
+ filter = filter.filter(dsl::created_at.eq(created_time));
+ }
+ if let Some(created_time_lt) = mandate_list_constraints.created_time_lt {
+ filter = filter.filter(dsl::created_at.lt(created_time_lt));
+ }
+ if let Some(created_time_gt) = mandate_list_constraints.created_time_gt {
+ filter = filter.filter(dsl::created_at.gt(created_time_gt));
+ }
+ if let Some(created_time_lte) = mandate_list_constraints.created_time_lte {
+ filter = filter.filter(dsl::created_at.le(created_time_lte));
+ }
+ if let Some(created_time_gte) = mandate_list_constraints.created_time_gte {
+ filter = filter.filter(dsl::created_at.ge(created_time_gte));
+ }
+ if let Some(connector) = mandate_list_constraints.connector {
+ filter = filter.filter(dsl::connector.eq(connector));
+ }
+ if let Some(mandate_status) = mandate_list_constraints.mandate_status {
+ let storage_mandate_status: storage_models::enums::MandateStatus =
+ mandate_status.foreign_into();
+ filter = filter.filter(dsl::mandate_status.eq(storage_mandate_status));
+ }
+ if let Some(limit) = mandate_list_constraints.limit {
+ filter = filter.limit(limit);
+ }
+
+ logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
+
+ filter
+ .get_results_async(conn)
+ .await
+ .into_report()
+ // The query built here returns an empty Vec when no records are found, and if any error does occur,
+ // it would be an internal database error, due to which we are raising a DatabaseError::Unknown error
+ .change_context(errors::DatabaseError::Others)
+ .attach_printable("Error filtering mandates by specified constraints")
+ }
+}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 7f5a7f1b551..822121803ab 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -76,6 +76,12 @@ impl ForeignFrom<storage_enums::MandateStatus> for api_enums::MandateStatus {
}
}
+impl ForeignFrom<api_enums::MandateStatus> for storage_enums::MandateStatus {
+ fn foreign_from(status: api_enums::MandateStatus) -> Self {
+ frunk::labelled_convert_from(status)
+ }
+}
+
impl ForeignFrom<api_enums::PaymentMethod> for storage_enums::PaymentMethod {
fn foreign_from(pm_type: api_enums::PaymentMethod) -> Self {
frunk::labelled_convert_from(pm_type)
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 12ebb2e205a..0266373beb7 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -96,6 +96,8 @@ pub enum Flow {
MandatesRetrieve,
/// Mandates revoke flow.
MandatesRevoke,
+ /// Mandates list flow.
+ MandatesList,
/// Payment methods create flow.
PaymentMethodsCreate,
/// Payment methods list flow.
|
feat
|
add mandates list api (#1143)
|
39cde670f38257e7629f961176f09c492714065e
|
2024-12-03 22:21:45
|
Pa1NarK
|
ci: update cypress creds (#6726)
| false
|
diff --git a/.github/workflows/cypress-tests-runner.yml b/.github/workflows/cypress-tests-runner.yml
index 93e8b34eb08..bb22a5692ad 100644
--- a/.github/workflows/cypress-tests-runner.yml
+++ b/.github/workflows/cypress-tests-runner.yml
@@ -127,7 +127,7 @@ jobs:
CONNECTOR_AUTH_PASSPHRASE: ${{ secrets.CONNECTOR_AUTH_PASSPHRASE }}
CONNECTOR_CREDS_S3_BUCKET_URI: ${{ secrets.CONNECTOR_CREDS_S3_BUCKET_URI}}
DESTINATION_FILE_NAME: "creds.json.gpg"
- S3_SOURCE_FILE_NAME: "c5701d35-aede-4d85-a866-0da4721acf30.json.gpg"
+ S3_SOURCE_FILE_NAME: "6f8289a9-6da0-433b-8a24-18d4d7257b7f.json.gpg"
shell: bash
run: |
mkdir -p ".github/secrets" ".github/test"
|
ci
|
update cypress creds (#6726)
|
8ee1a58c386fc5f08025c6ac90c96468e6d26bc7
|
2024-04-25 13:31:58
|
Gnanasundari24
|
docs(cypress): Update Cypress README Documentation (#4380)
| false
|
diff --git a/cypress-tests/readme.md b/cypress-tests/readme.md
index 8e08d6c01de..e77cd7ed10d 100644
--- a/cypress-tests/readme.md
+++ b/cypress-tests/readme.md
@@ -1,29 +1,37 @@
# Cypress Tests
## Overview
+
This Tool is a solution designed to automate testing for the [Hyperswitch](https://github.com/juspay/hyperswitch/) using Cypress, an open-source tool capable of conducting API call tests and UI tests. This README provides guidance on installing Cypress and its dependencies.
## Installation
### Prerequisites
+
Before installing Cypress, ensure you have the following prerequisites installed:
+
- npm (Node Package Manager)
- Node.js (18.x and above)
### Run Test Cases on your local
+
To run test cases, follow these steps:
1. Install Cypress
+
```shell
npm install cypress --save-dev
```
-3. Clone the repository and switch to the project directory:
+
+2. Clone the repository and switch to the project directory:
```shell
git clone https://github.com/juspay/hyperswitch
cd cypress-tests
```
-4. Set environment variables for cypress
+
+3. Set environment variables for cypress
+
```shell
export CYPRESS_CONNECTOR="connector_id"
export CYPRESS_BASEURL="base_url"
@@ -31,15 +39,158 @@ To run test cases, follow these steps:
export CYPRESS_ADMINAPIKEY="admin_api_key"
```
-5. Run Cypress test cases
- To run the tests in a browser in interactive mode run the following command
- ```
- npm run cypress
- ```
- To run the tests in headless mode run the following command
- ```
- npm run cypress:ci
- ```
+4. Run Cypress test cases
+
+ To execute a connector create test, ensure the connector details are included in the `creds.json` file. Then, integrate the path in the `command.js` as follows:
+
+ ```javascript
+ import ConnectorAuthDetails from "../../creds.json";
+ ```
+
+ To run the tests in a browser in interactive mode run the following command
+
+ ```shell
+ npm run cypress
+ ```
+
+ To run the tests in headless mode run the following command
+
+ ```shell
+ npm run cypress:ci
+ ```
+
+## Folder Structure
+
+The folder structure of this directory is as follows:
+
+```text
+. # The root directory for the Cypress tests.
+├── .gitignore
+├── cypress # Contains Cypress-related files and folders.
+│ ├── e2e # End-to-end test directory.
+│ │ ├── ConnectorTest # Directory for test scenarios related to connectors.
+│ │ │ ├── your_testcase1_files_here.cy.js
+│ │ │ ├── your_testcase2_files_here.cy.js
+│ │ │ └── ...
+│ │ └── ConnectorUtils # Directory for utility functions related to connectors.
+│ │ ├── connector_detail_files_here.js
+│ │ └── utils.js
+│ ├── fixtures # Directory for storing test data API request.
+│ │ └── your_fixture_files_here.json
+│ ├── support # Directory for Cypress support files.
+│ │ ├── commands.js # File containing custom Cypress commands and utilities.
+│ │ └── e2e.js
+│ └── utils
+│ └── utility_files_go_here.js
+├── cypress.config.js # Cypress configuration file.
+├── cypress.env.json # File is used to store environment-specific configuration values,such as base URLs, which can be accessed within your Cypress tests.
+├── package.json # Node.js package file.
+├── readme.md # This file
+└── yarn.lock
+```
+
+## Writing Tests
+
+### Adding Connectors
+
+To add a new connector for testing with Hyperswitch, follow these steps:
+
+1.Include the connector details in the `creds.json` file:
+
+example:
+
+```json
+{
+ "stripe": {
+ "auth_type": "HeaderKey",
+ "api_key": "SK_134"
+ }
+}
+```
+
+2.Add the new connector details to the ConnectorUtils folder (including CardNo and connector-specific information).
+
+Refer to Stripe.js file for guidance:
+
+```javascript
+/cypress-tests/cypress/e2e/ConnectorUtils/Stripe.js
+```
+
+Similarly, create a new file named newconnectorname.js and include all the relevant information for that connector.
+
+3.In util.js, import the new connector details.
+
+### Adding Functions
+
+Similarly, add any helper functions or utilities in the `command.js` in support folder and import them into your tests as needed.
+
+Example: Adding List Mandate function to support `ListMandate` scenario
+
+```javascript
+Cypress.Commands.add("listMandateCallTest", (globalState) => {
+ const customerId = globalState.get("customerId");
+ cy.request({
+ method: "GET",
+ url: `${globalState.get("baseUrl")}/customers/${customerId}/mandates`,
+ headers: {
+ "Content-Type": "application/json",
+ "api-key": globalState.get("apiKey"),
+ },
+ }).then((response) => {
+ const xRequestId = response.headers["x-request-id"];
+ if (xRequestId) {
+ cy.task("cli_log", "x-request-id ->> " + xRequestId);
+ } else {
+ cy.task(
+ "cli_log",
+ "x-request-id is not available in the response headers"
+ );
+ }
+ expect(response.headers["content-type"]).to.include("application/json");
+ console.log(response.body);
+ let i = 0;
+ for (i in response.body) {
+ if (response.body[i].mandate_id === globalState.get("mandateId")) {
+ expect(response.body[i].status).to.equal("active");
+ }
+ }
+ });
+});
+```
+
+### Adding Scenarios
+
+To add new test scenarios:
+
+1. Navigate to the ConnectorTest directory.
+2. Create a new test file or modify existing ones to add your scenarios.
+3. Write your test scenarios using Cypress commands.
+
+For example, to add a scenario for listing mandates in the `Mandateflows`:
+
+```javascript
+
+// cypress/ConnectorTest/CreateSingleuseMandate.js
+
+describe("Payment Scenarios", () => {
+ it("should complete a successful payment", () => {
+ // Your test logic here
+ });
+});
+```
+
+In this scenario, you can call functions defined in `command.js`. For instance, to test the `listMandateCallTest` function:
+
+```javascript
+describe("Payment Scenarios", () => {
+ it("list-mandate-call-test", () => {
+ cy.listMandateCallTest(globalState);
+ });
+});
+```
+
+You can create similar scenarios by calling other functions defined in `command.js`. These functions interact with utility files like `connector.js` and include necessary assertions to support various connector scenarios.
## Additional Resources
+
For more information on using Cypress and writing effective tests, refer to the official Cypress documentation: [Cypress Documentation](https://docs.cypress.io/)
|
docs
|
Update Cypress README Documentation (#4380)
|
409913fd75076e4ee1dac1e4dc5b2f164528bc23
|
2023-10-04 18:49:34
|
Narayan Bhat
|
refactor(webhook): add a function to retrieve payment_id (#2447)
| false
|
diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs
index a1cafee1f8d..252e3110d6a 100644
--- a/crates/api_models/src/webhooks.rs
+++ b/crates/api_models/src/webhooks.rs
@@ -59,6 +59,17 @@ pub enum WebhookResponseTracker {
NoEffect,
}
+impl WebhookResponseTracker {
+ pub fn get_payment_id(&self) -> Option<String> {
+ match self {
+ Self::Payment { payment_id, .. }
+ | Self::Refund { payment_id, .. }
+ | Self::Dispute { payment_id, .. } => Some(payment_id.to_string()),
+ Self::NoEffect => None,
+ }
+ }
+}
+
impl From<IncomingWebhookEvent> for WebhookFlow {
fn from(evt: IncomingWebhookEvent) -> Self {
match evt {
|
refactor
|
add a function to retrieve payment_id (#2447)
|
9f2832f60078b98e6faae34b05b63d2dab6b7969
|
2023-06-05 18:18:00
|
Sanchith Hegde
|
refactor(router): remove `pii-encryption-script` feature and use of timestamps for decryption (#1350)
| false
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 28113bfb3cd..645908ee8d9 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -101,7 +101,6 @@ admin_api_key = "test_admin" # admin API key for admin authentication. Only
kms_encrypted_admin_api_key = "" # Base64-encoded (KMS encrypted) ciphertext of the admin_api_key. Only applicable when KMS is enabled.
jwt_secret = "secret" # JWT secret used for user authentication. Only applicable when KMS is disabled.
kms_encrypted_jwt_secret = "" # Base64-encoded (KMS encrypted) ciphertext of the jwt_secret. Only applicable when KMS is enabled.
-migration_encryption_timestamp = 0 # Timestamp to decide which entries are not encrypted in the database.
# Locker settings contain details for accessing a card locker, a
# PCI Compliant storage entity which stores payment method information
diff --git a/config/development.toml b/config/development.toml
index 48a476231cb..1921e0791ef 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -32,7 +32,6 @@ connection_timeout = 10
[secrets]
admin_api_key = "test_admin"
-migration_encryption_timestamp = 1682425530
master_enc_key = "73ad7bbbbc640c845a150f67d058b279849370cd2c1f3c67c4dd6c869213e13a"
[locker]
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 04838e91137..254503f57d4 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -16,8 +16,8 @@ kms = ["external_services/kms","dep:aws-config"]
email = ["external_services/email","dep:aws-config"]
basilisk = ["kms"]
stripe = ["dep:serde_qs"]
-sandbox = ["kms", "stripe", "basilisk", "s3","email"]
-production = ["kms", "stripe", "basilisk", "s3","pii-encryption-script","email"]
+sandbox = ["kms", "stripe", "basilisk", "s3", "email"]
+production = ["kms", "stripe", "basilisk", "s3", "email"]
olap = []
oltp = []
kv_store = []
@@ -25,7 +25,6 @@ accounts_cache = []
openapi = ["olap", "oltp"]
vergen = ["router_env/vergen"]
multiple_mca = ["api_models/multiple_mca"]
-pii-encryption-script = []
dummy_connector = ["api_models/dummy_connector"]
external_access_dc = ["dummy_connector"]
detailed_errors = ["api_models/detailed_errors", "error-stack/serde"]
diff --git a/crates/router/src/bin/router.rs b/crates/router/src/bin/router.rs
index de786275ba5..02ff2c241ef 100644
--- a/crates/router/src/bin/router.rs
+++ b/crates/router/src/bin/router.rs
@@ -36,24 +36,6 @@ async fn main() -> ApplicationResult<()> {
let _guard = logger::setup(&conf.log);
- #[cfg(feature = "pii-encryption-script")]
- {
- let store =
- router::services::Store::new(&conf, false, tokio::sync::oneshot::channel().0).await;
-
- // ^-------- KMS decryption of the master key is a fallible and the server will panic in
- // the above mentioned line
-
- router::scripts::pii_encryption::test_2_step_encryption(&store).await;
-
- #[allow(clippy::expect_used)]
- router::scripts::pii_encryption::encrypt_merchant_account_fields(&store)
- .await
- .expect("Failed while encrypting merchant account");
-
- crate::logger::error!("Done with everything");
- }
-
logger::info!("Application started [{:?}] [{:?}]", conf.server, conf.log);
#[allow(clippy::expect_used)]
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index 3a3980aac6d..fc2cec05465 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -40,7 +40,6 @@ impl Default for super::settings::Secrets {
kms_encrypted_jwt_secret: "".into(),
#[cfg(feature = "kms")]
kms_encrypted_admin_api_key: "".into(),
- migration_encryption_timestamp: 0,
}
}
}
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 3b39124e127..4d4f6d66d7a 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -37,8 +37,6 @@ pub enum Subcommand {
#[cfg(feature = "openapi")]
/// Generate the OpenAPI specification file from code.
GenerateOpenapiSpec,
- #[cfg(feature = "pii-encryption-script")]
- EncryptDatabase,
}
#[cfg(feature = "kms")]
@@ -288,8 +286,6 @@ pub struct Secrets {
pub kms_encrypted_jwt_secret: String,
#[cfg(feature = "kms")]
pub kms_encrypted_admin_api_key: String,
-
- pub migration_encryption_timestamp: i64,
}
#[derive(Debug, Deserialize, Clone)]
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index 5fc35af9f25..508c4045ab0 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -239,7 +239,7 @@ pub async fn delete_customer(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting key for encryption")?;
let redacted_encrypted_value: Encryptable<masking::Secret<_>> =
- Encryptable::encrypt(REDACTED.to_string().into(), &key, GcmAes256 {})
+ Encryptable::encrypt(REDACTED.to_string().into(), &key, GcmAes256)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
@@ -278,7 +278,7 @@ pub async fn delete_customer(
let updated_customer = storage::CustomerUpdate::Update {
name: Some(redacted_encrypted_value.clone()),
email: Some(
- Encryptable::encrypt(REDACTED.to_string().into(), &key, GcmAes256 {})
+ Encryptable::encrypt(REDACTED.to_string().into(), &key, GcmAes256)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?,
),
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index 317e8d34fac..d5f05bfb73a 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -74,16 +74,12 @@ pub trait StorageInterface:
pub trait MasterKeyInterface {
fn get_master_key(&self) -> &[u8];
- fn get_migration_timestamp(&self) -> i64;
}
impl MasterKeyInterface for Store {
fn get_master_key(&self) -> &[u8] {
&self.master_key
}
- fn get_migration_timestamp(&self) -> i64 {
- self.migration_timestamp
- }
}
/// Default dummy key for MockDb
@@ -94,10 +90,6 @@ impl MasterKeyInterface for MockDb {
25, 26, 27, 28, 29, 30, 31, 32,
]
}
-
- fn get_migration_timestamp(&self) -> i64 {
- 0
- }
}
#[async_trait::async_trait]
diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs
index 1e94911bed0..8df8b033305 100644
--- a/crates/router/src/db/address.rs
+++ b/crates/router/src/db/address.rs
@@ -2,7 +2,7 @@ use common_utils::ext_traits::AsyncExt;
use error_stack::{IntoReport, ResultExt};
use storage_models::address::AddressUpdateInternal;
-use super::{MasterKeyInterface, MockDb, Store};
+use super::{MockDb, Store};
use crate::{
connection,
core::errors::{self, CustomResult},
@@ -58,7 +58,7 @@ impl AddressInterface for Store {
.async_and_then(|address| async {
let merchant_id = address.merchant_id.clone();
address
- .convert(self, &merchant_id, self.get_migration_timestamp())
+ .convert(self, &merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
})
@@ -78,7 +78,7 @@ impl AddressInterface for Store {
.async_and_then(|address| async {
let merchant_id = address.merchant_id.clone();
address
- .convert(self, &merchant_id, self.get_migration_timestamp())
+ .convert(self, &merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
})
@@ -101,7 +101,7 @@ impl AddressInterface for Store {
.async_and_then(|address| async {
let merchant_id = address.merchant_id.clone();
address
- .convert(self, &merchant_id, self.get_migration_timestamp())
+ .convert(self, &merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
})
@@ -130,7 +130,7 @@ impl AddressInterface for Store {
let merchant_id = address.merchant_id.clone();
output.push(
address
- .convert(self, &merchant_id, self.get_migration_timestamp())
+ .convert(self, &merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)?,
)
@@ -158,7 +158,7 @@ impl AddressInterface for MockDb {
let merchant_id = address.merchant_id.clone();
address
.clone()
- .convert(self, &merchant_id, self.get_migration_timestamp())
+ .convert(self, &merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
}
@@ -190,7 +190,7 @@ impl AddressInterface for MockDb {
Some(address_updated) => {
let merchant_id = address_updated.merchant_id.clone();
address_updated
- .convert(self, &merchant_id, self.get_migration_timestamp())
+ .convert(self, &merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
}
@@ -217,7 +217,7 @@ impl AddressInterface for MockDb {
addresses.push(address.clone());
address
- .convert(self, &merchant_id, self.get_migration_timestamp())
+ .convert(self, &merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
}
@@ -244,7 +244,7 @@ impl AddressInterface for MockDb {
}) {
Some(address) => {
let address: domain::Address = address
- .convert(self, merchant_id, self.get_migration_timestamp())
+ .convert(self, merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)?;
Ok(vec![address])
diff --git a/crates/router/src/db/customers.rs b/crates/router/src/db/customers.rs
index fe8610a6430..130c64508d1 100644
--- a/crates/router/src/db/customers.rs
+++ b/crates/router/src/db/customers.rs
@@ -2,7 +2,7 @@ use common_utils::ext_traits::AsyncExt;
use error_stack::{IntoReport, ResultExt};
use masking::PeekInterface;
-use super::{MasterKeyInterface, MockDb, Store};
+use super::{MockDb, Store};
use crate::{
connection,
core::{
@@ -72,7 +72,7 @@ impl CustomerInterface for Store {
.map_err(Into::into)
.into_report()?
.async_map(|c| async {
- c.convert(self, merchant_id, self.get_migration_timestamp())
+ c.convert(self, merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
})
@@ -108,7 +108,7 @@ impl CustomerInterface for Store {
.into_report()
.async_and_then(|c| async {
let merchant_id = c.merchant_id.clone();
- c.convert(self, &merchant_id, self.get_migration_timestamp())
+ c.convert(self, &merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
})
@@ -128,7 +128,7 @@ impl CustomerInterface for Store {
.into_report()
.async_and_then(|c| async {
let merchant_id = c.merchant_id.clone();
- c.convert(self, &merchant_id, self.get_migration_timestamp())
+ c.convert(self, &merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
})
@@ -156,7 +156,7 @@ impl CustomerInterface for Store {
.into_report()
.async_and_then(|c| async {
let merchant_id = c.merchant_id.clone();
- c.convert(self, &merchant_id, self.get_migration_timestamp())
+ c.convert(self, &merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
})
@@ -194,7 +194,7 @@ impl CustomerInterface for MockDb {
customer
.async_map(|c| async {
let merchant_id = c.merchant_id.clone();
- c.convert(self, &merchant_id, self.get_migration_timestamp())
+ c.convert(self, &merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
})
@@ -236,7 +236,7 @@ impl CustomerInterface for MockDb {
customers.push(customer.clone());
customer
- .convert(self, &merchant_id, self.get_migration_timestamp())
+ .convert(self, &merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
}
diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs
index 7200ec61b6f..b7cade2f2bb 100644
--- a/crates/router/src/db/merchant_account.rs
+++ b/crates/router/src/db/merchant_account.rs
@@ -7,7 +7,6 @@ use crate::cache::{self, ACCOUNTS_CACHE};
use crate::{
connection,
core::errors::{self, CustomResult},
- db::MasterKeyInterface,
types::{
domain::{
self,
@@ -72,7 +71,7 @@ impl MerchantAccountInterface for Store {
.await
.map_err(Into::into)
.into_report()?
- .convert(self, &merchant_id, self.get_migration_timestamp())
+ .convert(self, &merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
}
@@ -93,7 +92,7 @@ impl MerchantAccountInterface for Store {
{
fetch_func()
.await?
- .convert(self, merchant_id, self.get_migration_timestamp())
+ .convert(self, merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
}
@@ -102,7 +101,7 @@ impl MerchantAccountInterface for Store {
{
super::cache::get_or_populate_in_memory(self, merchant_id, fetch_func, &ACCOUNTS_CACHE)
.await?
- .convert(self, merchant_id, self.get_migration_timestamp())
+ .convert(self, merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
}
@@ -124,7 +123,7 @@ impl MerchantAccountInterface for Store {
.map_err(Into::into)
.into_report()
.async_and_then(|item| async {
- item.convert(self, &_merchant_id, self.get_migration_timestamp())
+ item.convert(self, &_merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
})
@@ -163,7 +162,7 @@ impl MerchantAccountInterface for Store {
.map_err(Into::into)
.into_report()
.async_and_then(|item| async {
- item.convert(self, merchant_id, self.get_migration_timestamp())
+ item.convert(self, merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
})
@@ -197,7 +196,7 @@ impl MerchantAccountInterface for Store {
.into_report()
.async_and_then(|item| async {
let merchant_id = item.merchant_id.clone();
- item.convert(self, &merchant_id, self.get_migration_timestamp())
+ item.convert(self, &merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
})
@@ -248,7 +247,7 @@ impl MerchantAccountInterface for MockDb {
accounts.push(account.clone());
account
- .convert(self, &merchant_id, self.get_migration_timestamp())
+ .convert(self, &merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
}
@@ -264,7 +263,7 @@ impl MerchantAccountInterface for MockDb {
.find(|account| account.merchant_id == merchant_id)
.cloned()
.async_map(|a| async {
- a.convert(self, merchant_id, self.get_migration_timestamp())
+ a.convert(self, merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
})
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index 8bc484f4e56..997cc130c7d 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -7,7 +7,6 @@ use super::{MockDb, Store};
use crate::{
connection,
core::errors::{self, CustomResult},
- db::MasterKeyInterface,
services::logger,
types::{
self,
@@ -166,7 +165,7 @@ impl MerchantConnectorAccountInterface for Store {
.map_err(Into::into)
.into_report()
.async_and_then(|item| async {
- item.convert(self, merchant_id, self.get_migration_timestamp())
+ item.convert(self, merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
})
@@ -194,7 +193,7 @@ impl MerchantConnectorAccountInterface for Store {
{
find_call()
.await?
- .convert(self, merchant_id, self.get_migration_timestamp())
+ .convert(self, merchant_id)
.await
.change_context(errors::StorageError::DeserializationFailed)
}
@@ -203,7 +202,7 @@ impl MerchantConnectorAccountInterface for Store {
{
cache::get_or_populate_redis(self, merchant_connector_id, find_call)
.await?
- .convert(self, merchant_id, self.get_migration_timestamp())
+ .convert(self, merchant_id)
.await
.change_context(errors::StorageError::DeserializationFailed)
}
@@ -223,7 +222,7 @@ impl MerchantConnectorAccountInterface for Store {
.into_report()
.async_and_then(|item| async {
let merchant_id = item.merchant_id.clone();
- item.convert(self, &merchant_id, self.get_migration_timestamp())
+ item.convert(self, &merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
})
@@ -244,7 +243,7 @@ impl MerchantConnectorAccountInterface for Store {
let mut output = Vec::with_capacity(items.len());
for item in items.into_iter() {
output.push(
- item.convert(self, merchant_id, self.get_migration_timestamp())
+ item.convert(self, merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)?,
)
@@ -271,7 +270,7 @@ impl MerchantConnectorAccountInterface for Store {
.into_report()
.async_and_then(|item| async {
let merchant_id = item.merchant_id.clone();
- item.convert(self, &merchant_id, self.get_migration_timestamp())
+ item.convert(self, &merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
})
@@ -324,7 +323,7 @@ impl MerchantConnectorAccountInterface for MockDb {
.cloned()
.unwrap();
account
- .convert(self, merchant_id, self.get_migration_timestamp())
+ .convert(self, merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
}
@@ -367,7 +366,7 @@ impl MerchantConnectorAccountInterface for MockDb {
};
accounts.push(account.clone());
account
- .convert(self, &merchant_id, self.get_migration_timestamp())
+ .convert(self, &merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
}
diff --git a/crates/router/src/db/merchant_key_store.rs b/crates/router/src/db/merchant_key_store.rs
index 3e78e8b2b84..b4637af8c0c 100644
--- a/crates/router/src/db/merchant_key_store.rs
+++ b/crates/router/src/db/merchant_key_store.rs
@@ -1,6 +1,5 @@
use error_stack::{IntoReport, ResultExt};
-use super::MasterKeyInterface;
use crate::{
connection,
core::errors::{self, CustomResult},
@@ -41,7 +40,7 @@ impl MerchantKeyStoreInterface for Store {
.await
.map_err(Into::into)
.into_report()?
- .convert(self, &merchant_id, self.get_migration_timestamp())
+ .convert(self, &merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
}
@@ -57,7 +56,7 @@ impl MerchantKeyStoreInterface for Store {
.await
.map_err(Into::into)
.into_report()?
- .convert(self, merchant_id, self.get_migration_timestamp())
+ .convert(self, merchant_id)
.await
.change_context(errors::StorageError::DecryptionError)
}
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index 67234af661e..380448bab7b 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -19,7 +19,6 @@ pub mod scheduler;
pub mod middleware;
#[cfg(feature = "openapi")]
pub mod openapi;
-pub mod scripts;
pub mod services;
pub mod types;
pub mod utils;
diff --git a/crates/router/src/scripts.rs b/crates/router/src/scripts.rs
deleted file mode 100644
index dc9f789c164..00000000000
--- a/crates/router/src/scripts.rs
+++ /dev/null
@@ -1,2 +0,0 @@
-#[cfg(feature = "pii-encryption-script")]
-pub mod pii_encryption;
diff --git a/crates/router/src/scripts/pii_encryption.rs b/crates/router/src/scripts/pii_encryption.rs
deleted file mode 100644
index ce71edffb06..00000000000
--- a/crates/router/src/scripts/pii_encryption.rs
+++ /dev/null
@@ -1,421 +0,0 @@
-use async_bb8_diesel::AsyncConnection;
-use common_utils::errors::CustomResult;
-use diesel::{associations::HasTable, ExpressionMethods, Table};
-use error_stack::{IntoReport, ResultExt};
-use storage_models::{
- address::Address,
- customers::Customer,
- merchant_account::MerchantAccount,
- merchant_connector_account::MerchantConnectorAccount,
- query::generics::generic_filter,
- schema::{
- address::dsl as ad_dsl, customers::dsl as cu_dsl, merchant_account::dsl as ma_dsl,
- merchant_connector_account::dsl as mca_dsl,
- },
-};
-
-use crate::{
- connection,
- core::errors,
- db::{
- merchant_account::MerchantAccountInterface, merchant_key_store::MerchantKeyStoreInterface,
- MasterKeyInterface,
- },
- services::{self, Store},
- types::{
- domain::{
- self,
- behaviour::{Conversion, ReverseConversion},
- merchant_key_store, types,
- },
- storage,
- },
-};
-
-pub async fn create_merchant_key_store(
- state: &Store,
- merchant_id: &str,
- key: Vec<u8>,
-) -> CustomResult<(), errors::ApiErrorResponse> {
- crate::logger::info!("Trying to create MerchantKeyStore for {}", merchant_id);
- let master_key = state.get_master_key();
- let key_store = merchant_key_store::MerchantKeyStore {
- merchant_id: merchant_id.to_string(),
- key: types::encrypt(key.into(), master_key)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to decrypt data from key store")?,
- created_at: common_utils::date_time::now(),
- };
-
- match state.insert_merchant_key_store(key_store).await {
- Ok(_) => Ok(()),
- Err(err) => match err.current_context() {
- errors::StorageError::DatabaseError(f) => match f.current_context() {
- storage_models::errors::DatabaseError::UniqueViolation => Ok(()),
- _ => Err(err.change_context(errors::ApiErrorResponse::InternalServerError)),
- },
- _ => Err(err.change_context(errors::ApiErrorResponse::InternalServerError)),
- },
- }
-}
-
-pub async fn encrypt_merchant_account_fields(
- state: &Store,
-) -> CustomResult<(), errors::ApiErrorResponse> {
- let conn = connection::pg_connection_write(state)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
- let merchants: Vec<MerchantAccount> = generic_filter::<
- <MerchantAccount as HasTable>::Table,
- _,
- <<MerchantAccount as HasTable>::Table as Table>::PrimaryKey,
- _,
- >(
- &conn,
- ma_dsl::merchant_id.eq(ma_dsl::merchant_id),
- None,
- None,
- None,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
-
- for mer in merchants.iter() {
- let key = services::generate_aes256_key()
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
-
- create_merchant_key_store(state, &mer.merchant_id, key.to_vec()).await?;
- }
- let mut domain_merchants = Vec::with_capacity(merchants.len());
- for mf in merchants.into_iter() {
- let merchant_id = mf.merchant_id.clone();
- let domain_merchant: domain::MerchantAccount = mf
- .convert(state, &merchant_id, state.get_migration_timestamp())
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
- domain_merchants.push(domain_merchant);
- }
- for m in domain_merchants {
- let merchant_id = m.merchant_id.clone();
- let updated_merchant_account = storage::MerchantAccountUpdate::Update {
- merchant_name: m.merchant_name.clone(),
- merchant_details: m.merchant_details.clone(),
- return_url: None,
- webhook_details: None,
- sub_merchants_enabled: None,
- parent_merchant_id: None,
- primary_business_details: None,
- enable_payment_response_hash: None,
- payment_response_hash_key: None,
- redirect_to_merchant_with_http_post: None,
- routing_algorithm: None,
- locker_id: None,
- publishable_key: None,
- metadata: None,
- intent_fulfillment_time: None,
- frm_routing_algorithm: None,
- };
- crate::logger::warn!("Started for {}", merchant_id);
- state
- .update_merchant(m, updated_merchant_account)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
- encrypt_merchant_connector_account_fields(state, &merchant_id).await?;
- encrypt_customer_fields(state, &merchant_id).await?;
- encrypt_address_fields(state, &merchant_id).await?;
- crate::logger::warn!("Done for {}", merchant_id);
- }
-
- Ok(())
-}
-
-pub async fn encrypt_merchant_connector_account_fields(
- state: &Store,
- merchant_id: &str,
-) -> CustomResult<(), errors::ApiErrorResponse> {
- crate::logger::warn!("Updating MerchantConnectorAccount for {}", merchant_id);
- let conn = connection::pg_connection_write(state)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
-
- let merchants: Vec<MerchantConnectorAccount> = generic_filter::<
- <MerchantConnectorAccount as HasTable>::Table,
- _,
- <<MerchantConnectorAccount as HasTable>::Table as Table>::PrimaryKey,
- _,
- >(
- &conn,
- mca_dsl::merchant_id.eq(merchant_id.to_string()),
- None,
- None,
- None,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
-
- let mut domain_merchants = Vec::with_capacity(merchants.len());
- for m in merchants.into_iter() {
- let merchant_id = m.merchant_id.clone();
- let domain_merchant: domain::MerchantConnectorAccount = m
- .convert(state, &merchant_id, state.get_migration_timestamp())
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
- domain_merchants.push(domain_merchant);
- }
-
- conn.transaction_async::<(), async_bb8_diesel::ConnectionError, _, _>(|conn| async move {
- for m in domain_merchants {
- let updated_merchant_connector_account =
- storage::MerchantConnectorAccountUpdate::Update {
- merchant_id: None,
- connector_name: None,
- connector_type: None,
- frm_configs: None,
- test_mode: None,
- disabled: None,
- merchant_connector_id: None,
- payment_methods_enabled: None,
- metadata: None,
- connector_account_details: Some(m.connector_account_details.clone()),
- };
-
- Conversion::convert(m)
- .await
- .map_err(|_| {
- async_bb8_diesel::ConnectionError::Query(
- diesel::result::Error::QueryBuilderError(
- "Error while decrypting MerchantConnectorAccount".into(),
- ),
- )
- })?
- .update(&conn, updated_merchant_connector_account.into())
- .await
- .map_err(|_| {
- async_bb8_diesel::ConnectionError::Query(
- diesel::result::Error::QueryBuilderError(
- "Error while updating MerchantConnectorAccount".into(),
- ),
- )
- })?;
- }
- Ok(())
- })
- .await
- .into_report()
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
-
- crate::logger::warn!(
- "Done: Updating MerchantConnectorAccount for {}",
- merchant_id
- );
- Ok(())
-}
-
-pub async fn encrypt_customer_fields(
- state: &Store,
- merchant_id: &str,
-) -> CustomResult<(), errors::ApiErrorResponse> {
- crate::logger::warn!("Updating Customer for {}", merchant_id);
- let conn = connection::pg_connection_write(state)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
-
- let merchants: Vec<Customer> = generic_filter::<
- <Customer as HasTable>::Table,
- _,
- <<Customer as HasTable>::Table as Table>::PrimaryKey,
- _,
- >(
- &conn,
- cu_dsl::merchant_id.eq(merchant_id.to_string()),
- None,
- None,
- None,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
-
- let mut domain_merchants = Vec::with_capacity(merchants.len());
- for m in merchants.into_iter() {
- let merchant_id = m.merchant_id.clone();
- let domain_merchant: domain::Customer = m
- .convert(state, &merchant_id, state.get_migration_timestamp())
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
- domain_merchants.push(domain_merchant);
- }
-
- conn.transaction_async::<(), async_bb8_diesel::ConnectionError, _, _>(|conn| async move {
- for m in domain_merchants {
- let update_customer = storage::CustomerUpdate::Update {
- name: m.name.clone(),
- email: m.email.clone(),
- phone: m.phone.clone(),
- description: None,
- metadata: None,
- phone_country_code: None,
- connector_customer: None,
- };
-
- Customer::update_by_customer_id_merchant_id(
- &conn,
- m.customer_id.to_string(),
- m.merchant_id.to_string(),
- update_customer.into(),
- )
- .await
- .map_err(|_| {
- async_bb8_diesel::ConnectionError::Query(diesel::result::Error::QueryBuilderError(
- "Error while updating Customer".into(),
- ))
- })?;
- }
-
- Ok(())
- })
- .await
- .into_report()
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
-
- crate::logger::warn!("Done: Updating Customer for {}", merchant_id);
- Ok(())
-}
-
-pub async fn encrypt_address_fields(
- state: &Store,
- merchant_id: &str,
-) -> CustomResult<(), errors::ApiErrorResponse> {
- crate::logger::warn!("Updating Address for {}", merchant_id);
- let conn = connection::pg_connection_write(state)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
-
- let merchants: Vec<Address> = generic_filter::<
- <Address as HasTable>::Table,
- _,
- <<Address as HasTable>::Table as Table>::PrimaryKey,
- _,
- >(
- &conn,
- ad_dsl::merchant_id.eq(merchant_id.to_string()),
- None,
- None,
- None,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
-
- let mut domain_merchants = Vec::with_capacity(merchants.len());
- for m in merchants.into_iter() {
- let merchant_id = m.merchant_id.clone();
- let domain_merchant: domain::Address = m
- .convert(state, &merchant_id, state.get_migration_timestamp())
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
- domain_merchants.push(domain_merchant);
- }
-
- conn.transaction_async::<(), async_bb8_diesel::ConnectionError, _, _>(|conn| async move {
- for m in domain_merchants {
- let update_address = storage::address::AddressUpdate::Update {
- line1: m.line1.clone(),
- line2: m.line2.clone(),
- line3: m.line3.clone(),
- state: m.state.clone(),
- zip: m.zip.clone(),
- first_name: m.first_name.clone(),
- last_name: m.last_name.clone(),
- phone_number: m.phone_number.clone(),
- city: None,
- country: None,
- country_code: None,
- };
-
- Address::update_by_address_id(&conn, m.address_id, update_address.into())
- .await
- .map_err(|_| {
- async_bb8_diesel::ConnectionError::Query(
- diesel::result::Error::QueryBuilderError(
- "Error while updating Address".into(),
- ),
- )
- })?;
- }
- Ok(())
- })
- .await
- .into_report()
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
-
- crate::logger::warn!("Done: Updating Address for {}", merchant_id);
- Ok(())
-}
-
-///
-/// # Panics
-///
-/// The functions runs at the start of the migration and tests, all the functional parts of
-/// encryption.
-///
-#[allow(clippy::unwrap_used)]
-pub async fn test_2_step_encryption(store: &Store) {
- use masking::ExposeInterface;
- let (encrypted_merchant_key, master_key) = {
- let master_key = store.get_master_key();
- let merchant_key: Vec<u8> = services::generate_aes256_key().unwrap().into();
- let encrypted_merchant_key =
- types::encrypt::<_, crate::pii::WithType>(merchant_key.into(), master_key)
- .await
- .unwrap()
- .into_encrypted();
- let encrypted_merchant_key =
- storage_models::encryption::Encryption::new(encrypted_merchant_key);
- (encrypted_merchant_key, master_key)
- };
-
- let dummy_data = "Hello, World!".to_string();
- let encrypted_dummy_data = storage_models::encryption::Encryption::new(
- types::encrypt::<_, crate::pii::WithType>(
- masking::Secret::new(dummy_data.clone()),
- &types::decrypt::<Vec<u8>, crate::pii::WithType>(
- Some(encrypted_merchant_key.clone()),
- master_key,
- 0,
- 0,
- )
- .await
- .unwrap()
- .unwrap()
- .into_inner()
- .expose(),
- )
- .await
- .unwrap()
- .into_encrypted(),
- );
-
- let dummy_data_returned = types::decrypt::<String, crate::pii::WithType>(
- Some(encrypted_dummy_data),
- &types::decrypt::<Vec<u8>, crate::pii::WithType>(
- Some(encrypted_merchant_key),
- master_key,
- 0,
- 0,
- )
- .await
- .unwrap()
- .unwrap()
- .into_inner()
- .expose(),
- 0,
- 0,
- )
- .await
- .unwrap()
- .unwrap()
- .into_inner()
- .expose();
-
- assert!(dummy_data_returned == dummy_data)
-}
diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs
index 1e1bd40db63..957aa026dcc 100644
--- a/crates/router/src/services.rs
+++ b/crates/router/src/services.rs
@@ -119,7 +119,6 @@ pub struct Store {
#[cfg(feature = "kv_store")]
pub(crate) config: StoreConfig,
pub master_key: Vec<u8>,
- pub migration_timestamp: i64,
}
#[cfg(feature = "kv_store")]
@@ -183,7 +182,6 @@ impl Store {
drainer_num_partitions: config.drainer.num_partitions,
},
master_key: master_enc_key,
- migration_timestamp: config.secrets.migration_encryption_timestamp,
}
}
diff --git a/crates/router/src/types/domain/address.rs b/crates/router/src/types/domain/address.rs
index ed3851ea8fb..5ecbafda5d2 100644
--- a/crates/router/src/types/domain/address.rs
+++ b/crates/router/src/types/domain/address.rs
@@ -74,7 +74,6 @@ impl behaviour::Conversion for Address {
other: Self::DstType,
db: &dyn StorageInterface,
merchant_id: &str,
- migration_timestamp: i64,
) -> CustomResult<Self, ValidationError> {
let key = types::get_merchant_enc_key(db, merchant_id)
.await
@@ -83,9 +82,7 @@ impl behaviour::Conversion for Address {
})?;
async {
- let modified_at = other.modified_at.assume_utc().unix_timestamp();
- let inner_decrypt =
- |inner| types::decrypt(inner, &key, modified_at, migration_timestamp);
+ let inner_decrypt = |inner| types::decrypt(inner, &key);
Ok(Self {
id: Some(other.id),
address_id: other.address_id,
diff --git a/crates/router/src/types/domain/behaviour.rs b/crates/router/src/types/domain/behaviour.rs
index 5046622f6d7..2f95fe1611c 100644
--- a/crates/router/src/types/domain/behaviour.rs
+++ b/crates/router/src/types/domain/behaviour.rs
@@ -13,7 +13,6 @@ pub trait Conversion {
item: Self::DstType,
db: &dyn StorageInterface,
merchant_id: &str,
- migration_timestamp: i64,
) -> CustomResult<Self, ValidationError>
where
Self: Sized;
@@ -27,7 +26,6 @@ pub trait ReverseConversion<SrcType: Conversion> {
self,
db: &dyn StorageInterface,
merchant_id: &str,
- migration_timestamp: i64,
) -> CustomResult<SrcType, ValidationError>;
}
@@ -37,8 +35,7 @@ impl<T: Send, U: Conversion<DstType = T>> ReverseConversion<U> for T {
self,
db: &dyn StorageInterface,
merchant_id: &str,
- migration_timestamp: i64,
) -> CustomResult<U, ValidationError> {
- U::convert_back(self, db, merchant_id, migration_timestamp).await
+ U::convert_back(self, db, merchant_id).await
}
}
diff --git a/crates/router/src/types/domain/customer.rs b/crates/router/src/types/domain/customer.rs
index 060a15928d0..03c5c535c21 100644
--- a/crates/router/src/types/domain/customer.rs
+++ b/crates/router/src/types/domain/customer.rs
@@ -55,7 +55,6 @@ impl super::behaviour::Conversion for Customer {
item: Self::DstType,
db: &dyn StorageInterface,
merchant_id: &str,
- migration_timestamp: i64,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
@@ -66,12 +65,8 @@ impl super::behaviour::Conversion for Customer {
message: "Failed while getting key from key store".to_string(),
})?;
async {
- let modified_at = item.modified_at.assume_utc().unix_timestamp();
-
- let inner_decrypt =
- |inner| types::decrypt(inner, &key, modified_at, migration_timestamp);
- let inner_decrypt_email =
- |inner| types::decrypt(inner, &key, modified_at, migration_timestamp);
+ let inner_decrypt = |inner| types::decrypt(inner, &key);
+ let inner_decrypt_email = |inner| types::decrypt(inner, &key);
Ok(Self {
id: Some(item.id),
customer_id: item.customer_id,
diff --git a/crates/router/src/types/domain/merchant_account.rs b/crates/router/src/types/domain/merchant_account.rs
index 10106b1afe0..83ef5237673 100644
--- a/crates/router/src/types/domain/merchant_account.rs
+++ b/crates/router/src/types/domain/merchant_account.rs
@@ -149,7 +149,6 @@ impl super::behaviour::Conversion for MerchantAccount {
item: Self::DstType,
db: &dyn StorageInterface,
merchant_id: &str,
- migration_timestamp: i64,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
@@ -160,7 +159,6 @@ impl super::behaviour::Conversion for MerchantAccount {
message: "Failed while getting key from key store".to_string(),
})?;
async {
- let modified_at = item.modified_at.assume_utc().unix_timestamp();
Ok(Self {
id: Some(item.id),
merchant_id: item.merchant_id,
@@ -170,15 +168,11 @@ impl super::behaviour::Conversion for MerchantAccount {
redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
merchant_name: item
.merchant_name
- .async_lift(|inner| {
- types::decrypt(inner, &key, modified_at, migration_timestamp)
- })
+ .async_lift(|inner| types::decrypt(inner, &key))
.await?,
merchant_details: item
.merchant_details
- .async_lift(|inner| {
- types::decrypt(inner, &key, modified_at, migration_timestamp)
- })
+ .async_lift(|inner| types::decrypt(inner, &key))
.await?,
webhook_details: item.webhook_details,
sub_merchants_enabled: item.sub_merchants_enabled,
diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs
index a0a1a8a3e1a..9e97b58795c 100644
--- a/crates/router/src/types/domain/merchant_connector_account.rs
+++ b/crates/router/src/types/domain/merchant_connector_account.rs
@@ -89,14 +89,12 @@ impl behaviour::Conversion for MerchantConnectorAccount {
other: Self::DstType,
db: &dyn StorageInterface,
merchant_id: &str,
- migration_timestamp: i64,
) -> CustomResult<Self, ValidationError> {
let key = types::get_merchant_enc_key(db, merchant_id)
.await
.change_context(ValidationError::InvalidValue {
message: "Error while getting key from keystore".to_string(),
})?;
- let modified_at = other.modified_at.assume_utc().unix_timestamp();
Ok(Self {
id: Some(other.id),
@@ -105,9 +103,7 @@ impl behaviour::Conversion for MerchantConnectorAccount {
connector_account_details: Encryptable::decrypt(
other.connector_account_details,
&key,
- GcmAes256 {},
- modified_at,
- migration_timestamp,
+ GcmAes256,
)
.await
.change_context(ValidationError::InvalidValue {
diff --git a/crates/router/src/types/domain/merchant_key_store.rs b/crates/router/src/types/domain/merchant_key_store.rs
index efe4fb8403a..6917261e97b 100644
--- a/crates/router/src/types/domain/merchant_key_store.rs
+++ b/crates/router/src/types/domain/merchant_key_store.rs
@@ -36,14 +36,13 @@ impl super::behaviour::Conversion for MerchantKeyStore {
item: Self::DstType,
db: &dyn StorageInterface,
_merchant_id: &str,
- migration_timestamp: i64,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let key = &db.get_master_key();
Ok(Self {
- key: Encryptable::decrypt(item.key, key, GcmAes256 {}, i64::MAX, migration_timestamp)
+ key: Encryptable::decrypt(item.key, key, GcmAes256)
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
diff --git a/crates/router/src/types/domain/types.rs b/crates/router/src/types/domain/types.rs
index aa6b63af069..d159b631648 100644
--- a/crates/router/src/types/domain/types.rs
+++ b/crates/router/src/types/domain/types.rs
@@ -23,12 +23,11 @@ pub trait TypeEncryption<
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError>;
+
async fn decrypt(
encrypted_data: Encryption,
key: &[u8],
crypt_algo: V,
- timestamp: i64,
- migration_timestamp: i64,
) -> CustomResult<Self, errors::CryptoError>;
}
@@ -54,22 +53,9 @@ impl<
encrypted_data: Encryption,
key: &[u8],
crypt_algo: V,
- timestamp: i64,
- migration_timestamp: i64,
) -> CustomResult<Self, errors::CryptoError> {
let encrypted = encrypted_data.into_inner();
-
- let (data, encrypted) = if timestamp < migration_timestamp {
- (
- encrypted.clone(),
- crypt_algo.encode_message(key, &encrypted)?,
- )
- } else {
- (
- crypt_algo.decode_message(key, encrypted.clone())?,
- encrypted,
- )
- };
+ let data = crypt_algo.decode_message(key, encrypted.clone())?;
let value: String = std::str::from_utf8(&data)
.into_report()
@@ -106,21 +92,9 @@ impl<
encrypted_data: Encryption,
key: &[u8],
crypt_algo: V,
- timestamp: i64,
- migration_timestamp: i64,
) -> CustomResult<Self, errors::CryptoError> {
let encrypted = encrypted_data.into_inner();
- let (data, encrypted) = if timestamp < migration_timestamp {
- (
- encrypted.clone(),
- crypt_algo.encode_message(key, &encrypted)?,
- )
- } else {
- (
- crypt_algo.decode_message(key, encrypted.clone())?,
- encrypted,
- )
- };
+ let data = crypt_algo.decode_message(key, encrypted.clone())?;
let value: serde_json::Value = serde_json::from_slice(&data)
.into_report()
@@ -152,22 +126,10 @@ impl<
encrypted_data: Encryption,
key: &[u8],
crypt_algo: V,
- timestamp: i64,
- migration_timestamp: i64,
) -> CustomResult<Self, errors::CryptoError> {
let encrypted = encrypted_data.into_inner();
+ let data = crypt_algo.decode_message(key, encrypted.clone())?;
- let (data, encrypted) = if timestamp < migration_timestamp {
- (
- encrypted.clone(),
- crypt_algo.encode_message(key, &encrypted)?,
- )
- } else {
- (
- crypt_algo.decode_message(key, encrypted.clone())?,
- encrypted,
- )
- };
Ok(Self::new(data.into(), encrypted))
}
}
@@ -241,7 +203,7 @@ where
crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>,
{
request::record_operation_time(
- crypto::Encryptable::encrypt(inner, key, crypto::GcmAes256 {}),
+ crypto::Encryptable::encrypt(inner, key, crypto::GcmAes256),
&ENCRYPTION_TIME,
)
.await
@@ -264,22 +226,12 @@ where
pub async fn decrypt<T: Clone, S: masking::Strategy<T>>(
inner: Option<Encryption>,
key: &[u8],
- timestamp: i64,
- migration_timestamp: i64,
) -> CustomResult<Option<crypto::Encryptable<Secret<T, S>>>, errors::CryptoError>
where
crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>,
{
request::record_operation_time(
- inner.async_map(|item| {
- crypto::Encryptable::decrypt(
- item,
- key,
- crypto::GcmAes256 {},
- timestamp,
- migration_timestamp,
- )
- }),
+ inner.async_map(|item| crypto::Encryptable::decrypt(item, key, crypto::GcmAes256)),
&DECRYPTION_TIME,
)
.await
|
refactor
|
remove `pii-encryption-script` feature and use of timestamps for decryption (#1350)
|
177fe1b8929260c5ee14f768eae4b7b29ad073ed
|
2024-05-02 05:44:16
|
github-actions
|
chore(version): 2024.05.02.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e6973b1db0e..765cf9e84ef 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,34 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 2024.05.02.0
+
+### Features
+
+- **FRM:** Add shipping details for signifyd ([#4500](https://github.com/juspay/hyperswitch/pull/4500)) ([`bda749d`](https://github.com/juspay/hyperswitch/commit/bda749d097ee9cfe80bc509491bec229da3725c3))
+- Add support for merchant to pass public key and ttl for encrypting payload ([#4456](https://github.com/juspay/hyperswitch/pull/4456)) ([`b562e62`](https://github.com/juspay/hyperswitch/commit/b562e62ac895c34574bcc8c3fcce8e5b49d0f923))
+- Add an api for retrieving the extended card info from redis ([#4484](https://github.com/juspay/hyperswitch/pull/4484)) ([`dfa4b50`](https://github.com/juspay/hyperswitch/commit/dfa4b50dbd5cfc927fbbd6a68725d2c51625e6d1))
+
+### Bug Fixes
+
+- **access_token:** Use fallback to `connector_name` if `merchant_connector_id` is not present ([#4503](https://github.com/juspay/hyperswitch/pull/4503)) ([`632a00c`](https://github.com/juspay/hyperswitch/commit/632a00cb6803e3e6f94099e48fb4198a0ea49f99))
+- **connector:** Send valid sdk information in authentication flow netcetera ([#4474](https://github.com/juspay/hyperswitch/pull/4474)) ([`8f0d4d4`](https://github.com/juspay/hyperswitch/commit/8f0d4d4191bb96efd8700fb115d91213c2872ad8))
+- **euclid_wasm:** Connector config wasm metadata update ([#4460](https://github.com/juspay/hyperswitch/pull/4460)) ([`28df646`](https://github.com/juspay/hyperswitch/commit/28df646830f544179b7cf00eb8f51de2a606bdbc))
+
+### Refactors
+
+- **core:** Remove payment_method_id from RouterData struct ([#4485](https://github.com/juspay/hyperswitch/pull/4485)) ([`3077a0d`](https://github.com/juspay/hyperswitch/commit/3077a0d31e8d36f18e359f1edf9a742969601f6b))
+- **cypress:** Read creds from env instead of hardcoding the path ([#4430](https://github.com/juspay/hyperswitch/pull/4430)) ([`0c9ba1e`](https://github.com/juspay/hyperswitch/commit/0c9ba1e848c757cf3e0708f2ed4694259a5344aa))
+- **user:** Deprecate Signin, Verify email and Invite v1 APIs ([#4465](https://github.com/juspay/hyperswitch/pull/4465)) ([`b0133f3`](https://github.com/juspay/hyperswitch/commit/b0133f33693575f2145d295eff78dd07b61efcda))
+
+### Miscellaneous Tasks
+
+- Make client certificate and private key secret across codebase ([#4490](https://github.com/juspay/hyperswitch/pull/4490)) ([`dd7b10a`](https://github.com/juspay/hyperswitch/commit/dd7b10a8bdad4c509a4fbae429f3abd21a5d6758))
+
+**Full Changelog:** [`2024.04.30.0...2024.05.02.0`](https://github.com/juspay/hyperswitch/compare/2024.04.30.0...2024.05.02.0)
+
+- - -
+
## 2024.04.30.0
### Features
|
chore
|
2024.05.02.0
|
af0d2a8cbdbf8526520da0c3b75c4b0e07cd905e
|
2024-09-24 17:38:36
|
Amisha Prabhat
|
refactor(core): add connector mandate id in `payments_response` based on merchant config (#5999)
| false
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index cf930f4b4ea..99462e95e07 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -14100,6 +14100,11 @@
}
],
"nullable": true
+ },
+ "connector_mandate_id": {
+ "type": "string",
+ "description": "Connector Identifier for the payment method",
+ "nullable": true
}
}
},
@@ -15254,6 +15259,11 @@
}
],
"nullable": true
+ },
+ "connector_mandate_id": {
+ "type": "string",
+ "description": "Connector Identifier for the payment method",
+ "nullable": true
}
}
},
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json
index 75e240cff7d..f5f01c8c49c 100644
--- a/api-reference/openapi_spec.json
+++ b/api-reference/openapi_spec.json
@@ -17424,6 +17424,11 @@
}
],
"nullable": true
+ },
+ "connector_mandate_id": {
+ "type": "string",
+ "description": "Connector Identifier for the payment method",
+ "nullable": true
}
}
},
@@ -18578,6 +18583,11 @@
}
],
"nullable": true
+ },
+ "connector_mandate_id": {
+ "type": "string",
+ "description": "Connector Identifier for the payment method",
+ "nullable": true
}
}
},
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index a2ae6e950f6..c1cd995b725 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -4217,6 +4217,9 @@ pub struct PaymentsResponse {
pub merchant_order_reference_id: Option<String>,
/// order tax amount calculated by tax connectors
pub order_tax_amount: Option<MinorUnit>,
+
+ /// Connector Identifier for the payment method
+ pub connector_mandate_id: Option<String>,
}
/// Fee information to be charged on the payment being collected
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index e0324438b48..538f6d70c4f 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -14,7 +14,7 @@ use router_env::{instrument, logger, metrics::add_attributes, tracing};
use storage_impl::DataModelExt;
use tracing_futures::Instrument;
-use super::{Operation, PostUpdateTracker};
+use super::{Operation, OperationSessionSetters, PostUpdateTracker};
use crate::{
connector::utils::PaymentResponseRouterData,
consts,
@@ -198,7 +198,9 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
if is_legacy_mandate {
// Mandate is created on the application side and at the connector.
- let (payment_method_id, _payment_method_status) = save_payment_call_future.await?;
+ let tokenization::SavePaymentMethodDataResponse {
+ payment_method_id, ..
+ } = save_payment_call_future.await?;
let mandate_id = mandate::mandate_procedure(
state,
@@ -212,11 +214,22 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
.await?;
payment_data.payment_attempt.payment_method_id = payment_method_id;
payment_data.payment_attempt.mandate_id = mandate_id;
+
Ok(())
} else if is_connector_mandate {
// The mandate is created on connector's end.
- let (payment_method_id, _payment_method_status) = save_payment_call_future.await?;
+ let tokenization::SavePaymentMethodDataResponse {
+ payment_method_id,
+ mandate_reference_id,
+ ..
+ } = save_payment_call_future.await?;
+
payment_data.payment_attempt.payment_method_id = payment_method_id;
+
+ payment_data.set_mandate_id(api_models::payments::MandateIds {
+ mandate_id: None,
+ mandate_reference_id,
+ });
Ok(())
} else if should_avoid_saving {
if let Some(pm_info) = &payment_data.payment_method_info {
@@ -266,7 +279,11 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
if let Err(err) = result {
logger::error!("Asynchronously saving card in locker failed : {:?}", err);
- } else if let Ok((payment_method_id, _pm_status)) = result {
+ } else if let Ok(tokenization::SavePaymentMethodDataResponse {
+ payment_method_id,
+ ..
+ }) = result
+ {
let payment_attempt_update =
storage::PaymentAttemptUpdate::PaymentMethodDetailsUpdate {
payment_method_id,
@@ -828,23 +845,24 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestDa
}
})?;
let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone();
- let (payment_method_id, _payment_method_status) =
- Box::pin(tokenization::save_payment_method(
- state,
- connector_name,
- merchant_connector_id.clone(),
- save_payment_data,
- customer_id.clone(),
- merchant_account,
- resp.request.payment_method_type,
- key_store,
- resp.request.amount,
- Some(resp.request.currency),
- billing_name,
- None,
- business_profile,
- ))
- .await?;
+ let tokenization::SavePaymentMethodDataResponse {
+ payment_method_id, ..
+ } = Box::pin(tokenization::save_payment_method(
+ state,
+ connector_name,
+ merchant_connector_id.clone(),
+ save_payment_data,
+ customer_id.clone(),
+ merchant_account,
+ resp.request.payment_method_type,
+ key_store,
+ resp.request.amount,
+ Some(resp.request.currency),
+ billing_name,
+ None,
+ business_profile,
+ ))
+ .await?;
let mandate_id = mandate::mandate_procedure(
state,
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index ca8c6718aa7..6815d2dfc4f 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -5,6 +5,7 @@ use std::collections::HashMap;
not(feature = "payment_methods_v2")
))]
use api_models::payment_methods::PaymentMethodsData;
+use api_models::payments::{ConnectorMandateReferenceId, MandateReferenceId};
use common_enums::PaymentMethod;
use common_utils::{
crypto::Encryptable,
@@ -57,7 +58,11 @@ impl<F, Req: Clone> From<&types::RouterData<F, Req, types::PaymentsResponseData>
}
}
}
-
+pub struct SavePaymentMethodDataResponse {
+ pub payment_method_id: Option<String>,
+ pub payment_method_status: Option<common_enums::PaymentMethodStatus>,
+ pub mandate_reference_id: Option<MandateReferenceId>,
+}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
@@ -78,7 +83,7 @@ pub async fn save_payment_method<FData>(
billing_name: Option<Secret<String>>,
payment_method_billing_address: Option<&api::Address>,
business_profile: &domain::Profile,
-) -> RouterResult<(Option<String>, Option<common_enums::PaymentMethodStatus>)>
+) -> RouterResult<SavePaymentMethodDataResponse>
where
FData: mandate::MandateBehaviour + Clone,
{
@@ -737,9 +742,36 @@ where
} else {
None
};
- Ok((pm_id, pm_status))
+ let cmid_config = db
+ .find_config_by_key_unwrap_or(
+ format!("{}_should_show_connector_mandate_id_in_payments_response", merchant_account.get_id().get_string_repr().to_owned()).as_str(),
+ Some("false".to_string()),
+ )
+ .await.map_err(|err| services::logger::error!(message="Failed to fetch the config", connector_mandate_details_population=?err)).ok();
+
+ let mandate_reference_id = match cmid_config {
+ Some(config) if config.config == "true" => Some(
+ MandateReferenceId::ConnectorMandateId(ConnectorMandateReferenceId {
+ connector_mandate_id: connector_mandate_id.clone(),
+ payment_method_id: pm_id.clone(),
+ update_history: None,
+ mandate_metadata: mandate_metadata.clone(),
+ }),
+ ),
+ _ => None,
+ };
+
+ Ok(SavePaymentMethodDataResponse {
+ payment_method_id: pm_id,
+ payment_method_status: pm_status,
+ mandate_reference_id,
+ })
}
- Err(_) => Ok((None, None)),
+ Err(_) => Ok(SavePaymentMethodDataResponse {
+ payment_method_id: None,
+ payment_method_status: None,
+ mandate_reference_id: None,
+ }),
}
}
@@ -761,7 +793,7 @@ pub async fn save_payment_method<FData>(
_billing_name: Option<Secret<String>>,
_payment_method_billing_address: Option<&api::Address>,
_business_profile: &domain::Profile,
-) -> RouterResult<(Option<String>, Option<common_enums::PaymentMethodStatus>)>
+) -> RouterResult<SavePaymentMethodDataResponse>
where
FData: mandate::MandateBehaviour + Clone,
{
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index d8c5f88dde9..6b84ceb9759 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -1128,6 +1128,17 @@ where
.or_else(|| tax.default.map(|a| a.order_tax_amount))
})
});
+ let connector_mandate_id = payment_data.get_mandate_id().and_then(|mandate| {
+ mandate
+ .mandate_reference_id
+ .as_ref()
+ .and_then(|mandate_ref| match mandate_ref {
+ api_models::payments::MandateReferenceId::ConnectorMandateId(
+ connector_mandate_reference_id,
+ ) => connector_mandate_reference_id.connector_mandate_id.clone(),
+ _ => None,
+ })
+ });
let payments_response = api::PaymentsResponse {
payment_id: payment_intent.payment_id,
@@ -1227,6 +1238,7 @@ where
frm_metadata: payment_intent.frm_metadata,
merchant_order_reference_id: payment_intent.merchant_order_reference_id,
order_tax_amount,
+ connector_mandate_id,
};
services::ApplicationResponse::JsonWithHeaders((payments_response, headers))
@@ -1480,6 +1492,7 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay
charges: None,
frm_metadata: None,
order_tax_amount: None,
+ connector_mandate_id:None,
}
}
}
diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs
index 11d7b644c07..435e39acae1 100644
--- a/crates/router/tests/payments.rs
+++ b/crates/router/tests/payments.rs
@@ -445,6 +445,7 @@ async fn payments_create_core() {
frm_metadata: None,
merchant_order_reference_id: None,
order_tax_amount: None,
+ connector_mandate_id: None,
};
let expected_response =
services::ApplicationResponse::JsonWithHeaders((expected_response, vec![]));
@@ -702,6 +703,7 @@ async fn payments_create_core_adyen_no_redirect() {
frm_metadata: None,
merchant_order_reference_id: None,
order_tax_amount: None,
+ connector_mandate_id: None,
},
vec![],
));
diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs
index 28759f7111c..b6c22c469d4 100644
--- a/crates/router/tests/payments2.rs
+++ b/crates/router/tests/payments2.rs
@@ -206,7 +206,9 @@ async fn payments_create_core() {
frm_metadata: None,
merchant_order_reference_id: None,
order_tax_amount: None,
+ connector_mandate_id: None,
};
+
let expected_response =
services::ApplicationResponse::JsonWithHeaders((expected_response, vec![]));
let actual_response = Box::pin(payments::payments_core::<
@@ -471,6 +473,7 @@ async fn payments_create_core_adyen_no_redirect() {
frm_metadata: None,
merchant_order_reference_id: None,
order_tax_amount: None,
+ connector_mandate_id: None,
},
vec![],
));
|
refactor
|
add connector mandate id in `payments_response` based on merchant config (#5999)
|
8f6583fbeeb7ab7ac31566adf9d182a839ed9a51
|
2023-08-02 18:15:18
|
Sarthak Soni
|
refactor(common_enums): Added derive for additional traits in FutureU… (#1848)
| false
|
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index cb599d105be..dc1840b79d5 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -764,10 +764,13 @@ pub enum IntentStatus {
Debug,
Default,
Eq,
+ Hash,
PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
+ strum::EnumVariantNames,
+ strum::EnumIter,
strum::EnumString,
ToSchema,
)]
|
refactor
|
Added derive for additional traits in FutureU… (#1848)
|
b60ced02ffba21624a9491a63fcde1c04cfa0b06
|
2024-08-21 14:53:10
|
Hrithikesh
|
feat: use admin_api_key auth along with merchant_id for connector list, retrieve and update apis (#5613)
| false
|
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index 353be92163c..46b679f0508 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -434,7 +434,7 @@ pub async fn connector_retrieve(
)
},
auth::auth_type(
- &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::AdminApiAuthWithMerchantId::default(),
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantConnectorAccountRead,
@@ -533,7 +533,7 @@ pub async fn payment_connector_list(
merchant_id.to_owned(),
|state, _auth, merchant_id, _| list_payment_connectors(state, merchant_id, None),
auth::auth_type(
- &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::AdminApiAuthWithMerchantId::default(),
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantConnectorAccountRead,
@@ -593,7 +593,7 @@ pub async fn connector_update(
)
},
auth::auth_type(
- &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::AdminApiAuthWithMerchantId::default(),
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantConnectorAccountWrite,
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 30857f797fb..4ac2c02c94c 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -37,6 +37,7 @@ use crate::{
api_keys,
errors::{self, utils::StorageErrorExt, RouterResult},
},
+ headers,
routes::app::SessionStateInfo,
services::api,
types::domain,
@@ -76,6 +77,9 @@ pub enum AuthenticationType {
key_id: String,
},
AdminApiKey,
+ AdminApiAuthWithMerchantId {
+ merchant_id: id_type::MerchantId,
+ },
MerchantJwt {
merchant_id: id_type::MerchantId,
user_id: Option<String>,
@@ -122,6 +126,7 @@ impl AuthenticationType {
merchant_id,
key_id: _,
}
+ | Self::AdminApiAuthWithMerchantId { merchant_id }
| Self::MerchantId { merchant_id }
| Self::PublishableKey { merchant_id }
| Self::MerchantJwt {
@@ -655,7 +660,7 @@ where
}
}
-#[derive(Debug)]
+#[derive(Debug, Default)]
pub struct AdminApiAuth;
#[async_trait]
@@ -683,6 +688,81 @@ where
}
}
+#[derive(Debug, Default)]
+pub struct AdminApiAuthWithMerchantId(AdminApiAuth);
+
+#[async_trait]
+impl<A> AuthenticateAndFetch<AuthenticationData, A> for AdminApiAuthWithMerchantId
+where
+ A: SessionStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {
+ self.0
+ .authenticate_and_fetch(request_headers, state)
+ .await?;
+ let merchant_id =
+ get_header_value_by_key(headers::X_MERCHANT_ID.to_string(), request_headers)?
+ .get_required_value(headers::X_MERCHANT_ID)
+ .change_context(errors::ApiErrorResponse::InvalidRequestData {
+ message: format!("`{}` header is missing", headers::X_MERCHANT_ID),
+ })
+ .and_then(|merchant_id_str| {
+ id_type::MerchantId::try_from(std::borrow::Cow::from(
+ merchant_id_str.to_string(),
+ ))
+ .change_context(
+ errors::ApiErrorResponse::InvalidRequestData {
+ message: format!("`{}` header is invalid", headers::X_MERCHANT_ID),
+ },
+ )
+ })?;
+ let key_manager_state = &(&state.session_state()).into();
+ let key_store = state
+ .store()
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
+ &merchant_id,
+ &state.store().get_master_key().to_vec().into(),
+ )
+ .await
+ .map_err(|e| {
+ if e.current_context().is_db_not_found() {
+ e.change_context(errors::ApiErrorResponse::Unauthorized)
+ } else {
+ e.change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to fetch merchant key store for the merchant id")
+ }
+ })?;
+
+ let merchant = state
+ .store()
+ .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
+ .await
+ .map_err(|e| {
+ if e.current_context().is_db_not_found() {
+ e.change_context(errors::ApiErrorResponse::Unauthorized)
+ } else {
+ e.change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to fetch merchant account for the merchant id")
+ }
+ })?;
+
+ let auth = AuthenticationData {
+ merchant_account: merchant,
+ key_store,
+ profile_id: None,
+ };
+ Ok((
+ auth,
+ AuthenticationType::AdminApiAuthWithMerchantId { merchant_id },
+ ))
+ }
+}
+
#[derive(Debug)]
pub struct EphemeralKeyAuth;
@@ -1425,7 +1505,7 @@ pub fn is_ephemeral_auth<A: SessionStateInfo + Sync + Send>(
}
pub fn is_jwt_auth(headers: &HeaderMap) -> bool {
- headers.get(crate::headers::AUTHORIZATION).is_some()
+ headers.get(headers::AUTHORIZATION).is_some()
|| get_cookie_from_header(headers)
.and_then(cookies::parse_cookie)
.is_ok()
@@ -1465,8 +1545,8 @@ pub fn get_header_value_by_key(key: String, headers: &HeaderMap) -> RouterResult
pub fn get_jwt_from_authorization_header(headers: &HeaderMap) -> RouterResult<&str> {
headers
- .get(crate::headers::AUTHORIZATION)
- .get_required_value(crate::headers::AUTHORIZATION)?
+ .get(headers::AUTHORIZATION)
+ .get_required_value(headers::AUTHORIZATION)?
.to_str()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert JWT token to string")?
diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.js
index bc23934efc1..3affe123db8 100644
--- a/cypress-tests/cypress/support/commands.js
+++ b/cypress-tests/cypress/support/commands.js
@@ -484,7 +484,8 @@ Cypress.Commands.add("connectorRetrieveCall", (globalState) => {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
- "api-key": globalState.get("apiKey"),
+ "api-key": globalState.get("adminApiKey"),
+ "x-merchant-id": merchant_id,
},
failOnStatusCode: false,
}).then((response) => {
@@ -530,7 +531,8 @@ Cypress.Commands.add(
headers: {
Accept: "application/json",
"Content-Type": "application/json",
- "api-key": globalState.get("apiKey"),
+ "api-key": globalState.get("adminApiKey"),
+ "x-merchant-id": merchant_id,
},
body: updateConnectorBody,
failOnStatusCode: false,
@@ -554,7 +556,8 @@ Cypress.Commands.add("connectorListByMid", (globalState) => {
url: `${globalState.get("baseUrl")}/account/${merchant_id}/connectors`,
headers: {
"Content-Type": "application/json",
- "api-key": globalState.get("apiKey"),
+ "api-key": globalState.get("adminApiKey"),
+ "X-Merchant-Id": merchant_id,
},
failOnStatusCode: false,
}).then((response) => {
@@ -2062,7 +2065,8 @@ Cypress.Commands.add("ListMCAbyMID", (globalState) => {
url: `${globalState.get("baseUrl")}/account/${merchantId}/connectors`,
headers: {
"Content-Type": "application/json",
- "api-key": globalState.get("apiKey"),
+ "api-key": globalState.get("adminApiKey"),
+ "X-Merchant-Id": merchantId,
},
failOnStatusCode: false,
}).then((response) => {
diff --git a/postman/collection-dir/stripe/PaymentConnectors/.meta.json b/postman/collection-dir/stripe/PaymentConnectors/.meta.json
index 198acc6d532..3f8bc360dd4 100644
--- a/postman/collection-dir/stripe/PaymentConnectors/.meta.json
+++ b/postman/collection-dir/stripe/PaymentConnectors/.meta.json
@@ -1,6 +1,5 @@
{
"childrenOrder": [
- "API Key - Create",
"Payment Connector - Create",
"Payment Connector - Retrieve",
"Payment Connector - Update",
diff --git a/postman/collection-dir/stripe/PaymentConnectors/API Key - Create/.event.meta.json b/postman/collection-dir/stripe/PaymentConnectors/API Key - Create/.event.meta.json
deleted file mode 100644
index 0731450e6b2..00000000000
--- a/postman/collection-dir/stripe/PaymentConnectors/API Key - Create/.event.meta.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "eventOrder": ["event.test.js"]
-}
diff --git a/postman/collection-dir/stripe/PaymentConnectors/API Key - Create/event.test.js b/postman/collection-dir/stripe/PaymentConnectors/API Key - Create/event.test.js
deleted file mode 100644
index 4e27c5a5025..00000000000
--- a/postman/collection-dir/stripe/PaymentConnectors/API Key - Create/event.test.js
+++ /dev/null
@@ -1,46 +0,0 @@
-// Validate status 2xx
-pm.test("[POST]::/api_keys/:merchant_id - Status code is 2xx", function () {
- pm.response.to.be.success;
-});
-
-// Validate if response header has matching content-type
-pm.test(
- "[POST]::/api_keys/:merchant_id - Content-Type is application/json",
- function () {
- pm.expect(pm.response.headers.get("Content-Type")).to.include(
- "application/json",
- );
- },
-);
-
-// Set response object as internal variable
-let jsonData = {};
-try {
- jsonData = pm.response.json();
-} catch (e) {}
-
-// pm.collectionVariables - Set api_key_id as variable for jsonData.key_id
-if (jsonData?.key_id) {
- pm.collectionVariables.set("api_key_id", jsonData.key_id);
- console.log(
- "- use {{api_key_id}} as collection variable for value",
- jsonData.key_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{api_key_id}}, as jsonData.key_id is undefined.",
- );
-}
-
-// pm.collectionVariables - Set api_key as variable for jsonData.api_key
-if (jsonData?.api_key) {
- pm.collectionVariables.set("api_key", jsonData.api_key);
- console.log(
- "- use {{api_key}} as collection variable for value",
- jsonData.api_key,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.",
- );
-}
diff --git a/postman/collection-dir/stripe/PaymentConnectors/API Key - Create/request.json b/postman/collection-dir/stripe/PaymentConnectors/API Key - Create/request.json
deleted file mode 100644
index 6ceefe5d24c..00000000000
--- a/postman/collection-dir/stripe/PaymentConnectors/API Key - Create/request.json
+++ /dev/null
@@ -1,47 +0,0 @@
-{
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{admin_api_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- }
- ]
- },
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "raw_json_formatted": {
- "name": "API Key 1",
- "description": null,
- "expiration": "2069-09-23T01:02:03.000Z"
- }
- },
- "url": {
- "raw": "{{baseUrl}}/api_keys/:merchant_id",
- "host": ["{{baseUrl}}"],
- "path": ["api_keys", ":merchant_id"],
- "variable": [
- {
- "key": "merchant_id",
- "value": "{{merchant_id}}"
- }
- ]
- }
-}
diff --git a/postman/collection-dir/stripe/PaymentConnectors/API Key - Create/response.json b/postman/collection-dir/stripe/PaymentConnectors/API Key - Create/response.json
deleted file mode 100644
index fe51488c706..00000000000
--- a/postman/collection-dir/stripe/PaymentConnectors/API Key - Create/response.json
+++ /dev/null
@@ -1 +0,0 @@
-[]
diff --git a/postman/collection-dir/stripe/PaymentConnectors/List Connectors by MID/request.json b/postman/collection-dir/stripe/PaymentConnectors/List Connectors by MID/request.json
index f731ff3a422..e3ed8ab2925 100644
--- a/postman/collection-dir/stripe/PaymentConnectors/List Connectors by MID/request.json
+++ b/postman/collection-dir/stripe/PaymentConnectors/List Connectors by MID/request.json
@@ -4,7 +4,7 @@
"apikey": [
{
"key": "value",
- "value": "{{api_key}}",
+ "value": "{{admin_api_key}}",
"type": "string"
},
{
@@ -19,6 +19,10 @@
{
"key": "Content-Type",
"value": "application/json"
+ },
+ {
+ "key": "x-merchant-id",
+ "value": "{{merchant_id}}"
}
],
"url": {
diff --git a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Retrieve/request.json b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Retrieve/request.json
index 05f84b5771e..97afd9f26e7 100644
--- a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Retrieve/request.json
+++ b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Retrieve/request.json
@@ -4,7 +4,7 @@
"apikey": [
{
"key": "value",
- "value": "{{api_key}}",
+ "value": "{{admin_api_key}}",
"type": "string"
},
{
@@ -24,6 +24,10 @@
{
"key": "Accept",
"value": "application/json"
+ },
+ {
+ "key": "x-merchant-id",
+ "value": "{{merchant_id}}"
}
],
"url": {
diff --git a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Update/request.json b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Update/request.json
index bcc133ce436..f9631103356 100644
--- a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Update/request.json
+++ b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Update/request.json
@@ -4,7 +4,7 @@
"apikey": [
{
"key": "value",
- "value": "{{api_key}}",
+ "value": "{{admin_api_key}}",
"type": "string"
},
{
@@ -28,6 +28,10 @@
{
"key": "Accept",
"value": "application/json"
+ },
+ {
+ "key": "x-merchant-id",
+ "value": "{{merchant_id}}"
}
],
"body": {
diff --git a/postman/collection-dir/stripe/QuickStart/Payment Connector - Update/request.json b/postman/collection-dir/stripe/QuickStart/Payment Connector - Update/request.json
index 8b46ad180ff..84c7a2fa48c 100644
--- a/postman/collection-dir/stripe/QuickStart/Payment Connector - Update/request.json
+++ b/postman/collection-dir/stripe/QuickStart/Payment Connector - Update/request.json
@@ -4,7 +4,7 @@
"apikey": [
{
"key": "value",
- "value": "{{api_key}}",
+ "value": "{{admin_api_key}}",
"type": "string"
},
{
@@ -28,6 +28,10 @@
{
"key": "Accept",
"value": "application/json"
+ },
+ {
+ "key": "x-merchant-id",
+ "value": "{{merchant_id}}"
}
],
"body": {
diff --git a/postman/collection-json/stripe.postman_collection.json b/postman/collection-json/stripe.postman_collection.json
index c3e3c6f1588..329b444a41f 100644
--- a/postman/collection-json/stripe.postman_collection.json
+++ b/postman/collection-json/stripe.postman_collection.json
@@ -1348,115 +1348,6 @@
}
]
},
- {
- "name": "API Key - Create",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[POST]::/api_keys/:merchant_id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(",
- " \"[POST]::/api_keys/:merchant_id - Content-Type is application/json\",",
- " function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- " },",
- ");",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set api_key_id as variable for jsonData.key_id",
- "if (jsonData?.key_id) {",
- " pm.collectionVariables.set(\"api_key_id\", jsonData.key_id);",
- " console.log(",
- " \"- use {{api_key_id}} as collection variable for value\",",
- " jsonData.key_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{api_key_id}}, as jsonData.key_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set api_key as variable for jsonData.api_key",
- "if (jsonData?.api_key) {",
- " pm.collectionVariables.set(\"api_key\", jsonData.api_key);",
- " console.log(",
- " \"- use {{api_key}} as collection variable for value\",",
- " jsonData.api_key,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.\",",
- " );",
- "}",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{admin_api_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- }
- ]
- },
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"name\":\"API Key 1\",\"description\":null,\"expiration\":\"2069-09-23T01:02:03.000Z\"}"
- },
- "url": {
- "raw": "{{baseUrl}}/api_keys/:merchant_id",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "api_keys",
- ":merchant_id"
- ],
- "variable": [
- {
- "key": "merchant_id",
- "value": "{{merchant_id}}"
- }
- ]
- }
- },
- "response": []
- },
{
"name": "Payment Connector - Create",
"event": [
@@ -1637,7 +1528,7 @@
"apikey": [
{
"key": "value",
- "value": "{{api_key}}",
+ "value": "{{admin_api_key}}",
"type": "string"
},
{
@@ -1657,6 +1548,10 @@
{
"key": "Accept",
"value": "application/json"
+ },
+ {
+ "key": "x-merchant-id",
+ "value": "{{merchant_id}}"
}
],
"url": {
@@ -1752,7 +1647,7 @@
"apikey": [
{
"key": "value",
- "value": "{{api_key}}",
+ "value": "{{admin_api_key}}",
"type": "string"
},
{
@@ -1776,6 +1671,10 @@
{
"key": "Accept",
"value": "application/json"
+ },
+ {
+ "key": "x-merchant-id",
+ "value": "{{merchant_id}}"
}
],
"body": {
@@ -1849,7 +1748,7 @@
"apikey": [
{
"key": "value",
- "value": "{{api_key}}",
+ "value": "{{admin_api_key}}",
"type": "string"
},
{
@@ -1864,6 +1763,10 @@
{
"key": "Content-Type",
"value": "application/json"
+ },
+ {
+ "key": "x-merchant-id",
+ "value": "{{merchant_id}}"
}
],
"url": {
@@ -2684,7 +2587,7 @@
"apikey": [
{
"key": "value",
- "value": "{{api_key}}",
+ "value": "{{admin_api_key}}",
"type": "string"
},
{
@@ -2708,6 +2611,10 @@
{
"key": "Accept",
"value": "application/json"
+ },
+ {
+ "key": "x-merchant-id",
+ "value": "{{merchant_id}}"
}
],
"body": {
|
feat
|
use admin_api_key auth along with merchant_id for connector list, retrieve and update apis (#5613)
|
1cfe3632a70115da74469b88624b4bdb5abfe5c4
|
2023-08-07 08:21:17
|
github-actions
|
chore(version): v1.17.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 255319de78d..a2a7593896b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,26 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 1.17.0 (2023-08-07)
+
+### Features
+
+- **config:** Add config support to pt_mapping along with redis ([#1861](https://github.com/juspay/hyperswitch/pull/1861)) ([`b03dd24`](https://github.com/juspay/hyperswitch/commit/b03dd244561641f5b3481c79035766561bcd0a8a))
+- **connector:** [Payme] Add Sync, RSync & webhook flow support ([#1862](https://github.com/juspay/hyperswitch/pull/1862)) ([`8057980`](https://github.com/juspay/hyperswitch/commit/80579805f9dd7c387eb3c0b5c48e01fa69e48299))
+
+### Bug Fixes
+
+- **core:** If frm is not called, send None in frm_message instead of initial values in update tracker ([#1867](https://github.com/juspay/hyperswitch/pull/1867)) ([`3250204`](https://github.com/juspay/hyperswitch/commit/3250204acc1e32f92dad725378b19dd3e4da33f6))
+
+### Revert
+
+- Fix(core): add validation for all the connector auth_type ([#1833](https://github.com/juspay/hyperswitch/pull/1833)) ([`ae3d25e`](https://github.com/juspay/hyperswitch/commit/ae3d25e6899af0d78171d40c980146d58f8fc03f))
+
+**Full Changelog:** [`v1.16.0...v1.17.0`](https://github.com/juspay/hyperswitch/compare/v1.16.0...v1.17.0)
+
+- - -
+
+
## 1.16.0 (2023-08-04)
### Features
|
chore
|
v1.17.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.